问:
How is inter module dependencies achieved in wildfly swarm
How is inter module dependencies achieved in wildfly swarm?

For example, I have a module with these contents:

```<code>    <module xmlns="urn:jboss:module:1.3" name="com.obbi.domain.security">
      <resources>
       <artifact name="com.obbi.domain.platform:domain-service-security-jboss:2.0.86"/>
       <artifact name="com.obbi.domain.platform:domain-service-security-client:2.0.86"/>
      </resources>
      <dependencies>
       <module name="org.jboss.as.web"/>
       <module name="org.jboss.logging"/>
       <module name="org.picketbox"/>
       <module name="javax.api"/>
       <module name="javax.security.auth.message.api"/>
       <module name="javax.servlet.api"/>
      </dependencies>
    </module>

At runtime, when I try to access my application, it fails because it can't find the dependencies specified in the module.

2017-07-05 16:58:50,312 ERROR [io.undertow.request] (default task-1) UT005023: Exception handling request to /Test/rest/Ping: java.lang.NoClassDefFoundError: org/jose4j/json/internal/json_simple/parser/ParseException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
at java.lang.Class.getConstructor0(Class.java:3075)
at java.lang.Class.getConstructor(Class.java:1825)
at org.jboss.security.auth.message.config.JBossServerAuthConfig.createSAM(JBossServerAuthConfig.java:244)
at org.jboss.security.auth.message.config.JBossServerAuthConfig.getAuthContext(JBossServerAuthConfig.java:178)
at org.jboss.security.plugins.auth.JASPIServerAuthenticationManager.secureResponse(JASPIServerAuthenticationManager.java:158)
at org.wildfly.extension.undertow.security.jaspi.JASPICSecureResponseHandler.handleRequest(JASPICSecureResponseHandler.java:35)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:211)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:809)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Caused by: java.lang.ClassNotFoundException: org.jose4j.json.internal.json_simple.parser.ParseException from [Module "com.obbi.domain.security:main" from BootModuleLoader@752325ad for finders [BootstrapClasspathModuleFinder, BootstrapModuleFinder(org.wildfly.swarm.bootstrap:main), ClasspathModuleFinder, ContainerModuleFinder(swarm.container:main), ApplicationModuleFinder(swarm.application:main), org.wildfly.swarm.bootstrap.modules.DynamicModuleFinder@279fedbd]]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
... 28 more
</code>```

I have tried copying the dependencies modules from the normal wildfly modules directory into the wildfly swarm resources, but the issue persists.

So how are these dependencies within the module configured?

Regards

答:
I had to include

```<code><artifact name="org.bitbucket.b_c:jose4j:0.5.0"/>
</code>```

in my module.xml, as well as

```<code><dependency>
    <groupId>org.bitbucket.b_c</groupId>
    <artifactId>jose4j</artifactId>
    <version>0.5.0</version>
</dependency>
</code>```

in my POM.

The issue had nothing to do with inter module dependencies

Body:
How is inter module dependencies achieved in wildfly swarm?

For example, I have a module with these contents:

    <module xmlns="urn:jboss:module:1.3" name="com.obbi.domain.security">
      <resources>
       <artifact name="com.obbi.domain.platform:domain-service-security-jboss:2.0.86"/>
       <artifact name="com.obbi.domain.platform:domain-service-security-client:2.0.86"/>
      </resources>
      <dependencies>
       <module name="org.jboss.as.web"/>
       <module name="org.jboss.logging"/>
       <module name="org.picketbox"/>
       <module name="javax.api"/>
       <module name="javax.security.auth.message.api"/>
       <module name="javax.servlet.api"/>
      </dependencies>
    </module>

At runtime, when I try to access my application, it fails because it can't find the dependencies specified in the module.

2017-07-05 16:58:50,312 ERROR [io.undertow.request] (default task-1) UT005023: Exception handling request to /Test/rest/Ping: java.lang.NoClassDefFoundError: org/jose4j/json/internal/json_simple/parser/ParseException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
at java.lang.Class.getConstructor0(Class.java:3075)
at java.lang.Class.getConstructor(Class.java:1825)
at org.jboss.security.auth.message.config.JBossServerAuthConfig.createSAM(JBossServerAuthConfig.java:244)
at org.jboss.security.auth.message.config.JBossServerAuthConfig.getAuthContext(JBossServerAuthConfig.java:178)
at org.jboss.security.plugins.auth.JASPIServerAuthenticationManager.secureResponse(JASPIServerAuthenticationManager.java:158)
at org.wildfly.extension.undertow.security.jaspi.JASPICSecureResponseHandler.handleRequest(JASPICSecureResponseHandler.java:35)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:211)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:809)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Caused by: java.lang.ClassNotFoundException: org.jose4j.json.internal.json_simple.parser.ParseException from [Module "com.obbi.domain.security:main" from BootModuleLoader@752325ad for finders [BootstrapClasspathModuleFinder, BootstrapModuleFinder(org.wildfly.swarm.bootstrap:main), ClasspathModuleFinder, ContainerModuleFinder(swarm.container:main), ApplicationModuleFinder(swarm.application:main), org.wildfly.swarm.bootstrap.modules.DynamicModuleFinder@279fedbd]]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
... 28 more

I have tried copying the dependencies modules from the normal wildfly modules directory into the wildfly swarm resources, but the issue persists.

So how are these dependencies within the module configured?

Regards

Body:
I had to include

<artifact name="org.bitbucket.b_c:jose4j:0.5.0"/>

in my module.xml, as well as

<dependency>
    <groupId>org.bitbucket.b_c</groupId>
    <artifactId>jose4j</artifactId>
    <version>0.5.0</version>
</dependency>

in my POM.

The issue had nothing to do with inter module dependencies


来源: stackexchange

问:
How are "mvn clean package" and "mvn clean install" different?
What exactly are the differences between mvn clean package and mvn clean install? When I run both of these commands, they both seem to do the same thing.

答:
package will generate Jar/war as per POM file.
install will install generated jar file to the local repository for other dependencies if any.

install phase comes after package phase

ContentLicense: CC BY-SA 3.0


问:
jQuery CSS Property
I used the .css() for changing the border color for an element, and every time I perform the action that trigger the jQuery script, the border changes like it supposed to, but changes back after a second.

This is the code:

$("#form1").submit(function() {
  if (!$('#foo').val().length) {
    $("#foo").css('border', '3px solid red');
  }
  $("#foo").css('border', '3px solid red');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<div>
  <form id="form1" name="form1" method="post">
    <div class="textInput">
      PO: <input type="text" class="txtBox" name="foo" id="foo"><br /><br />
    </div>
    <input type="submit" name="Submit" value="Submit" />
  </form>
</div></code>```

No additional JS or css file.

答:
because when you submit the form your page reload again
you can prevent it from load again

```<code>$("#form1").submit(function(e) {
  e.preventDefault();
  $("#foo").css('border', '3px solid red');
});
</code>```

also i removed

```<code>if (!$('#foo').val().length) {
    $("#foo").css('border', '3px solid red');
  }
</code>```

because it will execute by the way in below this if

Title: jQuery CSS Property

Body:
I used the .css() for changing the border color for an element, and every time I perform the action that trigger the jQuery script, the border changes like it supposed to, but changes back after a second.

This is the code:

$("#form1").submit(function() {
  if (!$('#foo').val().length) {
    $("#foo").css('border', '3px solid red');
  }
  $("#foo").css('border', '3px solid red');
});

  <form id="form1" name="form1" method="post">

      PO: <input type="text" class="txtBox" name="foo" id="foo">

    <input type="submit" name="Submit" value="Submit" />
  </form>

No additional JS or css file.

Body:
because when you submit the form your page reload again
you can prevent it from load again

$("#form1").submit(function(e) {
  e.preventDefault();
  $("#foo").css('border', '3px solid red');
});

also i removed

if (!$('#foo').val().length) {
    $("#foo").css('border', '3px solid red');
  }

because it will execute by the way in below this if


问:
C++ const getter method with lazy initialization
What is the proper way to implement a getter method for a lazily-initialized member variable and maintain const-correctness? That is, I would like to have my getter method be const, because after the first time it is used, it's a normal getter method. It is only the first time (when the object is first initialized) that const does not apply. What I would like to do:

```<code>class MyClass {
  MyClass() : expensive_object_(NULL) {}
  QObject* GetExpensiveObject() const {
    if (!expensive_object_) {
      expensive_object = CreateExpensiveObject();
    }
    return expensive_object_;
  }
private:
  QObject *expensive_object_;
};
</code>```

Can I eat my cake and have it too?

答:
I played a bit with this topic and came up with an alternative solution in case you use C++11. Consider the following:

```<code>class MyClass
{
public:
    MyClass() :
        expensiveObjectLazyAccess()
    {
        // Set initial behavior to initialize the expensive object when called.
        expensiveObjectLazyAccess = [this]()
        {
            // Consider wrapping result in a shared_ptr if this is the owner of the expensive object.
            auto result = std::shared_ptr<ExpensiveType>(CreateExpensiveObject());

            // Maintain a local copy of the captured variable.
            auto self = this;

            // overwrite itself to a function which just returns the already initialized expensive object
            // Note that all the captures of the lambda will be invalidated after this point, accessing them
            // would result in undefined behavior. If the captured variables are needed after this they can be
            // copied to local variable beforehand (i.e. self).
            expensiveObjectLazyAccess = [result]() { return result.get(); };

            // Initialization is done, call self again. I'm calling self->GetExpensiveObject() just to
            // illustrate that it's safe to call method on local copy of this. Using this->GetExpensiveObject()
            // would be undefined behavior since the reassignment above destroys the lambda captured
            // variables. Alternatively I could just use:
            // return result.get();
            return self->GetExpensiveObject();
        };
    }

    ExpensiveType* GetExpensiveObject() const
    {
        // Forward call to member function
        return expensiveObjectLazyAccess();
    }
private:
    // hold a function returning the value instead of the value itself
    std::function<ExpensiveType*()> expensiveObjectLazyAccess;
};
</code>```

Main idea is to hold a function returning the expensive object as member instead of the object itself. In the constructor initialize with a function that does the following:

Initializes the expensive object

Replaces itself with a function which captures the already initialized object and just returns it.

Returns the object.

What I like about this is that the initialization code is still written in the constructor (where I'd naturally put it if lazyness was not needed) even though it will only get executed when the first query for the expensive object happens.

A downside of this approach is that std::function reassigns itself within it's execution. Accessing any non static members (captures in case of using lambda's) after the reassignment would result in undefined behavior so this requires extra attention. Also this is kind of a hack since GetExpensiveObject() is const but it still modifies a member attribute on first call.

In production code I'd probably prefer to just make the member mutable as James Curran described. This way the public API of your class clearly states that the member is not considered part of the objects state, therefore it doesn't affect constness.

After a bit more thinking I figured that std::async with std::launch::deferred could also be used in combination with a std::shared_future in order to be able to retrieve the result multiple times. Here is the code:

```<code>class MyClass
{
public:
    MyClass() :
        deferredObj()
    {
        deferredObj = std::async(std::launch::deferred, []()
        {
            return std::shared_ptr<ExpensiveType>(CreateExpensiveObject());
        });
    }

    const ExpensiveType* GetExpensiveObject() const
    {
        return deferredObj.get().get();
    }
private:
    std::shared_future<std::shared_ptr<ExpensiveType>> deferredObj;
};
</code>```

ContentLicense: CC BY-SA 2.5

Body:
What is the proper way to implement a getter method for a lazily-initialized member variable and maintain const-correctness? That is, I would like to have my getter method be const, because after the first time it is used, it's a normal getter method. It is only the first time (when the object is first initialized) that const does not apply. What I would like to do:

class MyClass {
  MyClass() : expensive_object_(NULL) {}
  QObject* GetExpensiveObject() const {
    if (!expensive_object_) {
      expensive_object = CreateExpensiveObject();
    }
    return expensive_object_;
  }
private:
  QObject *expensive_object_;
};

Can I eat my cake and have it too?

Body:
I played a bit with this topic and came up with an alternative solution in case you use C++11. Consider the following:

class MyClass
{
public:
    MyClass() :
        expensiveObjectLazyAccess()
    {
        // Set initial behavior to initialize the expensive object when called.
        expensiveObjectLazyAccess = [this]()
        {
            // Consider wrapping result in a shared_ptr if this is the owner of the expensive object.
            auto result = std::shared_ptr<ExpensiveType>(CreateExpensiveObject());

            // Maintain a local copy of the captured variable.
            auto self = this;

            // overwrite itself to a function which just returns the already initialized expensive object
            // Note that all the captures of the lambda will be invalidated after this point, accessing them
            // would result in undefined behavior. If the captured variables are needed after this they can be
            // copied to local variable beforehand (i.e. self).
            expensiveObjectLazyAccess = [result]() { return result.get(); };

            // Initialization is done, call self again. I'm calling self->GetExpensiveObject() just to
            // illustrate that it's safe to call method on local copy of this. Using this->GetExpensiveObject()
            // would be undefined behavior since the reassignment above destroys the lambda captured
            // variables. Alternatively I could just use:
            // return result.get();
            return self->GetExpensiveObject();
        };
    }

    ExpensiveType* GetExpensiveObject() const
    {
        // Forward call to member function
        return expensiveObjectLazyAccess();
    }
private:
    // hold a function returning the value instead of the value itself
    std::function<ExpensiveType*()> expensiveObjectLazyAccess;
};

Main idea is to hold a function returning the expensive object as member instead of the object itself. In the constructor initialize with a function that does the following:

Initializes the expensive object

Replaces itself with a function which captures the already initialized object and just returns it.

Returns the object.

What I like about this is that the initialization code is still written in the constructor (where I'd naturally put it if lazyness was not needed) even though it will only get executed when the first query for the expensive object happens.

A downside of this approach is that std::function reassigns itself within it's execution. Accessing any non static members (captures in case of using lambda's) after the reassignment would result in undefined behavior so this requires extra attention. Also this is kind of a hack since GetExpensiveObject() is const but it still modifies a member attribute on first call.

In production code I'd probably prefer to just make the member mutable as James Curran described. This way the public API of your class clearly states that the member is not considered part of the objects state, therefore it doesn't affect constness.

After a bit more thinking I figured that std::async with std::launch::deferred could also be used in combination with a std::shared_future in order to be able to retrieve the result multiple times. Here is the code:

class MyClass
{
public:
    MyClass() :
        deferredObj()
    {
        deferredObj = std::async(std::launch::deferred, []()
        {
            return std::shared_ptr<ExpensiveType>(CreateExpensiveObject());
        });
    }

    const ExpensiveType* GetExpensiveObject() const
    {
        return deferredObj.get().get();
    }
private:
    std::shared_future<std::shared_ptr<ExpensiveType>> deferredObj;
};


问:
Dynamically generating buttons based on query results in ASP.NET?
I am trying to add some filters to a gridview that I am working on, and I'm wondering if it is possible to generate links or buttons above the gridview based on the years returned in the dataset. For example, if my dataset contains dates from 2001, 2009, and 2031 in my date column, I would like to be able to take that data from my SQL query (getting a distinct list of years is not an issue), and generate the buttons. From there, I would filter the data in the gridview based on the user clicking the buttons.

Is dynamic generation of buttons possible in ASP.NET? I do have some other ideas of how to accomplish the same functionality, but I would prefer to do it this way.

Thanks,

badPanda

答: You can use another databound control e.g. a repeater that has a Button or LinkButton in it's ItemTemplate. Bind this control to your Years list. Set the Text Property of the button to display the year.</p>


问:
Google Calendar Api working fine Locally but not raising its Authentication on Server
I have created a project in console.developers.google.com to use Google Calendar API. there we need to generate credential and select application type

For Localhost and application type other following is the Json which works fine.

```<code>{
    "installed": {
    "client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
    "project_id": "xxxxxx-00000",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "xxxxxxxxxxxx",
    "redirect_uris": [ "urn:ietf:wg:oauth:2.0:oob", "http://localhost" ]
    }
}
</code>```

And for Application type Web Application to Host on Server Few parameters has different Values in Json as shown below.

```<code>{
    "web": {
    "client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
    "project_id": "xxxxxxxx-99999",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "xxxxxxxxxxxxxxxxxxxxxxx",
    "redirect_uris": [ "http://demo.mydemo.com" ],
    "javascript_origins": [ "http://demo.mydemo.com" ]
    }
}
</code>```

Here when user(Only those who have integrated Google Calendar) try to create an event Google should take consent of which google account to use and ask to read personal data before redirecting to the redirected page.
On giving consent it will add the provided data in the selected google account's calendar. The Problem is It is not redirecting the user to Oauth Authentication i.e. The Consent Screen.

 Can anyone help me to solve this issue?

Error is as follows

```<code>System.AggregateException: One or more errors occurred. ---> System.NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=xxxxxxxxxxxx-vqi4faduqgcpt3d2ruv53ltgr0rkgfsb.apps.googleusercontent.com&redirect_uri=http:%2F%2Flocalhost:53998%2Fauthorize%2F&scope=https:%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar" for authorization. See inner exception for details. ---> System.ComponentModel.Win32Exception: Access is denied
   at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
   at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.<ReceiveCodeAsync>d__8.MoveNext()
   --- End of inner exception stack trace ---
   at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.<ReceiveCodeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.<AuthorizeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__1.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at KriyaCRM.Controllers.ActivitiesController.GetCalendarConnection(Activities objact, String Operation)
---> (Inner Exception #0) System.NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=430760523223-vqi4faduqgcpt3d2ruv53ltgr0rkgfsb.apps.googleusercontent.com&redirect_uri=http:%2F%2Flocalhost:53998%2Fauthorize%2F&scope=https:%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar" for authorization. See inner exception for details. ---> System.ComponentModel.Win32Exception: Access is denied
   at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
   at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.<ReceiveCodeAsync>d__8.MoveNext()
   --- End of inner exception stack trace ---
   at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.<ReceiveCodeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.<AuthorizeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__1.MoveNext()<---
--> Important Link related to API : https://www.codeproject.com/Articles/1183150/Securing-ASP-NET-Web-API-using-Custom-Token-Based <--
</code>```

答:
```<code>var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                             scopes,
                                                                             userName,
                                                                             CancellationToken.None,
                                                                             new FileDataStore(credPath, true)).Result;
</code>```

Is used for installed applications.  It will probably work when you are running your code in debug mode because you have access to open a web browser on your local-machine.   However when you try to host it on a server its not going to work because you don't have access to open a web browser on the server what you want to do is open a web browser on the clients machine.

```<code>private static readonly IAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = "PUT_CLIENT_ID_HERE",
                        ClientSecret = "PUT_CLIENT_SECRET_HERE"
                    },
                    Scopes = new[] { DriveService.Scope.Drive },
                    DataStore = new FileDataStore("Drive.Api.Auth.Store")
                });
</code>```

You should try following this article.  Google Oauth2 asp.net MVC

Body:
I have created a project in console.developers.google.com to use Google Calendar API. there we need to generate credential and select application type

For Localhost and application type other following is the Json which works fine.

{
    "installed": {
    "client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
    "project_id": "xxxxxx-00000",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "xxxxxxxxxxxx",
    "redirect_uris": [ "urn:ietf:wg:oauth:2.0:oob", "http://localhost" ]
    }
}

And for Application type Web Application to Host on Server Few parameters has different Values in Json as shown below.

{
    "web": {
    "client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
    "project_id": "xxxxxxxx-99999",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "xxxxxxxxxxxxxxxxxxxxxxx",
    "redirect_uris": [ "http://demo.mydemo.com" ],
    "javascript_origins": [ "http://demo.mydemo.com" ]
    }
}

Here when user(Only those who have integrated Google Calendar) try to create an event Google should take consent of which google account to use and ask to read personal data before redirecting to the redirected page.
On giving consent it will add the provided data in the selected google account's calendar. The Problem is It is not redirecting the user to Oauth Authentication i.e. The Consent Screen.

 Can anyone help me to solve this issue?

Error is as follows

System.AggregateException: One or more errors occurred. ---> System.NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=xxxxxxxxxxxx-vqi4faduqgcpt3d2ruv53ltgr0rkgfsb.apps.googleusercontent.com&redirect_uri=http:%2F%2Flocalhost:53998%2Fauthorize%2F&scope=https:%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar" for authorization. See inner exception for details. ---> System.ComponentModel.Win32Exception: Access is denied
   at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
   at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.<ReceiveCodeAsync>d__8.MoveNext()
   --- End of inner exception stack trace ---
   at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.<ReceiveCodeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.<AuthorizeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__1.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at KriyaCRM.Controllers.ActivitiesController.GetCalendarConnection(Activities objact, String Operation)
---> (Inner Exception #0) System.NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=430760523223-vqi4faduqgcpt3d2ruv53ltgr0rkgfsb.apps.googleusercontent.com&redirect_uri=http:%2F%2Flocalhost:53998%2Fauthorize%2F&scope=https:%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar" for authorization. See inner exception for details. ---> System.ComponentModel.Win32Exception: Access is denied
   at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
   at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.<ReceiveCodeAsync>d__8.MoveNext()
   --- End of inner exception stack trace ---
   at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.<ReceiveCodeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.<AuthorizeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__1.MoveNext()<---
--> Important Link related to API : https://www.codeproject.com/Articles/1183150/Securing-ASP-NET-Web-API-using-Custom-Token-Based <--

Body:
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                             scopes,
                                                                             userName,
                                                                             CancellationToken.None,
                                                                             new FileDataStore(credPath, true)).Result;

Is used for installed applications.  It will probably work when you are running your code in debug mode because you have access to open a web browser on your local-machine.   However when you try to host it on a server its not going to work because you don't have access to open a web browser on the server what you want to do is open a web browser on the clients machine.

private static readonly IAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = "PUT_CLIENT_ID_HERE",
                        ClientSecret = "PUT_CLIENT_SECRET_HERE"
                    },
                    Scopes = new[] { DriveService.Scope.Drive },
                    DataStore = new FileDataStore("Drive.Api.Auth.Store")
                });

You should try following this article.  Google Oauth2 asp.net MVC


问:
PHP: MYSQLI Change Order By Style

Hi, i want to get data from chat table like this:

```<code>6
7
8
</code>```

My Code show like this:

```<code>8
7
6
</code>```

Code:

```<code>"SELECT * FROM `chat` WHERE
    `chat-code` = 'vm1mxo3dpi9gzuo' AND (`user_1` = '1' OR `user_2` = '1')
     ORDER BY id DESC LIMIT 3"
</code>```

答:
I have the solution of your problem - use below query:</p>

```<code>SELECT * FROM (
    SELECT * FROM `chat`
    WHERE `chat-code` = 'vm1mxo3dpi9gzuo' AND
    (`user_1` = '1' OR `user_2` = '1')
    ORDER BY `text` DESC LIMIT 3
) t ORDER BY `text` ASC
</code>```

Title: PHP: MYSQLI Change Order By Style

Body:
Hi, i want to get data from chat table like this:

6
7
8

My Code show like this:

8
7
6

Code:

"SELECT * FROM `chat` WHERE
    `chat-code` = 'vm1mxo3dpi9gzuo' AND (`user_1` = '1' OR `user_2` = '1')
     ORDER BY id DESC LIMIT 3"

Body:
I have the solution of your problem - use below query:

SELECT * FROM (
    SELECT * FROM `chat`
    WHERE `chat-code` = 'vm1mxo3dpi9gzuo' AND
    (`user_1` = '1' OR `user_2` = '1')
    ORDER BY `text` DESC LIMIT 3
) t ORDER BY `text` ASC

ContentLicense: CC BY-SA 4.0


问:
convert date format to 'YYYYMMDD'
In Javascript, I have date string as shown below:

```<code>var dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";
</code>```

I need to convert it to  "YYYYMMDD" format. For example the above date should be : "20150325"

答:
Here's a dirty hack to get you started. There are numerous ways of achieving the format you want. I went for string manipulation (which isn't the best performance).

var someDate = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
var dateFormated = someDate.toISOString().substr(0,10).replace(/-/g,"");

alert(dateFormated);```

Title: convert date format to 'YYYYMMDD'

Body:
In Javascript, I have date string as shown below:

var dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";

I need to convert it to  "YYYYMMDD" format. For example the above date should be : "20150325"


问:
SELECT-ing data from stored procedures
I have a complicated SELECT query that filters on a time range, and I want this time range (start and end dates) to be specifiable using user-supplied parameters.  So I can use a stored procedure to do this, and the return is a multiple-row result set.  The problem I'm having is how to deal with this result set afterwards.  I can't do something like:

```<code>SELECT * FROM (CALL stored_procedure(start_time, end_time))
</code>```

even though the stored procedure is just a SELECT that takes parameters.  Server-side prepared statement also don't work (and they're not persistent either).
Some suggest using temporary tables; the reason that's not an ideal solution is that 1) I don't want to specify the table schema and it seems that you have to, and 2) the lifetime of the temporary table would only be limited to a invocation of the query, it doesn't need to persist beyond that.

So to recap, I want something like a persistent prepared statement server-side, whose return is a result set that MySQL can manipulate as if it was a subquery.  Any ideas?  Thanks.

By the way, I'm using MySQL 5.0.  I know it's a pretty old version, but this feature doesn't seem to exist in any more recent version.  I'm not sure whether SELECT-ing from a stored procedure is possible in other SQL engines; switching is not an option at the moment, but I'd like to know whether it's possible anyway, in case we decide to switch in the future.

答:
Selecting from functions is possible in other engines. For instance, Oracle allows you to write a function that returns a table of user defined type. You can define result sets in the function, fill them by using queries or even using a combination of selects and code. Eventually, the result set can be returned from the function, and you can continue to query on that by using:

```<code>select * from table(FunctionToBeCalls(parameters));
</code>```

The only disadvantage, is that this result set is not indexed, so it might be slow if the function is used within a complex query.

In MySQL nothing like this is possible. There is no way to use a result set from a procedure directly in a select query. You can return single values from a function and you can use OUT or INOUT parameters to you procedure to return values from.
But entire result sets is not possible. Filling a temporary table within you procedure is the closest you will get.

Title: SELECT-ing data from stored procedures

Body:
I have a complicated SELECT query that filters on a time range, and I want this time range (start and end dates) to be specifiable using user-supplied parameters.  So I can use a stored procedure to do this, and the return is a multiple-row result set.  The problem I'm having is how to deal with this result set afterwards.  I can't do something like:

SELECT * FROM (CALL stored_procedure(start_time, end_time))

even though the stored procedure is just a SELECT that takes parameters.  Server-side prepared statement also don't work (and they're not persistent either).
Some suggest using temporary tables; the reason that's not an ideal solution is that 1) I don't want to specify the table schema and it seems that you have to, and 2) the lifetime of the temporary table would only be limited to a invocation of the query, it doesn't need to persist beyond that.

So to recap, I want something like a persistent prepared statement server-side, whose return is a result set that MySQL can manipulate as if it was a subquery.  Any ideas?  Thanks.

By the way, I'm using MySQL 5.0.  I know it's a pretty old version, but this feature doesn't seem to exist in any more recent version.  I'm not sure whether SELECT-ing from a stored procedure is possible in other SQL engines; switching is not an option at the moment, but I'd like to know whether it's possible anyway, in case we decide to switch in the future.

Body:
Selecting from functions is possible in other engines. For instance, Oracle allows you to write a function that returns a table of user defined type. You can define result sets in the function, fill them by using queries or even using a combination of selects and code. Eventually, the result set can be returned from the function, and you can continue to query on that by using:

select * from table(FunctionToBeCalls(parameters));

The only disadvantage, is that this result set is not indexed, so it might be slow if the function is used within a complex query.

In MySQL nothing like this is possible. There is no way to use a result set from a procedure directly in a select query. You can return single values from a function and you can use OUT or INOUT parameters to you procedure to return values from.
But entire result sets is not possible. Filling a temporary table within you procedure is the closest you will get.


问:
Can we send notification globally without using firebase?
Can we create rest services for sending a notification to Android app without using Firebase Cloud Messaging / Google Cloud Messaging or other cloud messenger tool? If yes, how's that possible? I have searched for the same but couldn't get the appropriate result. The result I get in that REST services are combined with cloud messenger tool, but I want to create services through which I could easily send notification without open Cloud Messenger console.

code to handle data from php

```<code>    private void handleNotification(String message) {
    Log.e(TAG, "===========================messaging 4=======" );

    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {

        Intent intent= new Intent(this,MainActivity.class);
        intent.putExtra("message",message);
        intent.putExtra("imageUrl",imageUrl);
        intent.putExtra("time_stamp",timeStamp);

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

        final PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri notificationSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notifiBuilder=new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("NOTIFICATION !!")
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(notificationSound)
                .setContentIntent(pendingIntent) ;

        NotificationManager notificationManager=
                ( NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0,notifiBuilder.build());

        Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
        pushNotification.putExtra("message", message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

        // play notification sound
       /* NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());

       notificationUtils.playNotificationSound();*/

    }
}

private void handleDataMessage(JSONObject json) {
    Log.e(TAG, "===========================messaging 4=======" );
    Log.e(TAG, "push json: " + json.toString());

    try {
        JSONObject data = json.getJSONObject("data");

        String title = data.getString("title");
        String message = data.getString("message");
       boolean isBackground = data.getBoolean("is_background");
        String imageUrl = data.getString("image");
       String timestamp = data.getString("timestamp");
      JSONObject payload = data.getJSONObject("payload");

        Log.e(TAG, "title: " + title);
        Log.e(TAG, "message: " + message);
       Log.e(TAG, "isBackground: " + isBackground);
        Log.e(TAG, "payload: " + payload.toString());
        Log.e(TAG, "imageUrl: " + imageUrl);
        Log.e(TAG, "timestamp: " + timestamp);

        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message

            Intent intent= new Intent(this,MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            final PendingIntent pendingIntent = PendingIntent.getActivity(
                    this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

            Uri notificationSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.Builder notifiBuilder=new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("NOTIFICATION data message!!")
                    .setContentText(message)
                    .addAction(R.mipmap.ic_accept,"ACCEPT",pendingIntent)
                    .addAction(R.mipmap.ic_decline,"DECLINE",pendingIntent)
                    .setAutoCancel(true)
                    .setSound(notificationSound)
                    .setContentIntent(pendingIntent) ;

            NotificationManager notificationManager=
                    ( NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(0,notifiBuilder.build());

            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound

        } else {
            // app is in background, show the notification in notification tray

            Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
            resultIntent.putExtra("message", message);

            // check for image attachment
            if (TextUtils.isEmpty(imageUrl)) {
                showNotificationMessage(getApplicationContext(), title, message, resultIntent);
            } else {
                // image is present, show notification with image
                showNotificationMessageWithBigImage(getApplicationContext(), title, message, resultIntent, imageUrl);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}
</code>```

答:
This can be a longer and tough process

Create a background service in your app which keeps on checking your webserver for new messages after every certain interval(May be seconds or Minutes).

This service is liable to be killed or cleaned by the Android OS. Hence, you may need to register an AlarmManager which invokes the Services at the intervals.

The background service, will call a webserver API along with a unique ID (May be device ID or some Access Token)

On your webserver, you can create an API which, on receiving a request from the device, using the passed UniqueID, checks if there is any message or not. If there is a message, it responds back with the data.

On the App, on receiving the data from the webserver, you can do the needful.

A similar process is used by FCM/GCM. But it guarantees the notification, as the GooglePlayServices is always running in Android in the background.

This procedure can make you do what you want to a certain extent, but, as aforesaid, can be difficult and challenging.

Body:
Can we create rest services for sending a notification to Android app without using Firebase Cloud Messaging / Google Cloud Messaging or other cloud messenger tool? If yes, how's that possible? I have searched for the same but couldn't get the appropriate result. The result I get in that REST services are combined with cloud messenger tool, but I want to create services through which I could easily send notification without open Cloud Messenger console.

code to handle data from php

    private void handleNotification(String message) {
    Log.e(TAG, "===========================messaging 4=======" );

    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {

        Intent intent= new Intent(this,MainActivity.class);
        intent.putExtra("message",message);
        intent.putExtra("imageUrl",imageUrl);
        intent.putExtra("time_stamp",timeStamp);

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

        final PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri notificationSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notifiBuilder=new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("NOTIFICATION !!")
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(notificationSound)
                .setContentIntent(pendingIntent) ;

        NotificationManager notificationManager=
                ( NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0,notifiBuilder.build());

        Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
        pushNotification.putExtra("message", message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

        // play notification sound
       /* NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());

       notificationUtils.playNotificationSound();*/

    }
}

private void handleDataMessage(JSONObject json) {
    Log.e(TAG, "===========================messaging 4=======" );
    Log.e(TAG, "push json: " + json.toString());

    try {
        JSONObject data = json.getJSONObject("data");

        String title = data.getString("title");
        String message = data.getString("message");
       boolean isBackground = data.getBoolean("is_background");
        String imageUrl = data.getString("image");
       String timestamp = data.getString("timestamp");
      JSONObject payload = data.getJSONObject("payload");

        Log.e(TAG, "title: " + title);
        Log.e(TAG, "message: " + message);
       Log.e(TAG, "isBackground: " + isBackground);
        Log.e(TAG, "payload: " + payload.toString());
        Log.e(TAG, "imageUrl: " + imageUrl);
        Log.e(TAG, "timestamp: " + timestamp);

        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message

            Intent intent= new Intent(this,MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            final PendingIntent pendingIntent = PendingIntent.getActivity(
                    this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

            Uri notificationSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.Builder notifiBuilder=new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("NOTIFICATION data message!!")
                    .setContentText(message)
                    .addAction(R.mipmap.ic_accept,"ACCEPT",pendingIntent)
                    .addAction(R.mipmap.ic_decline,"DECLINE",pendingIntent)
                    .setAutoCancel(true)
                    .setSound(notificationSound)
                    .setContentIntent(pendingIntent) ;

            NotificationManager notificationManager=
                    ( NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(0,notifiBuilder.build());

            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound

        } else {
            // app is in background, show the notification in notification tray

            Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
            resultIntent.putExtra("message", message);

            // check for image attachment
            if (TextUtils.isEmpty(imageUrl)) {
                showNotificationMessage(getApplicationContext(), title, message, resultIntent);
            } else {
                // image is present, show notification with image
                showNotificationMessageWithBigImage(getApplicationContext(), title, message, resultIntent, imageUrl);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}


问:
EntityFramework LINQ query returned same values
Help understand please  why that query returns same values but if i use anonymous type it return correct result

```<code>//same values
var deviceMessageList1 = _deviceMessageRepository.Fromdevicemessages
                .Where(m => m.DeviceId == deviceId).Take(1000).ToList();
//different values
            var deviceMessageList2 = _deviceMessageRepository.Fromdevicemessages
                .Where(m => m.DeviceId == deviceId).Take(1000).Select(x=> new { Message = x.Message }).ToList();
</code>```

[]

答:
Both the queries are same except in second query you are using anonymous type.
first query will return original object with all the properties in that object and second query will just return message as you are using anonymous type.

To better understand this is like
//first query

```<code>select Top 1000 * from Fromdevicemessages
</code>```

//Second query

```<code>select Top 1000 Message from Fromdevicemessages
</code>```

Body:
Help understand please  why that query returns same values but if i use anonymous type it return correct result

//same values
var deviceMessageList1 = _deviceMessageRepository.Fromdevicemessages
                .Where(m => m.DeviceId == deviceId).Take(1000).ToList();
//different values
            var deviceMessageList2 = _deviceMessageRepository.Fromdevicemessages
                .Where(m => m.DeviceId == deviceId).Take(1000).Select(x=> new { Message = x.Message }).ToList();

[]

Body:
Both the queries are same except in second query you are using anonymous type.
first query will return original object with all the properties in that object and second query will just return message as you are using anonymous type.

To better understand this is like
//first query

select Top 1000 * from Fromdevicemessages

//Second query

select Top 1000 Message from Fromdevicemessages


问:
Why does Gerrit show a different number of changes than git does?
This is the result of my latest commit / change in Git...

...and in Gerrit:

Is there any explanation for difference in number of lines added and deleted? Different algorithm?

答:
The actual changes are same. But the difference is due to how GIT and GERRIT computes the number of lines changed. Say you have 4 versions/changes/patchsets of the commit on top of HEAD.

commit_patchset#4

commit_patchset#3

commit_patchset#2

commit_patchset#1

HEAD

Git:

Number of lines changed for commit#4(A1): diff between commit_patchset#4 and commit_patch#3

Number of lines changed for commit#3(B1): diff between commit_patchset#3 and commit_patch#2

Number of lines changed for commit#2(C1): diff between commit_patchset#2 and commit_patch#1

Number of lines changed for commit#1(D1): diff between commit_patchset#1 and HEAD

Gerrit:

Number of lines changed for commit#4(A2): diff between commit_patchset#4 and BASE/HEAD

Number of lines changed for commit#3(B2): diff between commit_patchset#3 and BASE/HEAD

Number of lines changed for commit#2(C2): diff between commit_patchset#2 and BASE/HEAD

Number of lines changed for commit#1(D2): diff between commit_patchset#1 and BASE/HEAD

So always the number of lines changed will be different.

You can ask Gerrit to show the exact difference (as GIT shows) between patchset version instead of BASE/HEAD using ".." option.

For example,

http://your_gerrit_url/your_change_id/4..3 gives you the exact lines changed between commit_patchset#4 and commit_patchset#3. This should match the GIT calculations.

Hope it helps.


问:
Appcelerator titanium crashes building java files for my android project
My project was compiled successfully 3 weeks ago. I'm avoiding to update appcelerator components because certain modules of my project need that specific version.

I'm not update Java (1.8 131) neither the appcelerator cli or sdk since 3 weeks ago. The SDK version i am using is 6.0.2.

I can't undestand why titanium is showing this errors now in the "building Java source files" stage:

```<code>[INFO]  Building Java source files: /usr/lib/jvm/java-8-oracle/bin/javac "-J-Xmx1024M" "-encoding" "utf8" "-bootclasspath" "/home/user/android-sdk/platforms/android-23/android.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/kroll-v8.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-analytics.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/aps-analytics.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-android.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/jaxen-1.1.1.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/ti-commons-codec-1.3.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/kroll-common.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/titanium.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/android-support-multidex.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-filesystem.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-app.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-ui.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/nineoldandroids-appc-2.4.0.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-media.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-appcompat.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/android-support-v4.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/android-support-v7-appcompat.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-cardview.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/cardview-v7-23.0.1.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-locale.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-network.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-xml.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-map.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-calendar.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-geolocation.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-database.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-accelerometer.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-platform.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-contacts.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-gesture.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-utils.jar:/home/user/Appcelerator_Studio_Workspace/myproject/modules/android/ti.map/3.1.1/map.jar:/home/user/Appcelerator_Studio_Workspace/myproject/modules/android/ti.map/3.1.1/lib/google-play-services-gcm+maps.jar:/home/user/Appcelerator_Studio_Workspace/myproject/modules/android/ti.imagefactory/3.0.0/imagefactory.jar:/home/user/Appcelerator_Studio_Workspace/myproject/modules/android/ti.goosh/2.0.5/ti.goosh.jar:/home/user/Appcelerator_Studio_Workspace/myproject/modules/android/ti.goosh/2.0.5/lib/gson.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/kroll-apt.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/lib/titanium-verify.jar:Manifest.class:R.class:AssetCryptImpl.class:FixioActivity.class:FixioAppInfo.class:FixioApplication.class" "-d" "/home/user/Appcelerator_Studio_Workspace/myproject/build/android/bin/classes" "-proc:none" "-target" "1.6" "-source" "1.6" "@/home/user/Appcelerator_Studio_Workspace/myproject/build/android/java-sources.txt"
[ERROR] Failed to compile Java source files:
[ERROR]
[ERROR] /home/user/Appcelerator_Studio_Workspace/myproject/build/android/gen/es/myproject/AssetCryptImpl.java:44: error: cannot find symbol
[ERROR]             Range range = assets.get(path);
[ERROR]                           ^
[ERROR]   symbol:   variable assets
[ERROR]   location: class AssetCryptImpl
[ERROR] /home/user/Appcelerator_Studio_Workspace/myproject/build/android/gen/es/myproject/AssetCryptImpl.java:48: error: cannot find symbol
[ERROR]             return new String(filterDataInRange(assetsBytes, range.offset, range.length));
[ERROR]                                                 ^
[ERROR]   symbol:   variable assetsBytes
[ERROR]   location: class AssetCryptImpl
[ERROR] Note: /home/user/Appcelerator_Studio_Workspace/myproject/build/android/gen/es/fixio/AssetCryptImpl.java uses unchecked or unsafe operations.
[ERROR] Note: Recompile with -Xlint:unchecked for details.
[ERROR] 2 errors
</code>```

Thanks in advance for your help and sorry for my bad English.

UPDATE (2017-07-05):

I found this appcelerator jira with the same problem:
https://jira.appcelerator.org/browse/TIMOB-24895

I'm waiting for a official workarround.

答: Apparently the problem is version 4.4.0-81 of my linux kernel (Ubuntu 16.04). At the moment, my solution has been to start up with version 4.4.0-79 in order to compile as usually.</p>

Body:
My project was compiled successfully 3 weeks ago. I'm avoiding to update appcelerator components because certain modules of my project need that specific version.

I'm not update Java (1.8 131) neither the appcelerator cli or sdk since 3 weeks ago. The SDK version i am using is 6.0.2.

I can't undestand why titanium is showing this errors now in the "building Java source files" stage:

[INFO]  Building Java source files: /usr/lib/jvm/java-8-oracle/bin/javac "-J-Xmx1024M" "-encoding" "utf8" "-bootclasspath" "/home/user/android-sdk/platforms/android-23/android.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/kroll-v8.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-analytics.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/aps-analytics.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-android.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/jaxen-1.1.1.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/ti-commons-codec-1.3.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/kroll-common.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/titanium.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/android-support-multidex.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-filesystem.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-app.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-ui.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/nineoldandroids-appc-2.4.0.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-media.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-appcompat.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/android-support-v4.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/android-support-v7-appcompat.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-cardview.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/cardview-v7-23.0.1.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-locale.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-network.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-xml.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-map.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-calendar.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-geolocation.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-database.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-accelerometer.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-platform.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-contacts.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-gesture.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/modules/titanium-utils.jar:/home/user/Appcelerator_Studio_Workspace/myproject/modules/android/ti.map/3.1.1/map.jar:/home/user/Appcelerator_Studio_Workspace/myproject/modules/android/ti.map/3.1.1/lib/google-play-services-gcm+maps.jar:/home/user/Appcelerator_Studio_Workspace/myproject/modules/android/ti.imagefactory/3.0.0/imagefactory.jar:/home/user/Appcelerator_Studio_Workspace/myproject/modules/android/ti.goosh/2.0.5/ti.goosh.jar:/home/user/Appcelerator_Studio_Workspace/myproject/modules/android/ti.goosh/2.0.5/lib/gson.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/kroll-apt.jar:/home/user/.titanium/mobilesdk/linux/6.0.2.GA/android/lib/titanium-verify.jar:Manifest.class:R.class:AssetCryptImpl.class:FixioActivity.class:FixioAppInfo.class:FixioApplication.class" "-d" "/home/user/Appcelerator_Studio_Workspace/myproject/build/android/bin/classes" "-proc:none" "-target" "1.6" "-source" "1.6" "@/home/user/Appcelerator_Studio_Workspace/myproject/build/android/java-sources.txt"
[ERROR] Failed to compile Java source files:
[ERROR]
[ERROR] /home/user/Appcelerator_Studio_Workspace/myproject/build/android/gen/es/myproject/AssetCryptImpl.java:44: error: cannot find symbol
[ERROR]             Range range = assets.get(path);
[ERROR]                           ^
[ERROR]   symbol:   variable assets
[ERROR]   location: class AssetCryptImpl
[ERROR] /home/user/Appcelerator_Studio_Workspace/myproject/build/android/gen/es/myproject/AssetCryptImpl.java:48: error: cannot find symbol
[ERROR]             return new String(filterDataInRange(assetsBytes, range.offset, range.length));
[ERROR]                                                 ^
[ERROR]   symbol:   variable assetsBytes
[ERROR]   location: class AssetCryptImpl
[ERROR] Note: /home/user/Appcelerator_Studio_Workspace/myproject/build/android/gen/es/fixio/AssetCryptImpl.java uses unchecked or unsafe operations.
[ERROR] Note: Recompile with -Xlint:unchecked for details.
[ERROR] 2 errors

Thanks in advance for your help and sorry for my bad English.

UPDATE (2017-07-05):

I found this appcelerator jira with the same problem:
https://jira.appcelerator.org/browse/TIMOB-24895

I'm waiting for a official workarround.


问:
Grails - How Do I Show Version And Build Date/Time In My Application
I'd like to know if there is a way to display the version and build date at the top of my Grails application.

Edit: I should have said I'm looking for the Date/Time the app was built.

答:
Any one looking for the solution for grails 3. It can be done by configuring the buildProperties task

```<code>buildProperties {
    inputs.property("info.app.build.date", new Date().format('yyyy-MM-dd HH:mm:ss'))
}

 <g:meta name="info.app.build.date"/>
</code>```

See Adding build date and other custom info to war

Body:
Any one looking for the solution for grails 3. It can be done by configuring the buildProperties task

buildProperties {
    inputs.property("info.app.build.date", new Date().format('yyyy-MM-dd HH:mm:ss'))
}

 <g:meta name="info.app.build.date"/>

See Adding build date and other custom info to war


问:
How do I set my application's dock name?
I'm making a Flex app and I'd like to know how to set the name of my app as it appears when the user hovers over it in the dock. Here's a screenshot of it now:

I'd like a space between the lowercase 'd' and the uppercase Y. What part of my app's XML file must I edit to change that text in the gray tooltip?

答:
I believe it is in Foo-app.xml, where "Foo" is the name of your project.  This file is generated when you create your AIR app project.  There is a tag called "filename" that you can set to whatever you like and it will get shown as the app name when you mouse over the icon in the dock.  So do something like this:

```<code><filename>Limud Yomi</filename>
</code>```

A description of the "filename" tag, from the Adobe documentation: "The name used for the application executable, install directory, and other references to the application in the operating system."

Hope that helps.

Body:
I believe it is in Foo-app.xml, where "Foo" is the name of your project.  This file is generated when you create your AIR app project.  There is a tag called "filename" that you can set to whatever you like and it will get shown as the app name when you mouse over the icon in the dock.  So do something like this:

<filename>Limud Yomi</filename>

A description of the "filename" tag, from the Adobe documentation: "The name used for the application executable, install directory, and other references to the application in the operating system."

Hope that helps.


问:
DLL can't be accessed on some systems
Our C# / .NET  program is calling a third party DLL (x.dll) in the target folder. x.dll is then calling another third party DLL y.dll in the same folder. At some systems, this does not work, because x.dll can't find y.dll.
The same program with the same dlls works on most other systems, but we can't find out what the differences are to the systems were it does not work. We checked the properties, the dlls are not blocked by Windows. Also the virus-scanner was disabled.</p>

答:
Please go through Dynamic-Link Library Search Order and see which case it applies. the most likely case is standard DLL search order with SafeDllSearchMode enabled:

If SafeDllSearchMode is enabled, the search order is as follows:

The directory from which the application loaded.

The system directory. Use the GetSystemDirectory function to get the path of this directory.

The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.

The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

The current directory.

The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by
  the App Paths registry key. The App Paths key is not used when
  computing the DLL search path.

Note that if the DLL is a managed assembly (you do not mention it is) then the .Net assembly search rules apply, see How the Runtime Locates Assemblies. Obviously, GAC would also play a role for managed DLLs.

I'm just giving you the pointers to do your own investigations, since your post is missing the relevant info.

Title: DLL can't be accessed on some systems


问:
Hyperledger fabcar sample fabric showing connect failed ERROR
I am trying to install hyperledger and run chain code. I followed all the steps as directed here. But getting error

error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: Connect Failed

while running the query.js.
I have following active docker running
Before running the node query.js, when i am running npm install its giving following warning :
npm WARN fabcar@1.0.0 No repository field. Is this the problem. Can any one please help me out about where it is going wrong.

答:
I have met the same error during run sample, it failed to connect. I fixed it with following steps:

get machine IP address with: ifconfig

replace localhosts in query.js with IP in #1

Example:

```<code>@@ -12,7 +12,7 @@ var options = {
     user_id: 'PeerAdmin',
     channel_id: 'mychannel',
     chaincode_id: 'fabcar',
-    network_url: 'grpc://localhost:7051',
+    network_url: 'grpc://****:7051',
};
</code>```

Body:
I have met the same error during run sample, it failed to connect. I fixed it with following steps:

get machine IP address with: ifconfig

replace localhosts in query.js with IP in #1

Example:

@@ -12,7 +12,7 @@ var options = {
     user_id: 'PeerAdmin',
     channel_id: 'mychannel',
     chaincode_id: 'fabcar',
-    network_url: 'grpc://localhost:7051',
+    network_url: 'grpc://****:7051',
};


问:
jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)
All,
I'm getting an error from some of my code that I downloaded. Here is the code:

```<code>/*----------------------------------------------------------------------*/
/* wl_Alert v 1.1
/* description: Handles alert boxes
/* dependency: jquery UI Slider, fadeOutSlide plugin
/*----------------------------------------------------------------------*/

$.fn.wl_Alert = function (method) {
var args = arguments;
return this.each(function () {

    var $this = $(this);

    if ($.fn.wl_Alert.methods[method]) {
        return $.fn.wl_Alert.methods[method].apply(this, Array.prototype.slice.call(args, 1));
    } else if (typeof method === 'object' || !method) {
        if ($this.data('wl_Alert')) {
            var opts = $.extend({}, $this.data('wl_Alert'), method);
        } else {

            var opts = $.extend({}, $.fn.wl_Alert.defaults, method, $this.data());
        }
    } else {
        $.error('Method "' + method + '" does not exist');
    }

    if (!$this.data('wl_Alert')) {

        $this.data('wl_Alert', {});

        //bind click events to hide alert box
        $this.bind('click.wl_Alert', function (event) {
            event.preventDefault();

            //Don't hide if it is sticky
            if (!$this.data('wl_Alert').sticky) {
                $.fn.wl_Alert.methods.close.call($this[0]);
            }

            //prevent hiding the box if an inline link is clicked
        }).find('a').bind('click.wl_Alert', function (event) {
            event.stopPropagation();
        });
    } else {

    }
    //show it if it is hidden
    if ($this.is(':hidden')) {
        $this.slideDown(opts.speed / 2);
    }

    if (opts) $.extend($this.data('wl_Alert'), opts);
});

};

$.fn.wl_Alert.defaults = {
speed: 500,
sticky: false,
onBeforeClose: function (element) {},
onClose: function (element) {}
};
$.fn.wl_Alert.version = '1.1';

$.fn.wl_Alert.methods = {
close: function () {
    var $this = $(this),
        opts = $this.data('wl_Alert');
    //call callback and stop if it returns false
    if (opts.onBeforeClose.call(this, $this) === false) {
        return false;
    };
    //fadeout and call an callback
    $this.fadeOutSlide(opts.speed, function () {
        opts.onClose.call($this[0], $this);
    });
},
set: function () {
    var $this = $(this),
        options = {};
    if (typeof arguments[0] === 'object') {
        options = arguments[0];
    } else if (arguments[0] && arguments[1] !== undefined) {
        options[arguments[0]] = arguments[1];
    }
    $.each(options, function (key, value) {
        if ($.fn.wl_Alert.defaults[key] !== undefined || $.fn.wl_Alert.defaults[key] == null) {
            $this.data('wl_Alert')[key] = value;
        } else {
            $.error('Key "' + key + '" is not defined');
        }
    });

}
};

//to create an alert box on the fly
$.wl_Alert = function (text, cssclass, insert, after, options) {
//go thru all
$('div.alert').each(function () {
    var _this = $(this);
    //...and hide if one with the same text is allready set
    if (_this.text() == text) {
        _this.slideUp($.fn.wl_Alert.defaults.speed);
    }
});

//create a new DOM element and inject it
var al = $('<div class="alert ' + cssclass + '">' + text + '</div>').hide();
(after) ? al.appendTo(insert).wl_Alert(options) : al.prependTo(insert).wl_Alert(options);

//return the element
return al;
};
</code>```

Has anyone seen this type of error before? How would I resolve something like this? Thanks for any advice you have!

答:
I too had the "Uncaught TypeError: Cannot read property 'fn' of undefined" with:

```<code>$.fn.circleType = function(options) {

CODE...

};
</code>```

But fixed it by wrapping it in a document ready function:

```<code>jQuery(document).ready.circleType = function(options) {

CODE...

};
</code>```

Body:
All,
I'm getting an error from some of my code that I downloaded. Here is the code:

/*----------------------------------------------------------------------*/
/* wl_Alert v 1.1
/* description: Handles alert boxes
/* dependency: jquery UI Slider, fadeOutSlide plugin
/*----------------------------------------------------------------------*/

$.fn.wl_Alert = function (method) {
var args = arguments;
return this.each(function () {

    var $this = $(this);

    if ($.fn.wl_Alert.methods[method]) {
        return $.fn.wl_Alert.methods[method].apply(this, Array.prototype.slice.call(args, 1));
    } else if (typeof method === 'object' || !method) {
        if ($this.data('wl_Alert')) {
            var opts = $.extend({}, $this.data('wl_Alert'), method);
        } else {

            var opts = $.extend({}, $.fn.wl_Alert.defaults, method, $this.data());
        }
    } else {
        $.error('Method "' + method + '" does not exist');
    }

    if (!$this.data('wl_Alert')) {

        $this.data('wl_Alert', {});

        //bind click events to hide alert box
        $this.bind('click.wl_Alert', function (event) {
            event.preventDefault();

            //Don't hide if it is sticky
            if (!$this.data('wl_Alert').sticky) {
                $.fn.wl_Alert.methods.close.call($this[0]);
            }

            //prevent hiding the box if an inline link is clicked
        }).find('a').bind('click.wl_Alert', function (event) {
            event.stopPropagation();
        });
    } else {

    }
    //show it if it is hidden
    if ($this.is(':hidden')) {
        $this.slideDown(opts.speed / 2);
    }

    if (opts) $.extend($this.data('wl_Alert'), opts);
});

};

$.fn.wl_Alert.defaults = {
speed: 500,
sticky: false,
onBeforeClose: function (element) {},
onClose: function (element) {}
};
$.fn.wl_Alert.version = '1.1';

$.fn.wl_Alert.methods = {
close: function () {
    var $this = $(this),
        opts = $this.data('wl_Alert');
    //call callback and stop if it returns false
    if (opts.onBeforeClose.call(this, $this) === false) {
        return false;
    };
    //fadeout and call an callback
    $this.fadeOutSlide(opts.speed, function () {
        opts.onClose.call($this[0], $this);
    });
},
set: function () {
    var $this = $(this),
        options = {};
    if (typeof arguments[0] === 'object') {
        options = arguments[0];
    } else if (arguments[0] && arguments[1] !== undefined) {
        options[arguments[0]] = arguments[1];
    }
    $.each(options, function (key, value) {
        if ($.fn.wl_Alert.defaults[key] !== undefined || $.fn.wl_Alert.defaults[key] == null) {
            $this.data('wl_Alert')[key] = value;
        } else {
            $.error('Key "' + key + '" is not defined');
        }
    });

}
};

//to create an alert box on the fly
$.wl_Alert = function (text, cssclass, insert, after, options) {
//go thru all
$('div.alert').each(function () {
    var _this = $(this);
    //...and hide if one with the same text is allready set
    if (_this.text() == text) {
        _this.slideUp($.fn.wl_Alert.defaults.speed);
    }
});

//create a new DOM element and inject it
var al = $('
' + text + '
').hide();
(after) ? al.appendTo(insert).wl_Alert(options) : al.prependTo(insert).wl_Alert(options);

//return the element
return al;
};

Has anyone seen this type of error before? How would I resolve something like this? Thanks for any advice you have!

Body:
I too had the "Uncaught TypeError: Cannot read property 'fn' of undefined" with:

$.fn.circleType = function(options) {

CODE...

};

But fixed it by wrapping it in a document ready function:

jQuery(document).ready.circleType = function(options) {

CODE...

};


问:
WebStorm navigate bar setting?
I need to change my WebStorm nav bar style from first into second:

The first does not contain file tab, as well as I can not split vertically file.

How can I do this?

答:
I need to change my WebStorm nav bar style

It's not a "nav bar" -- it's Editor Tabs bar.

The actual Navigation Bar is present on both screenshots and it is just above it (the bar that shows new.OrderList.js in it on first screenshot).

In any case: the Editor Tabs bar can be re-enabled again at:

Settings/Preferences

Editor | General | Editor Tabs

Set Placement to be anything else than "None" -- to be as on 2nd screenshot it should be set to "Top"

Title: WebStorm navigate bar setting?


问:
how to encrypt web chat URL token and User Id to avoid missus of my bot
I am using web chat for my bot application, but here I have security issue with URL.
If someone copies below url, he will be able to change userID and and name
than he can chat with my bot with name of other person.

So I want to encrypt this URL token and user id to avoid change user ID.

https://webchat.botframework.com/embed/YOUR_BOT_ID?s=YOUR_BOT_SECRET&username=DESIRED_USERNAME&userid=DESIRED_USERID

答:
There are several things pointed in your question that you should modify.

Use Token instead of Secret:

To avoid misuse of a webchat, you must not use the secret in the URL but generate a token and use this token in the URL.

How to do this?

To exchange your secret for a token and generate the embed:

Issue a GET request to https://webchat.botframework.com/api/tokens and pass your web chat secret via the Authorization header.

The response to your GET request will contain the token (surrounded with quotation marks) that can be used to start a conversation by rendering the web chat control within an iframe. A token is valid for one conversation only; to start another conversation, you must generate a new token.

Within the iframe Embed code that you copied from the Web Chat channel within the Bot Framework Portal (as described in Step 1 above), change the s= parameter to t= and replace YOUR_SECRET_HERE with your token.

So at the end your URL will look like:

```<code>https://webchat.botframework.com/embed/YOUR_BOT_ID?t=YOUR_TOKEN_HERE&...
</code>```

Everything is explained with more details in the documentation here

Passing values

If you want to avoid an user to change the settings you are passing in username and userid, you are free to encrypt / hash / whatever you want those fields and implement your decrypt / dehash logic on your bot side to get the interesting value

Body:
There are several things pointed in your question that you should modify.

Use Token instead of Secret:

To avoid misuse of a webchat, you must not use the secret in the URL but generate a token and use this token in the URL.

How to do this?

To exchange your secret for a token and generate the embed:

Issue a GET request to https://webchat.botframework.com/api/tokens and pass your web chat secret via the Authorization header.

The response to your GET request will contain the token (surrounded with quotation marks) that can be used to start a conversation by rendering the web chat control within an iframe. A token is valid for one conversation only; to start another conversation, you must generate a new token.

Within the iframe Embed code that you copied from the Web Chat channel within the Bot Framework Portal (as described in Step 1 above), change the s= parameter to t= and replace YOUR_SECRET_HERE with your token.

So at the end your URL will look like:

https://webchat.botframework.com/embed/YOUR_BOT_ID?t=YOUR_TOKEN_HERE&...

Everything is explained with more details in the documentation here

Passing values

If you want to avoid an user to change the settings you are passing in username and userid, you are free to encrypt / hash / whatever you want those fields and implement your decrypt / dehash logic on your bot side to get the interesting value


问:
SQL basic issue
```<code>   select x_pick.prod_code, x_order.order_state, x_pick.pick_state, x_pick.pick_qty, x_pick.pick_location, x_order.wave_id, x_prod.normal_pick_area, x_apr_loc.location, x_order.reqd_despatch_time, x_prod.bncd_awkward_item, sub1.LOC_COUNT
from x_pick, x_order, x_prod, x_apr_loc,

(select X_PICK.prod_CODE, COUNT(DISTINCT( X_APR_LOC.LOCATION)) AS LOC_COUNT
from X_APR_LOC, X_PICK
where X_APR_LOC.prod_CODE (+) = X_PICK.prod_CODE
group by X_PICK.prod_code) sub1,

(select x_prod.normal_pick_area,x_pick.pick_location,
(case when  x_prod.normal_pick_area = 'TP' then 'Miniload'
when x_prod.normal_pick_area = 'MTP' then 'Miniload'
when x_prod.normal_pick_area = 'PL' then 'Pallet Live'
when x_prod.normal_pick_area = 'HLOP' then 'HLOP'
when x_prod.normal_pick_area = 'STILLAGE' then 'High Value'
when x_prod.normal_pick_area = 'ZA' then 'Aerosol'
when x_prod.normal_pick_area = 'ZH' then 'Haz Shed'
when x_prod.normal_pick_area = 'APR' and substr(x_pick.pick_location,3,2) < 22 and x_prod.bncd_awkward_item = 'YES'  then 'APR Awkward'
when x_prod.normal_pick_area = 'APR' and substr(x_pick.pick_location,3,2) < 22 and x_prod.bncd_awkward_item = 'NO'  then 'APR'
when x_prod.normal_pick_area = 'APR' and substr(x_pick.pick_location,3,2) > 21 and x_prod.bncd_awkward_item = 'NO'  then 'APR 2'
when x_prod.normal_pick_area = 'APR' and substr(x_pick.pick_location,3,2) > 21 and x_prod.bncd_awkward_item = 'YES'  then 'TD1'
else 'Unknown' end) from x_pick) area,

where x_pick.prod_code  (+) = sub1.prod_code
and x_pick.prod_code = x_apr_loc.prod_code (+)
and x_pick.prod_code = x_prod.prod_code
and x_pick.order_id = x_order.order_id
and x_pick.pick_state in('RESERVED','WAIT REPLEN','STARTED')
and x_order.order_state in('RESERVED','STARTED')
</code>```

Part of a larger query. Initially I am getting an invalid parathensis message, I can get rid of this but am them getting invalid identifier error message, even though all the fields I'm using have been called. I am pretty new to SQL so any help would be great!.

答:
Please use below there was two issue First need to add comma after pick_location second from x_item will be after column name, Hopefully it will work at your side as well</p>

```<code>(select x_item.pick_area,x_item.awkward_item,x_ploc.pick_location,
(case when  x_prod.normal_pick_area = '0' then 'Z'
when x_item.pick_area = '1' then 'A'
when x_item.pick_area = '2' then 'B'
when x_item.pick_area = '3' then 'C'
when x_item.pick_area = '4' then 'D'
when x_item.pick_area = '5' then 'E'
when x_item.pick_area = '6' then 'F'
when x_item.pick_area = '7' and substr(x_ploc.pick_location,3,2) < 22 and
                                    x_prod.awkward_item = 'YES'  then 'G'
when x_item.normal_pick_area = 'APR' and substr(x_ploc.pick_location,3,2)
   < 22 and x_item.awkward_item = 'NO'  then 'H'

when x_item.pick_area = 'APR' and substr(x_ploc.pick_location,3,2) > 21
 and x_item.awkward_item = 'NO'  then 'I'
when x_item.pick_area = 'APR' and substr(x_ploc.pick_location,3,2) > 21
and x_item.awkward_item = 'YES'  then 'J'

else 'Unknown' end)  area from x_item)
</code>```

Title: SQL basic issue

Body:
   select x_pick.prod_code, x_order.order_state, x_pick.pick_state, x_pick.pick_qty, x_pick.pick_location, x_order.wave_id, x_prod.normal_pick_area, x_apr_loc.location, x_order.reqd_despatch_time, x_prod.bncd_awkward_item, sub1.LOC_COUNT
from x_pick, x_order, x_prod, x_apr_loc,

(select X_PICK.prod_CODE, COUNT(DISTINCT( X_APR_LOC.LOCATION)) AS LOC_COUNT
from X_APR_LOC, X_PICK
where X_APR_LOC.prod_CODE (+) = X_PICK.prod_CODE
group by X_PICK.prod_code) sub1,

(select x_prod.normal_pick_area,x_pick.pick_location,
(case when  x_prod.normal_pick_area = 'TP' then 'Miniload'
when x_prod.normal_pick_area = 'MTP' then 'Miniload'
when x_prod.normal_pick_area = 'PL' then 'Pallet Live'
when x_prod.normal_pick_area = 'HLOP' then 'HLOP'
when x_prod.normal_pick_area = 'STILLAGE' then 'High Value'
when x_prod.normal_pick_area = 'ZA' then 'Aerosol'
when x_prod.normal_pick_area = 'ZH' then 'Haz Shed'
when x_prod.normal_pick_area = 'APR' and substr(x_pick.pick_location,3,2) < 22 and x_prod.bncd_awkward_item = 'YES'  then 'APR Awkward'
when x_prod.normal_pick_area = 'APR' and substr(x_pick.pick_location,3,2) < 22 and x_prod.bncd_awkward_item = 'NO'  then 'APR'
when x_prod.normal_pick_area = 'APR' and substr(x_pick.pick_location,3,2) > 21 and x_prod.bncd_awkward_item = 'NO'  then 'APR 2'
when x_prod.normal_pick_area = 'APR' and substr(x_pick.pick_location,3,2) > 21 and x_prod.bncd_awkward_item = 'YES'  then 'TD1'
else 'Unknown' end) from x_pick) area,

where x_pick.prod_code  (+) = sub1.prod_code
and x_pick.prod_code = x_apr_loc.prod_code (+)
and x_pick.prod_code = x_prod.prod_code
and x_pick.order_id = x_order.order_id
and x_pick.pick_state in('RESERVED','WAIT REPLEN','STARTED')
and x_order.order_state in('RESERVED','STARTED')

Part of a larger query. Initially I am getting an invalid parathensis message, I can get rid of this but am them getting invalid identifier error message, even though all the fields I'm using have been called. I am pretty new to SQL so any help would be great!.

Body:
Please use below there was two issue First need to add comma after pick_location second from x_item will be after column name, Hopefully it will work at your side as well

(select x_item.pick_area,x_item.awkward_item,x_ploc.pick_location,
(case when  x_prod.normal_pick_area = '0' then 'Z'
when x_item.pick_area = '1' then 'A'
when x_item.pick_area = '2' then 'B'
when x_item.pick_area = '3' then 'C'
when x_item.pick_area = '4' then 'D'
when x_item.pick_area = '5' then 'E'
when x_item.pick_area = '6' then 'F'
when x_item.pick_area = '7' and substr(x_ploc.pick_location,3,2) < 22 and
                                    x_prod.awkward_item = 'YES'  then 'G'
when x_item.normal_pick_area = 'APR' and substr(x_ploc.pick_location,3,2)
   < 22 and x_item.awkward_item = 'NO'  then 'H'

when x_item.pick_area = 'APR' and substr(x_ploc.pick_location,3,2) > 21
 and x_item.awkward_item = 'NO'  then 'I'
when x_item.pick_area = 'APR' and substr(x_ploc.pick_location,3,2) > 21
and x_item.awkward_item = 'YES'  then 'J'

else 'Unknown' end)  area from x_item)


问:
What are the best use cases for Akka framework
I have heard lots of raving about Akka framework (Java/Scala service platform), but so far have not seen many actual examples of use cases it would be good for. So I would be interested in hearing about things developers have used it succesfully.

Only one limitation: please do not include case of writing a chat server.
(why? since this has been overused as an example for lots of similar things)

答:
If you abstract the chat server up a level, then you get the answer.

Akka provides a messaging system that is akin to Erlang's "let it crash" mentality.

So examples are things that need varying levels of durability and reliability of messaging:

Chat server

Network layer for an MMO

Financial data pump

Notification system for an iPhone/mobile/whatever app

REST Server

Maybe something akin to WebMachine (guess)

The nice things about Akka are the choices it affords for persistence, it's STM implementation, REST server and fault-tolerance.

Don't get annoyed by the example of a chat server, think of it as an example of a certain class of solution.

With all their excellent documentation, I feel like a gap is this exact question, use-cases and examples.  Keeping in mind the examples are non-trivial.

(Written with only experience of watching videos and playing with the source, I have implemented nothing using akka.)


答:
```<code>(select x_item.pick_area,x_item.awkward_item,x_ploc.pick_location,
case when  x_prod.normal_pick_area = '0' then 'Z'
when x_item.pick_area = '1' then 'A'
when x_item.pick_area = '2' then 'B'
when x_item.pick_area = '3' then 'C'
when x_item.pick_area = '4' then 'D'
when x_item.pick_area = '5' then 'E'
when x_item.pick_area = '6' then 'F'
when x_item.pick_area = '7' and substr(x_ploc.pick_location,3,2) < 22 and
x_prod.awkward_item = 'YES'  then 'G'
when x_item.normal_pick_area = 'APR' and substr(x_ploc.pick_location,3,2)
< 22 and x_item.awkward_item = 'NO'  then 'H'
when x_item.pick_area = 'APR' and substr(x_ploc.pick_location,3,2) > 21
and x_item.awkward_item = 'NO'  then 'I'
when x_item.pick_area = 'APR' and substr(x_ploc.pick_location,3,2) > 21
and x_item.awkward_item = 'YES'  then 'J'
else 'Unknown' end from x_item
</code>```

This should fix it.

Title: SQL basic issue

Body:
(select x_item.pick_area,x_item.awkward_item,x_ploc.pick_location,
case when  x_prod.normal_pick_area = '0' then 'Z'
when x_item.pick_area = '1' then 'A'
when x_item.pick_area = '2' then 'B'
when x_item.pick_area = '3' then 'C'
when x_item.pick_area = '4' then 'D'
when x_item.pick_area = '5' then 'E'
when x_item.pick_area = '6' then 'F'
when x_item.pick_area = '7' and substr(x_ploc.pick_location,3,2) < 22 and
x_prod.awkward_item = 'YES'  then 'G'
when x_item.normal_pick_area = 'APR' and substr(x_ploc.pick_location,3,2)
< 22 and x_item.awkward_item = 'NO'  then 'H'
when x_item.pick_area = 'APR' and substr(x_ploc.pick_location,3,2) > 21
and x_item.awkward_item = 'NO'  then 'I'
when x_item.pick_area = 'APR' and substr(x_ploc.pick_location,3,2) > 21
and x_item.awkward_item = 'YES'  then 'J'
else 'Unknown' end from x_item

This should fix it.