Using Microsoft adaptive cards in Java

Question: I'm trying to implement a chat bot in Java utilizing adaptive cards, much like the C# sample here.
I can get the bot to display a card in Teams, but I am unable to process any responses, as I always get this exception:
2021-11-23T05:32:35.715171392Z: [INFO]

java.util.concurrent.CompletionException: com.microsoft.bot.builder.ActivityHandler$InvokeResponseException
2021-11-23T05:32:35.715176693Z: [INFO]      at java.base/java.util.concurrent.CompletableFuture.encodeThrowable(Unknown Source) ~[na:na]
2021-11-23T05:32:35.715182093Z: [INFO]      at java.base/java.util.concurrent.CompletableFuture.uniComposeStage(Unknown Source) ~[na:na]
2021-11-23T05:32:35.715186993Z: [INFO]      at java.base/java.util.concurrent.CompletableFuture.thenCompose(Unknown Source) ~[na:na]
2021-11-23T05:32:35.715191793Z: [INFO]      at com.microsoft.bot.builder.ActivityHandler.onTurn(ActivityHandler.java:105) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715196594Z: [INFO]      at com.microsoft.bot.builder.MiddlewareSet.receiveActivityInternal(MiddlewareSet.java:99) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715201494Z: [INFO]      at com.microsoft.bot.builder.MiddlewareSet.lambda$receiveActivityInternal$1(MiddlewareSet.java:110) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715206394Z: [INFO]      at com.microsoft.bot.builder.BotFrameworkAdapter$TenantIdWorkaroundForTeamsMiddleware.onTurn(BotFrameworkAdapter.java:1430) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715211294Z: [INFO]      at com.microsoft.bot.builder.MiddlewareSet.receiveActivityInternal(MiddlewareSet.java:109) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715216095Z: [INFO]      at com.microsoft.bot.builder.MiddlewareSet.receiveActivityInternal(MiddlewareSet.java:74) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715220795Z: [INFO]      at com.microsoft.bot.builder.MiddlewareSet.receiveActivityWithStatus(MiddlewareSet.java:67) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715225395Z: [INFO]      at com.microsoft.bot.builder.BotAdapter.runPipeline(BotAdapter.java:206) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715243796Z: [INFO]      at com.microsoft.bot.builder.BotFrameworkAdapter.lambda$processActivity$2(BotFrameworkAdapter.java:478) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715248396Z: [INFO]      at java.base/java.util.concurrent.CompletableFuture.uniComposeStage(Unknown Source) ~[na:na]
2021-11-23T05:32:35.715252696Z: [INFO]      at java.base/java.util.concurrent.CompletableFuture.thenCompose(Unknown Source) ~[na:na]
2021-11-23T05:32:35.715256997Z: [INFO]      at com.microsoft.bot.builder.BotFrameworkAdapter.processActivity(BotFrameworkAdapter.java:476) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715261997Z: [INFO]      at com.microsoft.bot.builder.BotFrameworkAdapter.lambda$processActivity$1(BotFrameworkAdapter.java:433) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715266297Z: [INFO]      at java.base/java.util.concurrent.CompletableFuture.uniComposeStage(Unknown Source) ~[na:na]
2021-11-23T05:32:35.715270397Z: [INFO]      at java.base/java.util.concurrent.CompletableFuture.thenCompose(Unknown Source) ~[na:na]
2021-11-23T05:32:35.715274597Z: [INFO]      at com.microsoft.bot.builder.BotFrameworkAdapter.processActivity(BotFrameworkAdapter.java:433) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715278798Z: [INFO]      at com.microsoft.bot.integration.BotFrameworkHttpAdapter.processIncomingActivity(BotFrameworkHttpAdapter.java:102) ~[bot-integration-core-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715283098Z: [INFO]      at com.microsoft.bot.integration.spring.BotController.incoming(BotController.java:84) ~[bot-integration-spring-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.715287298Z: [INFO]      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
2021-11-23T05:32:35.715291498Z: [INFO]      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
2021-11-23T05:32:35.715295699Z: [INFO]      at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
2021-11-23T05:32:35.715299799Z: [INFO]      at java.base/java.lang.reflect.Method.invoke(Unknown Source) ~[na:na]
2021-11-23T05:32:35.715303799Z: [INFO]      at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.715308199Z: [INFO]      at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.715312499Z: [INFO]      at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.715317000Z: [INFO]      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893) ~[spring-webmvc-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.715321400Z: [INFO]      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:807) ~[spring-webmvc-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.715325800Z: [INFO]      at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.715330300Z: [INFO]      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1061) ~[spring-webmvc-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.715338401Z: [INFO]      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:961) ~[spring-webmvc-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.715342801Z: [INFO]      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.715347001Z: [INFO]      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.715351101Z: [INFO]      at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) ~[tomcat-embed-core-9.0.39.jar!/:4.0.FR]
2021-11-23T05:32:35.715355202Z: [INFO]      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.715359702Z: [INFO]      at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.39.jar!/:4.0.FR]
2021-11-23T05:32:35.715364102Z: [INFO]      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.715368302Z: [INFO]      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.715372902Z: [INFO]      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719456008Z: [INFO]      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719463708Z: [INFO]      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719468709Z: [INFO]      at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.719473209Z: [INFO]      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.719477709Z: [INFO]      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719482209Z: [INFO]      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719497610Z: [INFO]      at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.719502910Z: [INFO]      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.719507111Z: [INFO]      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719511411Z: [INFO]      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719515611Z: [INFO]      at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.719529412Z: [INFO]      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.1.jar!/:5.3.1]
2021-11-23T05:32:35.719533812Z: [INFO]      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719538012Z: [INFO]      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719542212Z: [INFO]      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719546413Z: [INFO]      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719550513Z: [INFO]      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719554813Z: [INFO]      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719559013Z: [INFO]      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719563113Z: [INFO]      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719567314Z: [INFO]      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719572214Z: [INFO]      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719576414Z: [INFO]      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719580514Z: [INFO]      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719584714Z: [INFO]      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719588815Z: [INFO]      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719593015Z: [INFO]      at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) ~[na:na]
2021-11-23T05:32:35.719597015Z: [INFO]      at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) ~[na:na]
2021-11-23T05:32:35.719601115Z: [INFO]      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.39.jar!/:9.0.39]
2021-11-23T05:32:35.719605216Z: [INFO]      at java.base/java.lang.Thread.run(Unknown Source) ~[na:na]
2021-11-23T05:32:35.719609216Z: [INFO]  Caused by: com.microsoft.bot.builder.ActivityHandler$InvokeResponseException: null
2021-11-23T05:32:35.719613216Z: [INFO]      at com.microsoft.bot.builder.ActivityHandler.getAdaptiveCardInvokeValue(ActivityHandler.java:712) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.719621116Z: [INFO]      at com.microsoft.bot.builder.ActivityHandler.onInvokeActivity(ActivityHandler.java:408) ~[bot-builder-4.14.0.jar!/:4.14.0]
2021-11-23T05:32:35.719625517Z: [INFO]      ... 68 common frames omitted
2021-11-23T05:32:35.719629517Z: [INFO]

I've narrowed the issue down to this code in the com.microsoft.bot.builder.ActivityHandler class:
Object obj = activity.getValue();
JsonNode node = null;
if (obj instanceof JsonNode) {
  node = (JsonNode) obj;
} else {
  AdaptiveCardInvokeResponse response = createAdaptiveCardInvokeErrorResponse(
      HttpURLConnection.HTTP_BAD_REQUEST, "BadRequest", "Value property instanceof not properly formed");
  throw new InvokeResponseException(HttpURLConnection.HTTP_BAD_REQUEST, response);
}

From this code I can see that a InvokeResponseException will be thrown if the activity.getValue() object is not an instance of JsonNode.
I went so far as to pull this code out into my own class and logged out the actual object type that was being returned:
Object obj = activity.getValue();
JsonNode node = null;
LOGGER.error("obj type: " + obj.getClass().getName());
if (obj instanceof JsonNode) {
  node = (JsonNode) obj;
} else {
  AdaptiveCardInvokeResponse response = createAdaptiveCardInvokeErrorResponse(
      HttpURLConnection.HTTP_BAD_REQUEST, "BadRequest", "Value property instanceof not properly formed");
  throw new InvokeResponseException(HttpURLConnection.HTTP_BAD_REQUEST, response);
}

The actual object type is java.util.LinkedHashMap.
So what is the solution here? Is there a configuration option that changes how the activity responses are deserialized by a standard chat bot project? I was basing my code off the sample project created with Yeoman yo botbuilder-java -T "echo" described here.
Answer: This does appear to be a bug with the Java Bot Framework SDK, but in the mean time I have worked around the problem with an intermediate class that accepts a Map from activity.getValue() (see the line invokeValue = objectMapper.convertValue(obj, AdaptiveCardInvokeValue.class);):
package com.matthewcasperson;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.bot.builder.ActivityHandler;
import com.microsoft.bot.builder.InvokeResponse;
import com.microsoft.bot.builder.TurnContext;
import com.microsoft.bot.connector.Async;
import com.microsoft.bot.schema.Activity;
import com.microsoft.bot.schema.AdaptiveCardInvokeResponse;
import com.microsoft.bot.schema.AdaptiveCardInvokeValue;
import com.microsoft.bot.schema.Serialization;
import com.microsoft.bot.schema.SignInConstants;
import java.net.HttpURLConnection;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FixedActivityHandler extends ActivityHandler {
  private static final Logger LOGGER = LoggerFactory.getLogger(CateringBot.class);

  @Override
  protected CompletableFuture<InvokeResponse> onInvokeActivity(TurnContext turnContext) {
    if (StringUtils.equals(turnContext.getActivity().getName(), "adaptiveCard/action")) {
      AdaptiveCardInvokeValue invokeValue = null;
      try {
        invokeValue = getAdaptiveCardInvokeValue(turnContext.getActivity());
      } catch (InvokeResponseException e) {
        return Async.completeExceptionally(e);
      }
      return onAdaptiveCardInvoke(turnContext, invokeValue).thenApply(result -> createInvokeResponse(result));
    }

    if (
        StringUtils.equals(
            turnContext.getActivity().getName(), SignInConstants.VERIFY_STATE_OPERATION_NAME
        ) || StringUtils.equals(
            turnContext.getActivity().getName(), SignInConstants.TOKEN_EXCHANGE_OPERATION_NAME
        )
    ) {
      return onSignInInvoke(turnContext).thenApply(aVoid -> createInvokeResponse(null))
          .exceptionally(ex -> {
            if (
                ex instanceof CompletionException
                    && ex.getCause() instanceof InvokeResponseException
            ) {
              InvokeResponseException ire = (InvokeResponseException) ex.getCause();
              return new InvokeResponse(500, "");
            } else if (ex instanceof InvokeResponseException) {
              InvokeResponseException ire = (InvokeResponseException) ex;
              return new InvokeResponse(500, "");
            }
            return new InvokeResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, null);
          });
    }

    CompletableFuture<InvokeResponse> result = new CompletableFuture<>();
    result.complete(new InvokeResponse(HttpURLConnection.HTTP_NOT_IMPLEMENTED, null));
    return result;
  }

  private AdaptiveCardInvokeValue getAdaptiveCardInvokeValue(Activity activity) throws InvokeResponseException {
    if (activity.getValue() == null) {
      AdaptiveCardInvokeResponse response = createAdaptiveCardInvokeErrorResponse(
          HttpURLConnection.HTTP_BAD_REQUEST, "BadRequest", "Missing value property");
      throw new InvokeResponseException(HttpURLConnection.HTTP_BAD_REQUEST, response);
    }

    /*
      The original code required activity.getValue() to be a JsonNode. It is in fact a
      LinkedHashMap, so this change allows the response to proceed.
     */
    Object obj = activity.getValue();
    AdaptiveCardInvokeValue invokeValue = null;
    if (obj instanceof JsonNode) {
      invokeValue = Serialization.treeToValue((JsonNode) obj, AdaptiveCardInvokeValue.class);
    } else if (obj instanceof Map) {
      final ObjectMapper objectMapper = new ObjectMapper();
      objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      invokeValue = objectMapper.convertValue(obj, AdaptiveCardInvokeValue.class);
    } else {
      AdaptiveCardInvokeResponse response = createAdaptiveCardInvokeErrorResponse(
          HttpURLConnection.HTTP_BAD_REQUEST, "BadRequest", "Value property instanceof not properly formed");
      throw new InvokeResponseException(HttpURLConnection.HTTP_BAD_REQUEST, response);
    }
    /*
      End of changes
     */

    if (invokeValue == null) {
      AdaptiveCardInvokeResponse response = createAdaptiveCardInvokeErrorResponse(
          HttpURLConnection.HTTP_BAD_REQUEST, "BadRequest", "Value property instanceof not properly formed");
      throw new InvokeResponseException(HttpURLConnection.HTTP_BAD_REQUEST, response);
    }

    if (invokeValue.getAction() == null) {
      AdaptiveCardInvokeResponse response = createAdaptiveCardInvokeErrorResponse(
          HttpURLConnection.HTTP_BAD_REQUEST, "BadRequest", "Missing action property");
      throw new InvokeResponseException(HttpURLConnection.HTTP_BAD_REQUEST, response);
    }

    if (!invokeValue.getAction().getType().equals("Action.Execute")) {
      AdaptiveCardInvokeResponse response = createAdaptiveCardInvokeErrorResponse(
          HttpURLConnection.HTTP_BAD_REQUEST, "NotSupported",
          String.format("The action '%s'is not supported.", invokeValue.getAction().getType()));
      throw new InvokeResponseException(HttpURLConnection.HTTP_BAD_REQUEST, response);
    }

    return invokeValue;
  }

  private AdaptiveCardInvokeResponse createAdaptiveCardInvokeErrorResponse(
      Integer statusCode,
      String code,
      String message
  ) {
    AdaptiveCardInvokeResponse adaptiveCardInvokeResponse = new AdaptiveCardInvokeResponse();
    adaptiveCardInvokeResponse.setStatusCode(statusCode);
    adaptiveCardInvokeResponse.setType("application/vnd.getmicrosoft().error");
    com.microsoft.bot.schema.Error error = new com.microsoft.bot.schema.Error();
    error.setCode(code);
    error.setMessage(message);
    adaptiveCardInvokeResponse.setValue(error);
    return adaptiveCardInvokeResponse;
  }
}

Using Microsoft adaptive cards in Java


how to send structure as parameter in python

Question: I am using boost python for  interoperability between C++ and the Python . i have enum and structure in c++ and have function in c++ that can take these structure as a parameter. and  i am able to access this function in python by using boost python but i don't know how to send structure as parameter in python. Set is function in c++ that can get structure as parameter.so in python how can i send this structure as a parameter . i am able to get this function in python but not able to send send structure as parameter. thanks for the help.
structure in c++ is as follow:
enum days
{
  friday,
  saturday
};
struct example
 {
    days m_day;
    std: string m_value;
 };

Class Base
 {
   public:
   void Set(example& Result) = 0;
  }
class Derived
{
  public:
  void Set(example& Result)
  {
    Result.m_day = friday;
   }

Comment: no i want to send structure as pyrameter from python to c++.
Comment: Maybe this could help you ? [send-receive-cstruct-using-python](http://stackoverflow.com/questions/6037555/how-to-elegantly-send-receive-a-large-c-struct-using-python)
Comment: how can i send empty structure from python that it can assess the Structurevalue of c++?not able to send Structure from python
Comment: Expose the enum and struct via [`boost::python::enum`](http://www.boost.org/doc/libs/1_55_0/libs/python/doc/v2/enum.html) and [`boost::python::class_`](http://www.boost.org/doc/libs/1_55_0/libs/python/doc/v2/class.html#class_-spec).  Boost.Python will handle converting to-and-from the struct and the associated Python types.
Comment: Problem is that how can i send empty structure from python that it can  access the structure in c++.
Answer: You have to expose structure example like this and then create a variable of this structure in python and send this variable as argument.
Class_<example> ("example")
.def_readwrite("m_day" , & example:: day)
.def_readwrite("m_value" , & example:: m_value)
;

Hope this will help..


Configuration of IPv6 on Debian 9 on OpenVZ

Question: Is there any information on configuring IPv6 on an Debian 9 VPS running on OpenVZ? I have a VPS which was running an older version of Debian on OpenVZ which I needed to upgrade to support some newer software. After the upgrade my IPv6 interface configuration does not seem to be working. IPv6 was working just fine before upgrading Debian on the same VPS.
The auto-generated /etc/network/interfaces (which was working before) is:
auto venet0
iface venet0 inet manual
        up ifconfig venet0 up
        up ifconfig venet0 127.0.0.2
        up route add default dev venet0
        down route del default dev venet0
        down ifconfig venet0 down

iface venet0 inet6 manual
        up ifconfig venet0 add 2604:880:26::a4cd:e7e/128
        down ifconfig venet0 del 2604:880:26::a4cd:e7e/128
        up route -A inet6 add default dev venet0
        down route -A inet6 del default dev venet0

auto venet0:0
iface venet0:0 inet static
        address 22.214.171.124
        netmask 255.255.255.255

So it appears I should also be able to configure IPv6 from the command line with ifconfig or ip address add commands but when I do I receive "no buffer space available messages (see below):
root@dal1:/# ifconfig venet0 add 2604:880:26::a4cd:e7e/128
SIOCSIFADDR: No buffer space available
root@dal1:/# ip address add 2604:880:26::a4cd:e7e/128 dev venet0
RTNETLINK answers: No buffer space available

Comment: Why are you using `up`/`down` commands instead of the normal `address` `netmask` and `gateway`?
Comment: Unsure. The original OpenVZ template which the VPS provider deployed the machine with had it that way. Not being an OpenVZ expert I assumed that it was something related to the OpenVZ environment.
Answer: It may be a MTU related problem.
Try adding mtu 1500 or some other sensible values in your add operation. If this solves the problem, the correct value to use will depend on your provider, so ask him what to use.
A change of version may have changed the default value of the MTU if not provided, and based in some reports it seems to be sometimes 0 as default, so that can not work.
Comment: I saw some references to the MTU issue in my googling as well. In checking it though it was already set to 1500. I tried resetting it to 1500 and applying an IP address again but still had the same problem.


Erro PHP Parse error: syntax error, unexpected '"', expecting T_STRING or T_VARIABLE or T_NUM_STRING

Question: Eu preciso fazer uma validação, se for verdadeiro vai para um link e se for falso vai para outro lugar.
meu código é seguinte.
<a href='<?php if($dado['st_nome'] =="FINALIZADO")
{echo "dashboard.php?link=17&id=<?php echo $dado["op_id"];?>";}
else{ echo '#';}?>'>

Mas está me retornando o
PHP Parse error:  syntax error, unexpected '"', expecting T_STRING or T_VARIABLE or T_NUM_STRING in E:\home\gigaclima\Web\giga_proj\paginas\listas\listar_op.php on line 50
Algo no código está gerando um conflito que não consigo identificar.
Answer: Uma vez que já estás no PHP não precisas abrir novamente, entendes?
O correto seria assim:
<a href='<?php if($dado['st_nome'] =="FINALIZADO")
{echo "dashboard.php?link=17&id={$dado['op_id']}";}
else{ echo '#';} ?>'>

Mas eu aconselhava-te a fazer assim:
<?php
if( $dado['st_nome'] == "FINALIZADO" )
    $link = "dashboard.php?link=17&id=".$dado["op_id"];
else
    $link= "#";
?>
<a href='<?php echo $link; ?>'>

Para ter o mínimo de PHP no meio do HTML. Fica menos confuso.
Answer: Acho que ainda pode utilizar um ternário como opção:
<?php
     $dado['st_nome'] == "FINALIZADO" ?  $link = "dashboard.php?link=17&id=".$dado["op_id"]: $link= "#";
?>

<a href='<?php echo $link; ?>'>

Answer: Seu código estava escrito errado, segue a correção do mesmo, sem alteração no seu estilo:
<a href='<?php
    if($dado['st_nome'] =="FINALIZADO"){
        echo "dashboard.php?link=17&id=" .  $dado["op_id"];
    }else{
        echo '#';
    } ?>'>Link

Também tem a versão postada por Jorge B., que separa o PHP do HTML e deixa o código mais limpo.


How to know if my XML Sitemap being submitted?

Question: I've configured the XML Sitemap and Site verification modules, but I don't see the sitemap being submitted to Google. If I enter the Google Webmaster tools it says no sitemaps were submitted, but maybe it doesn't show those posted via API or something.
How could I know if it's being actually submitted? Thanks.
Comment: Are you sure these two modules will do the submission?  I always do it manually in my GWT, Yahoo and Bing accounts.  Spiders will find them anyway, even if you don't submit.
Answer: If you are using Drupal 7, it will show that your sitemaps have been submitted in your log messages at Admin > Reports > Recent Log Messages (/admin/reports/dblog)
Click on "Filter log messages" and select "xmlsitemap"
If you do this, it will show when the last sitemap was generated and when it was submitted the the search engines that you have configured it to submit to (in my case, Google and Bing).


How do you remove a user role via a hook update?

Question: I would like to remove a user role via a hook update in Drupal 9.
I believe I would need to do something like the below but unclear what other code might be needed.
<code>$user->removeRole('administrator');
$user->save();
</code>
Comment: Search for drupal batch process update hook. Because when you want to process a lot of users you may want to prevent timeouts when your update hook runs.
Comment: Are you trying to remove a role from a specific user? Or delete the role so that it no longer exists in the system and can't be assigned to any user?
Comment: First remove the role for all users who have the assigned role. Then delete the role so that it no longer exists in the system and can't be assigned to any user.
Answer: First, load all your users having the role you wish to delete:
<code>$usersHavingRole = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(['roles' => 'my_role']);
</code>
Then, for each user, remove the role (this is the code you mentioned):
<code>foreach($usersHavingRole as $user) {
  $user->removeRole('my_role');
  $user->save();
}
</code>
And finally, delete the role:
<code>$role = \Drupal\user\Entity\Role::load('my_role');
if (!empty($role)) {
  $role->delete();
}
</code>
Comment: I guess OP is more in search of actual update hook code implementing a batch process at best.


Converter String de uma div para int e fazer uma operação matemática

Question: estou tentando fazer a seguinte função:
    R$ 71,90

    function calculaParcela(){
    var regex = /\d+,\d+/g;
    var texto = $(".our_price_display").text(); //id da div com o texto R$ 71,90
    var valor = regex.exec(texto);
    var insereValor = $("#valor-parcelado").text(valor.join(""));

    console.log(insereValor);

    var divide = insereValor / 3;

    console.log(divide);
}

Porém no console ele me Retorna NaN.
em que estou errando e o que poderia ser feito pra corrigir esta operação?
Answer: NaN é um erro retornado para não numérico (not a number). Você terá que converter pra número usando parseFloat:

$("button").click(function() {
  $("#resultado").text(calculaParcela());
});

function calculaParcela() {
  var regex = /\d+,\d+/g;
  var texto = $("#our_price_display").text(); //id da div com o texto R$ 170
  var valor = regex.exec(texto);
  var insereValor = parseFloat(valor.join("").replace(",","."));
  var divide = insereValor / 3;
  return divide;
}

R$ 71,90

<button>Só valor</button>
Comment: Cara, deu certinho! Muito obrigadooo!


Solving a problem without using the Riemann - Roch theorem

Question: I am studying elliptic curves and I faced with the concept of the divisors and Riemann Roch Theorem. My reference is " The Arithmetic of The Elliptic Curves " of Silverman .
I tried to solve one of the exercises that stats:
Let C be smooth curve and let  $ D \in Div(C) $. With out using the Riemann - Roch, Prove the following :
1 - $ L(D)$ is a $ \bar K -$vector space.
2- If $ Deg(D) \geq 0,$ then : $$ l(D) \leq deg (D) + 1 $$
 I  could solve the first part, but I can not solve the second. I was wondering if somebody helps me to prove it or give me a hint.
Comment: Do you mean $l(D)\le\deg(D)+1$?
Comment: yes. Sorry, I corrected it.
Answer: If $D$ has negative degree, then $l(D)=0$. So start an induction on the degree
starting with $\deg D=-1$. In general, write $D=D'+(P)$ for some point $P$.
It suffices to prove $l(D)\le l(D')+1$. Otherwise one must have $L(D)$
properly containing $l(D')$. Let $f$, $g\in L(D)-L(D')$. Then $f$ and $g$
have the same order  at $P$, and so $f-ag$ has degree at one higher
for a suitable scalar, so $f-ag\in L(D')$. This shows $\dim(L(D)/L(D'))\le1$,
that is $l(D)-L(D')\le1$.
Comment: Thanks! But I can't understand why such that "a" should   exist?
Comment: If such that "a" there exist, the proof completes!


Criar um arquivo *.csv com dados encontrados de um arquivo

Question: Estou desenvolvendo um projeto que extrai informações de um arquivo *.pdf, estava salvando essas informações em um arquivo *.txt, mas agora me foi pedido que essas informações fossem salvas no formato de uma planilha, quero criar um arquivo *.csv, porém a única forma que encontrei de criar o arquivo seria determinando o que estaria escrito em cada coluna, mas preciso é colocar o valor das variáveis nessas coluna.
public class modelo {

public static void main(String[] args) {
    System.out.println("inicio");
    Timer timer = null;
    if (timer == null) {
        timer = new Timer();
        TimerTask tarefa = new TimerTask() {
            public void run() {
                try {

                    File diretorio = new File("C//teste//");
                    File[] arquivos = diretorio.listFiles();

                    if (arquivos != null) {

                        for (int x = 0; x < arquivos.length; x++) {

                            if (arquivos[x].getName().endsWith("pdf")) {

                                File f = arquivos[x];
                                try (RandomAccessBufferedFileInputStream acesso = new RandomAccessBufferedFileInputStream(f.getAbsolutePath())) {
                                    PDFParser parser = new PDFParser(acesso);
                                    parser.parse();
                                    COSDocument cosDoc = parser.getDocument();
                                    PDFTextStripper pdfStripper = new PDFTextStripper();
                                    PDDocument pdDoc = new PDDocument(cosDoc);

                                    BufferedWriter StrW = new BufferedWriter(new FileWriter("C//teste2//" + f.getName().replace(".pdf", ".csv")));

                                    List<String> linhasGravadas = new ArrayList<>();

                                    int teste = 0, Aut = 0, vAut = 0;
                                    StrW.write("Página;Autotrização;Status Leitura;Retorno Ticket Log");

                                    for (int i = 1; i <= pdDoc.getNumberOfPages(); i++) {
                                        pdfStripper.setStartPage(i);
                                        pdfStripper.setEndPage(i);
                                        String parsedText = pdfStripper.getText(pdDoc);

                                        String aut = "";
                                        String Status = "";

                                        int AUT = 0;

                                        Matcher matcherAut = Pattern.compile("\\s\\b00\\d{7}\\b|\\b[3-9]\\d{8}\\b").matcher(parsedText);

                                        if (!matcherAut.find()) {
                                            vAut = vAut + 1;
                                            AUT = AUT + 1;
                                            aut = "-";
                                            Status = "Nao Lido";
                                        } else {
                                            Pattern pattern = Pattern.compile("\\s^0.*|^0.*"); // Segundo Filtro (Elimina os que não começam com 3|4)
                                            Scanner scanner = new Scanner(matcherAut.group()).useDelimiter(pattern);
                                            Matcher matcher2 = pattern.matcher(aut);
                                            while (scanner.hasNext()) {
                                                aut = scanner.next();
                                                if (!linhasGravadas.contains(aut)) {
                                                    linhasGravadas.add(aut);
                                                    Aut = Aut + 1;
                                                    Status = "Lido";
                                                }
                                            }
                                        }
                                        StrW.write(i,teste,status); // AQUI FICARIA AS VARIAVEIS
                                        linhasGravadas.clear(); // LIMPAR ARRAY DE TODOS OS DADOS ENCONTRADOS
                                    }
                                    acesso.close();
                                }
                                f.renameTo(new File("C//testes3//", f.getName()));
                            }

                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace(); // Tratar a exceção adequadamente.
                }
            }
        };
    }
}

}
Comment: Eu não consegui entender onde reside o seu problema. Crie uma planilha em Excel como você imagina e após salve-a em CSV para ver como fica. É simples. Apenas que a primeira linha contém a linha de cabeçalho e as linhas de abaixo com todos os valores separados por ponto e virgula.
Comment: Pois é, é simples se eu coloco o valor das linhas `StrW.write("1;123456789;Lido");` mas se eu quero colocar o valor de variáveis nessas linha da erro, por exemplo `StrW.write(pagina;autorizacao;status);`
Comment: Com certeza. Não é possível fazer isso. As variáveis tem de ser resolvidas para o Excel. A não ser que o programa que vai ler esse arquivo saiba como resolver essas variáveis, ou alguma coisa assim:     `StrW.write(pagina.value.toString();autorizacao.value.toString();status.value );` supondo, claro, que essas variaveis tenham esses métodos.
Comment: Cara bem a verdade, eu não entendi o que tu quis dizer, mas obrigado pela ajuda de qualquer forma
Answer: Consegui gerar um arquivo como precisava a partir deste código:
for (int i = 1; i <= pdDoc.getNumberOfPages(); i++) {
                                        pdfStripper.setStartPage(i);
                                        pdfStripper.setEndPage(i);
                                        String parsedText = pdfStripper.getText(pdDoc);

                                        //<editor-fold defaultstate="collapsed" desc="VARIAVEIS STRINGS">
                                        String aut = "";
                                        String Status = "";
                                        String pagina = Integer.toString(i);
                                        //</editor-fold>

                                        //<editor-fold defaultstate="collapsed" desc="VARIAVEIS "INT" REUTILIZADAS EM CADA PÁGINA">
                                        int AUT = 0;
                                        //</editor-fold>

                                        //<editor-fold defaultstate="collapsed" desc="MATCHER - EXPRESSÕES REGULARES">
                                        Matcher matcherAut = Pattern.compile("\\s\\b00\\d{7}\\b|\\b[3-9]\\d{8}\\b").matcher(parsedText);
                                        //</editor-fold>

                                        //<editor-fold defaultstate="collapsed" desc="MATCHER AUTORIZAÇÃO">
                                        if (!matcherAut.find()) {
                                            Status = "Não Lido";
                                            aut = "-";
                                        } else {
                                            Pattern pattern = Pattern.compile("\\s");
                                            Scanner scanner = new Scanner(matcherAut.group()).useDelimiter(pattern);
                                            Matcher matcher2 = pattern.matcher(aut);
                                            while (scanner.hasNext()) {
                                                aut = scanner.next();
                                                if (!linhasGravadas.contains(aut)) {
                                                    linhasGravadas.add(aut);
                                                    Aut = Aut + 1;
                                                    Status = "Lido";
                                                }
                                            }
                                        }
                                        StrW.write(pagina+";");
                                        StrW.write(aut+";");
                                        StrW.write(Status+"\n");
                                        //</editor-fold>

                                        linhasGravadas.clear(); // LIMPAR ARRAY DE TODOS OS DADOS ENCONTRADOS
                                    }


Equality involving Taylor coefficients

Question: Considering the following series expansion
$$
\frac{1}{{1 - 2x - x^2 }} = \sum\limits_{n = 0}^\infty  {a_n } x^n
$$
prove that $
\forall n,\,\exists m
$ such that $
a_n ^2  + a_{n + 1} ^2  = a_m
$
I tried proving this using the coefficients computed by Wolfram but it didn't really help.
Any ideas?
Answer: First find the zeros of $1-2x-x^2$:
$$x=\frac{-2\pm\sqrt{4+4}}2=1\pm\sqrt2\;.$$
Let $\alpha=1+\sqrt2$ and $\beta=1-\sqrt2$; then
$$(1-\alpha x)(1-\beta x)=1-(\alpha+\beta)x+\alpha\beta x^2=1-2x-x^2\;,$$
so you can decompose $\frac1{1-2x-x^2}$ into partial fractions with denominators $1-\alpha x$ and $1-\beta x$ as
$$\frac1{1-2x-x^2}=\frac{A}{1-\alpha x}+\frac{B}{1-\beta x}\;.$$
I'll leave it to you to calculate $A$ and $B$. Then observe that
$$\begin{align*}
\frac{A}{1-\alpha x}+\frac{B}{1-\beta x}&=A\sum_{n\ge 0}\alpha^nx^n+B\sum_{n\ge 0}\beta^nx^n\\\\
&=\sum_{n\ge 0}\left(A\alpha^n+B\beta^n\right)x^n\;,
\end{align*}$$
so $a_n=A\alpha^n+B\beta^n$, and
$$a_n^2+a_{n+1}^2=\left(A\alpha^n+B\beta^n\right)^2+\left(A\alpha^{n+1}+B\beta^{n+1}\right)^2\;.\tag{1}$$
Expand $(1)$ and collect terms, and with a little work you can find $m$ (in terms of $n$) such that it equals
$$A\alpha^m+B\beta^m=a_m\;.$$

Equality involving Taylor coefficients


MySQL Crashing and failing to restart

Question: MySQL seems to be crashing, normally later in the day but I can't see why! It says out of memory but there is loads of free ram and no swap space being used. I'm using Azure.
Here is the log:
Oct  3 20:42:20 GenyxLive kernel: [787828.711240] Out of memory: Kill process 53891 (mysqld) score 84 or sacrifice child
Oct  3 20:42:20 GenyxLive kernel: [787828.714081] Killed process 53891 (mysqld) total-vm:871780kB, anon-rss:58164kB, file-rss:0kB
Oct  3 20:42:20 GenyxLive kernel: [787828.731974] init: mysql main process (53891) killed by KILL signal
Oct  3 20:42:20 GenyxLive kernel: [787828.733525] init: mysql main process ended, respawning
Oct  3 20:42:20 GenyxLive kernel: [787828.974636] init: mysql main process (24975) terminated with status 1
Oct  3 20:42:20 GenyxLive kernel: [787828.974666] init: mysql main process ended, respawning
Oct  3 20:42:21 GenyxLive kernel: [787829.937186] init: mysql post-start process (24976) terminated with status 1
Oct  3 20:42:22 GenyxLive kernel: [787830.103158] init: mysql main process (25002) terminated with status 1
Oct  3 20:42:22 GenyxLive kernel: [787830.103194] init: mysql respawning too fast, stopped

Here's the graph of whats happening:

You can see a spike of cpu and then the mysql service stops...
Can anyone help me figure out whats happening?
Ubuntu 12.04
Azure Small (768mb ram, 1ghz cpu)
EDIT
There is a cron job that runs every 5 mins which just checks for new domains etc (using zpanel).
Its a 64 bit OS
Linux GenyxLive 3.2.0-48-virtual #74-Ubuntu SMP Thu Jun 6 20:02:55 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

free -lm result:
             total       used       free     shared    buffers     cached
Mem:           672        491        180          0         42        118
Low:           672        491        180
High:            0          0          0
-/+ buffers/cache:        330        341
Swap:            0          0          0

cat /proc/meminfo result:
MemTotal:         688348 kB
MemFree:          186788 kB
Buffers:           43956 kB
Cached:           120988 kB
SwapCached:            0 kB
Active:           335908 kB
Inactive:          84924 kB
Active(anon):     255976 kB
Inactive(anon):      296 kB
Active(file):      79932 kB
Inactive(file):    84628 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:             0 kB
SwapFree:              0 kB
Dirty:                16 kB
Writeback:             0 kB
AnonPages:        255924 kB
Mapped:            18568 kB
Shmem:               376 kB
Slab:              51788 kB
SReclaimable:      37052 kB
SUnreclaim:        14736 kB
KernelStack:        1344 kB
PageTables:         7632 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:      344172 kB
Committed_AS:     967220 kB
VmallocTotal:   34359738367 kB
VmallocUsed:       13192 kB
VmallocChunk:   34359723128 kB
HardwareCorrupted:     0 kB
AnonHugePages:         0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:       51136 kB
DirectMap2M:      735232 kB

Answer: Kernel OOM only kicks in when it considers resources are really tight... so you must be running out of memory but the chart doesn't make much sense then.
What does free -lm show?
Also, what does cat /proc/meminfo show?
In terms of a trigger for the issue, does some maintenance process or other cron job run around this time which might be doing queries where mysql needs to maintain temp tables in memory?
BTW... is this a 32-bit version of the OS?  Just wondering if your low memory is exhausted.
EDIT 1
  Ok.  Well, mysqld will be the single most memory consuming process so that is most likely why it is being picked on.  Check your apache config to see how may worker threads you are spawning... each will have a memory overhead and it is possible that when more spawn you run out of memory as you have no swap space.  Check your MaxClients parameter... if you have any more than 50 (just a ballpark figure) this might be a good place to look.  Might I recommend taking a look at Apache Performance Tuning.
Comment: Welcome to server fault!  Soon you will have enough reputation to leave comments on questions, so that you can ask for clarification from the author.
Comment: I have edited my question to answer your questions, thanks

MySQL Crashing and failing to restart


update previous row sql server

Question: Basically I want to update previous row based on value with same value others field
let say something like this :

I want to update an empty cell with previous value from previous record with same date, tr, sh.
I try something like this, but I think not correct
UPDATE #temptable
  SET
      tk = b.tk
FROM
(
    SELECT DISTINCT
           a.datetime,
           a.date,
           a.tr,
           a.sh,
           b.tk
    FROM
    (
        SELECT sh,
               tr,
               date,
               datetime
        FROM #temptable
        WHERE tk = 0
    ) a
    INNER JOIN
    (
        SELECT sh,
               tr,
               date,
               datetime,
               tk
        FROM #temptable
        WHERE tk != 0
    ) b ON(a.sh = b.sh
           AND a.tr = b.tr
           AND a.date = b.date
           AND a.datetime >= b.datetime)
) b
WHERE #temptable.tr = b.tr
      AND #temptable.date = b.date
      AND (#temptable.tk = 0
           OR #temptable.tk IS NULL);

need your suggestion about this case.
thank you
Comment: Show us some sample data and expected output instead of images .So,that people can help you out.Many of the user's won't have the access to open the pictures.
Answer: LAG can be used for this.
update #temptable set tk = b.tk
from (select a.datetime,
           a.date,
           a.tr,
           a.sh,
           ISNULL(LAG(tk) OVER(PARTITION BY d, t, tr, sh ORDER BY d, t, tr, sh) , tk) tk
from #temptable a) b

I made a testtable containing the two rows in your example and that part worked for me. Let me know if you are having further issues
Comment: hi @Zulatin this is not worked for me, it just switch value, sorry for late response
Comment: If you give me more data to work with, ill update my solution.
Answer: UPDATE #temptable AS R INNER JOIN #temptable AS P ON R.date= P.date
 AND R.TR = P.TR AND R.SH = P.SH AND P.TK != '' SET R.tk = P.tk WHERE R.tk = ''

Try to use update inner join
Answer: use CTE to check first and update the values. I assume u have multiple rows to be updated
DECLARE @temp TABLE (DATETIME DATETIME, DATE DATE, tr INT, sh INT, tk VARCHAR(255))

INSERT INTO @temp (DATETIME, DATE, tr, sh, tk)
SELECT '2018-02-06 00:00:00', '2018-02-06', 447, 2144, '10000001'

UNION ALL

SELECT '2018-02-06 00:00:00', '2018-02-06', 447, 2144, '';

WITH Opt
AS (
    SELECT *
    FROM @temp t
    WHERE t.tk = '' AND EXISTS (
            SELECT *
            FROM @temp x
            WHERE cast(x.DATETIME AS DATE) = cast(t.DATETIME AS DATE) AND x.DATE = t.DATE AND x.tr = t.tr AND x.sh = t.sh AND x.tk <> t.tk
            )
    )
UPDATE Opt
SET tk = t.tk
FROM opt x
INNER JOIN @temp t
    ON cast(x.DATETIME AS DATE) = cast(t.DATETIME AS DATE) AND x.DATE = t.DATE AND x.tr = t.tr AND x.sh = t.sh AND x.tk <> t.tk

SELECT *
FROM @temp

update previous row sql server


ImageEdgeInsets Square Aspect Ratio

Question: Is it possible to use ImageEdgeInsets to constrain an image to a square size? I have a UI Image inside of a button and I would like to make it a square size inside the button. Does ImageEdgeInsets offer the ability to maintain an aspect ratio? Thanks!
Answer: To maintain the aspect ratio, you should have a look here (it doesn't use ImageEdgeInsets)

ImageEdgeInsets Square Aspect Ratio


angular material (datepicker) focus is on body after any keyboard based operation

Question: its seems that every operation with the date-picker don't return the focus back to the date picker input or button and as a result the tab indexing is back to the first element.
you can take example with the official demo : https://material.angularjs.org/latest/demo/datepicker
looking at the sources and debugging - its seems that focus operation is triggered on the relevant element but even so - the focus changed to to the document body.
<code> /** Close the floating calendar pane. */
  DatePickerCtrl.prototype.closeCalendarPane = function() {
    if (this.isCalendarOpen) {
      var self = this;

      self.calendarPaneOpenedFrom.focus();
      self.calendarPaneOpenedFrom = null;

      if (self.openOnFocus) {
        // Ensures that all focus events have fired before detaching
        // the calendar. Prevents the calendar from reopening immediately
        // in IE when md-open-on-focus is set. Also it needs to trigger
        // a digest, in order to prevent issues where the calendar wasn't
        // showing up on the next open.
        this.$mdUtil.nextTick(detach);
      } else {
        detach();
      }
    }

    function detach() {
      self.detachCalendarPane();
      self.isCalendarOpen = false;
      self.ngModelCtrl.$setTouched();

      self.documentElement.off('click touchstart', self.bodyClickHandler);
      window.removeEventListener('resize', self.windowResizeHandler);
    }
  };
</code>
10x
elad.
Comment: please refer to https://github.com/angular/material/issues/8960#issuecomment-230820518
Answer: There was a bug in the datepicker focus issue caused because the SVG element inside didn't propagate the focus event.
solved by crisbeto.
ref : https://github.com/crisbeto/material/commit/e8d4ad217dd2ad5a8e8875f9bdc1269679667e3b


Definição de WSDL levantando exceção

Question: Olá, venho há uns dias tentando definir um wsdl de um componente que utiliza SOAP para um projeto SOA que mistura diversos tipos de serviços, integrando-os com camel. Porém estou travado num problema que não vejo sentido na resposta que ele me dá, que acredito ser puramente da definição do serviço.
Esse é o meu wsdl:

<wsdl:types>
    <xsd:schema targetNamespace="http://soapadapter.goodbooze.marlo.com.au/services/EntryService">
        <xsd:import schemaLocation="../entities/entryRequest.xsd"
                    namespace="http://soapadapter.goodbooze.marlo.com.au/entities/entryRequest"/>

        <xsd:import schemaLocation="../entities/entryResponse.xsd"
                    namespace="http://soapadapter.goodbooze.marlo.com.au/entities/entryResponse"/>

        <xsd:import schemaLocation="../entities/soapFault.xsd"
                    namespace="http://soapadapter.goodbooze.marlo.com.au/entities/soapFaultMessage"/>
    </xsd:schema>
</wsdl:types>

<wsdl:message name="entryRequest">
    <wsdl:part name="parameters" element="req:entryRequest"/>
</wsdl:message>

<wsdl:message name="entryResponse">
    <wsdl:part name="parameters" element="res:entryResponse"/>
</wsdl:message>

<wsdl:message name="entryRequestError">
    <wsdl:part name="soapChannelFault" element="sf:soapFaultMessage"/>
</wsdl:message>

<wsdl:portType name="entryService">
    <wsdl:operation name="postEntry">
        <wsdl:input message="entryRequest"/>
        <wsdl:output message="entryResponse"/>
        <wsdl:fault name="fault" message="entryRequestError" />
    </wsdl:operation>
</wsdl:portType>

    <wsdl:binding name="entryServiceBinding" type="entryService">
        <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>

        <wsdl:operation name="postEntry">
            <soap:operation soapAction="action" style="document"/>

            <wsdl:input >
                <soap:body use="literal" parts="parameters"/>
            </wsdl:input>

            <wsdl:output >
                <soap:body use="literal" />
            </wsdl:output>

            <wsdl:fault name="fault">
                <soap:fault name="fault" use="literal"/>
            </wsdl:fault>

    </wsdl:operation>
</wsdl:binding>

<wsdl:service name="publishEntryService">
    <wsdl:port name="entryService" binding="entryServiceBinding">
        <soap:address location="http://localhost:8383/insertEntry/publishentry"/>
    </wsdl:port>
</wsdl:service>

Vou pôr as definições das mensagens aqui também, para verem que o problema não é elas, de fato:
EntryRequest:
<xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns="http://www.w3.org/2001/XMLSchema"
    xmlns:au="http://soapadapter.goodbooze.marlo.com.au/entities/Entry"
    xmlns:ms="http://soapadapter.goodbooze.marlo.com.au/entities/entryRequest"
    targetNamespace="http://soapadapter.goodbooze.marlo.com.au/entities/entryRequest"
    elementFormDefault="qualified">
<xs:import namespace="http://soapadapter.goodbooze.marlo.com.au/entities/Entry"
           schemaLocation="entryDefinitions.xsd"/>
<xs:element name="entryRequest">
    <xs:complexType>
        <sequence>
            <xs:element name = "entry" type = "au:entryType"  minOccurs="1" maxOccurs="1"/>
        </sequence>
    </xs:complexType>
</xs:element>

EntryResponse:
<xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns="http://www.w3.org/2001/XMLSchema"
    xmlns:au="http://soapadapter.goodbooze.marlo.com.au/entities/Entry"
    xmlns:ms="http://soapadapter.goodbooze.marlo.com.au/entities/entryResponse"
    targetNamespace="http://soapadapter.goodbooze.marlo.com.au/entities/entryResponse"
    elementFormDefault="qualified">
<xs:import namespace="http://soapadapter.goodbooze.marlo.com.au/entities/Entry"
            schemaLocation="entryDefinitions.xsd"/>
<xs:element name="entryResponse">
    <xs:complexType>
        <sequence>
            <xs:element name = "entryResponse" type = "xs:string"/>
        </sequence>
    </xs:complexType>
</xs:element>

SoapFault:
<xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns="http://www.w3.org/2001/XMLSchema"
    xmlns:au="http://soapadapter.goodbooze.marlo.com.au/entities/Entry"
    xmlns:ms="http://soapadapter.goodbooze.marlo.com.au/entities/soapFaultMessage"
    targetNamespace="http://soapadapter.goodbooze.marlo.com.au/entities/soapFaultMessage"
    elementFormDefault="qualified">
<xs:import namespace="http://soapadapter.goodbooze.marlo.com.au/entities/Entry"
        schemaLocation="entryDefinitions.xsd"/>
<xs:element name="soapFaultMessage">
    <xs:complexType>
        <sequence>
            <xs:element name = "errorMessage" type = "au:errorMessageType"  />
        </sequence>
    </xs:complexType>
</xs:element>

E o xsd que define os tipos:

<xs:complexType name = "productType">
    <xs:sequence>
        <xs:element name = "internalID" type="xs:int"  minOccurs="1" maxOccurs="1"/>
        <xs:element name = "name" type="xs:string"  minOccurs="1" maxOccurs="1"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name = "storeType">
    <xs:sequence>
        <xs:element name = "storeID" type = "xs:int"  minOccurs="1" maxOccurs="1"/>
        <xs:element name = "name" type = "xs:string"  minOccurs="1" maxOccurs="1"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name = "itemStoreOrderType">
    <xs:sequence>
        <xs:element name="quantity" type="xs:long"  minOccurs="1" maxOccurs="1"/>
        <xs:element name="product" type="au:productType" minOccurs="1" maxOccurs="1"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name = "storeOrderType">
    <xs:sequence>
        <xs:element name ="storeOrderID" type="xs:int"  minOccurs="1" maxOccurs="1"/>
        <xs:element name = "store" type="au:storeType" minOccurs="1" maxOccurs="1"/>
        <xs:element name = "itemStoreOrderList" type = "au:itemStoreOrderType" maxOccurs = "unbounded" minOccurs = "1"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name = "entryType">
    <xs:sequence>
        <xs:element name = "insertDate" type = "xs:string" />
        <xs:element name = "storeOrder" type = "au:storeOrderType" maxOccurs = "unbounded" minOccurs = "1"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="errorMessageType">
    <xs:sequence>
        <xs:element name = "errorCode" type="xs:string" minOccurs="1" maxOccurs="1"/>
        <xs:element name = "errorCause" type="xs:string" minOccurs="1" maxOccurs="1"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="successMessageType">
    <xs:sequence>
        <xs:element name = "successMessage" type="xs:string" fixed="DONE." minOccurs="1" maxOccurs="1"/>
    </xs:sequence>
</xs:complexType>

Essa é a forma que fiz a definição das rotas. Ela basicamente define o tratamento dos erros, e, caso não haja, transforma o dado de entrada, repassa para outro endpoint e então processa um response:
onException(Exception.class)
            .log("${body}")
            .log(LoggingLevel.ERROR, "An error was found.")
            .process(new SOAPFaultProcessor())
            .handled(true);

    from("cxf:bean:insertEntry")
        .routeId("LegacySystemMessage")
        .log("${body}")
        .to("xquery:process/xquery/getListOfOrders.xq")
        .inOnly("jms:queue:orderManager")
        .process(new ResponseSucessProcessor())
        .log(LoggingLevel.INFO, "Response message: ${body}");

E as classes que o process chamam são bem simples também
ResponseSuccessProcessor:
public class ResponseSucessProcessor implements Processor {

@Override
public void process(Exchange exchange) throws Exception {

    StringWriter writer = new StringWriter();
    EntryResponse response = new EntryResponse();
    response.setEntryResponse("Message received");

    JAXBContext jxb = JAXBContext.newInstance(EntryResponse.class);
    Marshaller m = jxb.createMarshaller();

    m.marshal(response, writer);
    exchange.getOut().setBody(writer.toString());
}

}
E a SOAPFaultProcessor:
public class SOAPFaultProcessor implements Processor {

@Override
public void process(Exchange exchange) throws Exception {

    Exception exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);

    SoapFault fault = new SoapFault(exception.getMessage(), SoapFault.FAULT_CODE_SERVER);

    SoapFaultMessage soapFaultMessage = new SoapFaultMessage();
    ErrorMessageType errorMessageType = new ErrorMessageType();

    errorMessageType.setErrorCode(fault.getCode());
    errorMessageType.setErrorCause("Something wrong happened");

    soapFaultMessage.setErrorMessage(errorMessageType);

    StringWriter writer = new StringWriter();
    JAXBContext jxb = JAXBContext.newInstance(SoapFaultMessage.class);
    Marshaller marshaller = jxb.createMarshaller();
    marshaller.marshal(soapFaultMessage, writer);

    exchange.getOut().setFault(true);
    exchange.getOut().setBody(writer.toString());

}

Dessa forma, quando tento simular o serviço utilizando o SOAPUI, ele me dá a seguinte mensagem de erro
<faultstring>Part {http://soapadapter.goodbooze.marlo.com.au/services/EntryService}parameters should be of type au.com.marlo.goodbooze.soapadapter.entities.entryresponse.EntryResponse, not java.lang.String</faultstring>

A mensagem dá a entender que as definições do WSDL está errada, mas já chequei várias vezes e não consigo perceber nada que justifique essa mensagem. Será que alguém consegueria me ajudar a perceber o que é que está ocasionando essa resposta? Obrigado.
Answer: Parece que o erro vem pelo attributo parts qie está a utilizar no operation > bindings.

            <wsdl:operation name="postEntry">
                <soap:operation soapAction="action" style="document"/>

                <wsdl:input >
                    <soap:body use="literal" **parts="parameters"**/>
                </wsdl:input>
            ...

Experimente retirar esse parts="parameters".
Answer: O problema era bem simples, era só porque meu ResponseSucessProcessor estava devolvendo uma String como resposta, e o que o wsdl estava esperando era o objeto EntryResponse direto, e não uma conversão.

Definição de WSDL levantando exceção


How to Use NVD3.JS or D3.JS library to build Dashboard in OpenERP V7?

Question: I'm having a dataset, and I would like to visualize it in a dashboard on Odoo/OpenERP V7. Is there a way, I can import with it D3.JS or NVD3.JS charts into odoo and visualize them there?
Else, how can I visualize a bunch of CSV files on a dashboard in Odoo/OpenERP?
Answer: At the end, I used the dashboard module integrated in the OpenERP V7, using the graph tags in the xml file. Doesn't provide a high quality graphs, but, it did the job.


DENSE_RANK on Calculated Column

Question: CASE
          WHEN [col1] = 's' THEN 8
          WHEN [col1] = 't' THEN 6
          WHEN [col1] = 'u' THEN 9
          WHEN [col2] = 'v' THEN 1
.......
END AS product,
DENSE_RANK() OVER (ORDER BY product ASC) AS [Rank]
FROM dbo.TableA

DENSE_RANK() is not working on calculated column Product, showing

Invalid column name 'product'.

How to apply DENSE_RANK() on product?
Comment: Just to be clear: this has nothing to do with `DENSE_RANK()` - you just cannot refer to a newly introduced column alias later on in your `SELECT` statement - you have to use an approach as Mithrandir shows in his response
Answer: You could do something like this:
SELECT
  *,
  DENSE_RANK() over (order by product)
FROM (
SELECT
  CASE
          WHEN [col1] = 's' THEN 8
          WHEN [col1] = 't' THEN 6
          WHEN [col1] = 'u' THEN 9
          WHEN [col2] = 'v' THEN 1
 ...
END AS product
FROM dbo.TableA
) t

DENSE_RANK on Calculated Column


cannot be provided without an @Provides-annotated method Dagger/MissingBinding

Question: Unable to inject presenter to Activity
BookDashboard -> Activity
class BookDashboard : AppCompatActivity(),BookDashboardContract.MvpView{

    @Inject
    lateinit var presenter: BookDashboardContract.Presenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        presenter.fetchedBooks()
        // if I pass no parameter to BookPresenter than UninitializedPropertyAccessException: lateinit property presenter has not been initialized
    }

    override fun displayBooks() {
        Toast.makeText(this,"Books Displayed",Toast.LENGTH_LONG).show()
    }

    override fun showProgress() {}
    override fun hideProgress() {}
}

BookDashboardContract
interface BookDashboardContract {

    interface MvpView{
        fun displayBooks()
        fun showProgress()
        fun hideProgress()
    }

    interface Presenter{
        fun fetchedBooks()
    }
}

BookDashboardPresenter
If I pass no parameter to below constructor app will run but still presenter is not injected
and crashed at presenter.fetchBooks() in BookDashboard -> Activity __ See comments in that code
class BookDashboardPresenter @Inject constructor(val viewContract:BookDashboardContract.MvpView) : BookDashboardContract.Presenter{

    val bookInteractor = BookInteractor(this)

    override fun fetchedBooks() {
        bookInteractor.fetchDataFromServer()
        viewContract.displayBooks()
    }
}

ActivityBuilder
@Module
abstract class ActivityBuilder {

    @ContributesAndroidInjector(modules = {BookDashboardModule.class})
    @ActivityScope
    public abstract BookDashboard bindBookDashboard();
}

BookDashboardModule
@Module
abstract class BookDashboardModule {

    @Binds
    @ActivityScope
    abstract fun presenter(presenter: BookDashboardPresenter): BookDashboardContract.Presenter
}

Second approach I used. But still presenter isn't injected

 @Module
 class BookDashboardModule(val mvpView: BookDashboardContract.MvpView) {

    @Provides
    @ActivityScope
    fun providesCategoryView(): BookDashboardContract.MvpView {
        return this.mvpView
    }

    @Provides
    @ActivityScope
    fun provideBookPresenter(): BookDashboardPresenter {
        return BookDashboardPresenter(mvpView)
    }
}

@Subcomponent.Factory method is missing parameters for required modules or subcomp

@Module(subcomponents = ActivityBuilder_BindBookDashboard.BookDashboardSubcomponent.class)
public abstract class ActivityBuilder_BindBookDashboard {
  private ActivityBuilder_BindBookDashboard() {}

  @Binds
  @IntoMap
  @ClassKey(BookDashboard.class)
  abstract AndroidInjector.Factory<?> bindAndroidInjectorFactory(
      BookDashboardSubcomponent.Factory builder);

  @Subcomponent(modules = BookDashboardModule.class)
  @ActivityScope
  public interface BookDashboardSubcomponent extends AndroidInjector<BookDashboard> {
    @Subcomponent.Factory
    interface Factory extends AndroidInjector.Factory<BookDashboard> {}
  }
}

Edit
As Onik comment I have replace AppCompatActivity with DaggerAppCompatActivity but still unable to inject presenter
MvpView cannot be provided without an @Provides-annotate
/Users/geek/StudioProjects/MyApplication/app/build/tmp/kapt3/stubs/debug/quiz/mania/trivia/mcq/question/di/AppComponent.java:8: error: [Dagger/MissingBinding] quiz.mania.trivia.mcq.question.booksmvp.contract.BookDashboardContract.MvpView cannot be provided without an @Provides-annotated method.
public abstract interface AppComponent extends dagger.android.AndroidInjector<quiz.mania.trivia.mcq.question.App> {
                ^
      quiz.mania.trivia.mcq.question.booksmvp.contract.BookDashboardContract.MvpView is injected at
          quiz.mania.trivia.mcq.question.booksmvp.presenter.BookDashboardPresenter(viewContract)
      quiz.mania.trivia.mcq.question.booksmvp.presenter.BookDashboardPresenter is injected at
          quiz.mania.trivia.mcq.question.di.BookDashboardModule.presenter(presenter)
      quiz.mania.trivia.mcq.question.booksmvp.contract.BookDashboardContract.Presenter is injected at
          quiz.mania.trivia.mcq.question.booksmvp.BookDashboard.presenter
      quiz.mania.trivia.mcq.question.booksmvp.BookDashboard is injected at
          dagger.android.AndroidInjector.inject(T) [quiz.mania.trivia.mcq.question.di.AppComponent → quiz.mania.trivia.mcq.question.di.ActivityBuilder_BindBookDashboard.BookDashboardSubcomponent]

AppComponent
@Component(
    modules = [
        AndroidInjectionModule::class, // why it is necessary to use this class for injecting purpose
        AppModule::class,
        ActivityBuilder::class
    ]
)
@Singleton
interface AppComponent : AndroidInjector<App> {

    @Component.Builder
    interface Builder {

        fun addContext(@BindsInstance context: Context): Builder

        fun build(): AppComponent
    }
}

App.kt
class App : DaggerApplication() {

    override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        return DaggerAppComponent.builder().addContext(this).build()
    }
}

Comment: You must create Dagger component by manually initialising the Dagger module, say in the `Activity`'s `onCreate()`.
Comment: @Onik you are right I changed AppCompatActivity with DaggerAppCompatActivity
Comment: Now new error is BookDashboardContract.MvpView cannot be provided without an @Provides-annotated meth
Comment: In which class does the error occur?
Comment: When I try to run this applicaiton . This error shows  in Build output in class AppComponent.
Comment: @Onik see edit plz
Answer: I think there are some mess with the dependency graph. Please change your code like below and try again:
@Module
 class BookDashboardModule {

    @Provides
    @ActivityScope
    fun provideBookPresenter(view: BookDashboard): BookDashboardContract.Presenter = BookDashboardPresenter(view)
}

////////
@Module
abstract class ActivityBuilder {

    @ContributesAndroidInjector(modules = {BookDashboardModule.class})
    @ActivityScope
    abstract fun bind(): BookDashboard
}

/////////
class BookDashboardPresenter @Inject constructor(val view: BookDashboardContract.MvpView) : BookDashboardContract.Presenter{

    val bookInteractor = BookInteractor(this)

    override fun fetchedBooks() {
        bookInteractor.fetchDataFromServer()
        view.displayBooks()
    }
}

Comment: question/di/BookDashboardModule.java:12: error: @Binds methods' parameter type must be assignable to the return type
    public abstract quiz.mania.trivia.mcq.question.booksmvp.contract.BookDashboardContract.Presenter presenter(@org.jetbrains.annotations.NotNull()
Comment: AppComponent.java:8: error: [ComponentProcessor:MiscError] dagger.internal.codegen.ComponentProcessor was unable to process this interface because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
public abstract interface AppComponent extends dagger.android.AndroidInjector {
Comment: Did you add your ActivityBuilder to AppModule which is added in AppComponent?
Comment: I have added AppComponent and App in my question . See edit section
Comment: Convert your module Binds to Provides. Updated my answer with that check.
Comment: @0xAiHn your solutions works can you tell me why you pass BookDashboard instead of MvpView interface and what's the purpose of annotation ActivityScope
Comment: @XarEAhmer Because we are binding the BookDashboard through ActivityBuilder also ActivityScope is your stuffs i just make the dependency graph workable nothing with activityscope. However, if the solution works do upvote so that others can be helpful from this kind of issue as well.


Run LoadIncrementalHFiles from Java client

Question: I want to call hbase org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles /user/myuser/map_data/hfiles mytable method from my Java client code.
When I run the application I get the following exception:
org.apache.hadoop.hbase.io.hfile.CorruptHFileException: Problem reading HFile Trailer from file webhdfs://myserver.de:50070/user/myuser/map_data/hfiles/b/b22db8e263b74a7dbd8e36f9ccf16508
    at org.apache.hadoop.hbase.io.hfile.HFile.pickReaderVersion(HFile.java:477)
    at org.apache.hadoop.hbase.io.hfile.HFile.createReader(HFile.java:520)
    at org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles.groupOrSplit(LoadIncrementalHFiles.java:632)
    at org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles$3.call(LoadIncrementalHFiles.java:549)
    at org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles$3.call(LoadIncrementalHFiles.java:546)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.RuntimeException: native snappy library not available: this version of libhadoop was built without snappy support.
    at org.apache.hadoop.io.compress.SnappyCodec.checkNativeCodeLoaded(SnappyCodec.java:65)
    at org.apache.hadoop.io.compress.SnappyCodec.getDecompressorType(SnappyCodec.java:193)
    at org.apache.hadoop.io.compress.CodecPool.getDecompressor(CodecPool.java:178)
    at org.apache.hadoop.hbase.io.compress.Compression$Algorithm.getDecompressor(Compression.java:327)
    at org.apache.hadoop.hbase.io.compress.Compression.decompress(Compression.java:422)
    at org.apache.hadoop.hbase.io.encoding.HFileBlockDefaultDecodingContext.prepareDecoding(HFileBlockDefaultDecodingContext.java:90)
    at org.apache.hadoop.hbase.io.hfile.HFileBlock.unpack(HFileBlock.java:529)
    at org.apache.hadoop.hbase.io.hfile.HFileBlock$AbstractFSReader$1.nextBlock(HFileBlock.java:1350)
    at org.apache.hadoop.hbase.io.hfile.HFileBlock$AbstractFSReader$1.nextBlockWithBlockType(HFileBlock.java:1356)
    at org.apache.hadoop.hbase.io.hfile.HFileReaderV2.<init>(HFileReaderV2.java:149)
    at org.apache.hadoop.hbase.io.hfile.HFileReaderV3.<init>(HFileReaderV3.java:77)
    at org.apache.hadoop.hbase.io.hfile.HFile.pickReaderVersion(HFile.java:467)
    ... 8 more

Running the hbase ... command above from console on my Hadoop server works perfectly. But when I try to run these from my Java Code using HBase /Hadoop client libraries it fails with the exception!
Here a code snippet:
public static void main(String[] args) {

    try {
        Configuration conf = loginFromKeyTab("REALM.DE", "server.de", "user", "C:/user.keytab");
        conf.set("fs.webhdfs.impl", org.apache.hadoop.hdfs.web.WebHdfsFileSystem.class.getName());
        conf.set("hbase.zookeeper.quorum", "server1.de,server2.de,server3.de");
        conf.set("zookeeper.znode.parent", "/hbase-secure");
        conf.set("hbase.master.kerberos.principal", "email@example.com");
        conf.set("hbase.regionserver.kerberos.principal", "email@example.com");
        conf.set("hbase.security.authentication", "kerberos");

        Connection connection = ConnectionFactory.createConnection(conf);
        Table table = connection.getTable(TableName.valueOf("mytable"));

        RegionLocator locator = connection.getRegionLocator(table.getName());

        Job job = Job.getInstance(conf, "Test Bulk Load");

        //HFileOutputFormat2.configureIncrementalLoad(job, table, locator);
        //Configuration conf2 = job.getConfiguration();

        LoadIncrementalHFiles loader = new LoadIncrementalHFiles(conf);
        loader.doBulkLoad(new Path(HDFS_PATH), connection.getAdmin(), table, locator);
    } catch(Exception e) {
        e.printStackTrace();
    }
}

Do I need to add a dependency to my project? But how / where / which version?
I'm working with HDP 2.5 which contains HBase 1.1.2 and Hadoop 2.7.3
Answer: I found another solution for my issue: I'm using a Java program that runs a Process instance that calls the LoadIncrementalHFiles method automatically (running directly on the Hadoop node), instead of using the LoadIncrementalHFiles class itself in my code!
Here the code snippet of my solution:
TreeSet<String> subDirs = getHFileDirectories(new Path(HDFS_OUTPUT_PATH), conf);        // The HDFS_OUTPUT_PATH directory contains many HFile sub-directories

for(String hFileDir : subDirs) {
    String pathToReadFrom = HDFS_OUTPUT_PATH + "/" + hFileDir;

    String[] execCode = {"hbase", "org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles", "-Dcreate.table=no", pathToReadFrom, "mytable"};       // Important: Separate each parameter here!!!
    ProcessBuilder pb = new ProcessBuilder(execCode);
    pb.redirectErrorStream(true);
    final Process p = pb.start();

    new Thread(new Runnable() {
        public void run() {
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;

            try {
                while ((line = input.readLine()) != null)
                    System.out.println(line);
            } catch (IOException e) {
                    e.printStackTrace();
             }
        }
    }).start();

    p.waitFor();

    int exitCode = p.exitValue();
    System.out.println(" ==> Exit Code: " + exitCode);
}

System.out.println("Finished");

If somebody has another solution (e.g. how to use the LoadIncrementalHFiles class directly in code), let me know. Thank you!


How to play an accompaniment with a midi keyboard on Linux?

Question: I recently bought a 88 keys midi master keyboard. It doesn't play any sound by itself and you have to plug it to a computer and use a software synthetizer to produce sounds.
I was wondering if I could play chords and have a software generate some accompaniment sounds (like on little keyboards such as the one below).
Basicaly, I'd like to have a nice music style (let's say a "march" or "dance" style) play when I hit chords like Am / C / Dm, etc.
A split function to play a melody would be nice too.
Do you know any software on linux that could achieve this? (Or on any other OS if it doesn't exist on Linux).
)
Comment: [MMA](http://linuxband.org/) does not work in real time. Try [gmorgan](http://gmorgan.sourceforge.net/).
Answer: A 20 year old hardware Midi expander/arranger (Ketron MS40 is what I use, but there is a lot of different ones around) will be so much less painful than what you can make Linux software do that it isn't funny.
Hydrogen is a reasonably workable drum arranger/sequencer readily available on Linux.  It works directly via PCM so you avoid the lousy sample quality and latency problems of Timidity and other software Midi expanders.
Of course, that does not give you chord accompaniment.  If you really must, be sure to read the Linux Midi HOWTO thoroughly, in particular regarding latency problems.  Those are the worst funkillers when using software expanders.
Whether or not you settle on a hardware arranger/sequencer: for Midi->PCM expansion specifically the software solutions are not worth the effort you might put into them when the Midi is actually coming from a live keyboard.


Add some custom fields in Views exposed filters and preserve their data to Url (GET)

Question: I have a Views list of Boats and every Content Type 'boat' has a location. So I have created an exposed form that already contains a location <select>, and when changed, the boats are successfully filtered by the location selected.
I want to put other inputs in this form, like:

Check in Date
Check out Date
Number of visitors

But these data are not filters, they are just input that can be used in the next step (explained later).

Is there a simple way to add these custom fields in the exposed filter form (or look like being inside it somehow)?
How to retrieve this information, so when a specific boat is selected (that's the next step) the number of visitors,check in/out dates, etc will be shown in a similar form (Webform) which finally sends a mail..

Thanks in advance!
PS: I am a newbie on both Drupal and Drupal Answers!
I've searched but I am confused whether I should create a custom module or use an existing one that I currently am unaware of.
Answer: I think I found it! I got to the the Views' theme folder and did what exactly I show here!
Then the data-passing through different pages needs some script and is done!


do i need to check expiration cache in drupal from cache_get?

Question: I'm using drupal 6 and I've build table that is similar to cache (hook_schema) for using it with function cache_get/cache_set.
I just want to be sure how things should work in drupal.

To clean the table I'll need to use hook hook_flush_caches() where I'll decide if i want to clear expire data or whole cache? hook_flush_caches is called on cron?
In case I'll need to check data expiration by second, I'll need to do manually after cache_get function ?

This is kinda confusing...
Answer: It is actually pretty simple.
For your implementation of hook_flush_caches, all you need to do is return an array containing the names of your cache tables, eg
function mymodule_flush_caches ()
{
  return array("cache_mymodule");
}

drupal_flush_all_caches and cache_clear_all take care of the rest.  drupal_flush_all_caches is called anytime you manually clear the cache (the perforamnce page, admin menu, drush, etc).  system_cron does get called by cron, and also clears the cache tables, but does not do some of the other things that drupal_flush_all_caches does.
When you get something out of the cache with cache_get, expired items will have already been removed from the cache; you don't need to manually check expirations.  They will be handled automatically according to how you put them in the cache with cache_set.
That's it.
Comment: I missed "hook_flush_caches" :(
Thanks!


$\lim_{x\rightarrow\pm\infty} \frac{2x}{2x-\sqrt{4x^2-2x}}$

Question: $$\lim_{x\rightarrow\pm\infty} \frac{2x}{2x-\sqrt{4x^2-2x}}$$
What I did
I multiplied by the denominator's conjugate and got the following $$2x+\sqrt{4x^2-2x}$$
My question is,  what would I now do to evaluate the limit? The positive infinity I would do as follows:
$$\lim_{x\rightarrow\infty}2x+\sqrt{4x^2-2x} = 2\cdot\infty + \sqrt{4\cdot(\infty)^2 - 2\cdot\infty} = \infty???$$
Comment: but why this error occures there other questions in limits where i find errors while calculating
Answer: When $x \to +\infty$
$$2x+\sqrt{4x^2-2x} = 2x\left(1 +\sqrt{1- \dfrac{1}{2x}}\right) \sim 4x\to +\infty$$
When $x \to -\infty$
$$2x+\sqrt{4x^2-2x} = 2x\left(1 -\sqrt{1- \dfrac{1}{2x}}\right) = \dfrac{1}{1 +\sqrt{1- \dfrac{1}{2x}}} \to \dfrac{1}{2}$$
Comment: Why does the sign change inside the paranthesis when you factored the $2x$? Nvm, I see why. Thank you !


CUDA memory bandwidth when reading a limited number of finite-sized chunks?

Question: Knowing hardware limits is useful for understanding if your code is performing optimally. The global device memory bandwidth limits how many bytes you can read per second, and you can approach this limit if the chunks you are reading are large enough.
But suppose you are reading, in parallel, N chunks of D bytes each, scattered in random locations in global device memory. Is there a useful formula limiting how much of the bandwidth you'd be able to achieve then?
Comment: "nd you can approach this limit if the chunks you are reading are large enough" <- Well, not quite. You typically only approach some large fraction of NVIDIA's published maximum bandwidth.
Answer: let's assume:

we are talking about accesses from device code
a chunk of D bytes means D contiguous bytes
when reading a chunk, the read operation is fully coalesced - those bytes are read 4 bytes per thread, by however many adjacent threads in the block are predicted by D/4.
the temporal and spatial characteristics are such that no two chunks are within 32 bytes of each other - either they are all gapped by that much, or else the distribution of loads in time is such that the L2 doesn't provide any benefit.  Pretty much saying the L2 hitrate is zero.  This seems evident in your statement "global device memory bandwidth" - if the L2 hitrate is not zero, you're not measuring (purely) global device memory bandwidth
we are talking about a relatively recent GPU architecture, say Pascal or newer, or else for an older architecture the L1 is disabled for global loads.  Pretty much saying the L1 hitrate is zero.
the overall footprint is not so large as to thrash the TLB
the starting address of each chunk is aligned to a 32-byte boundary (&)
your GPU is sufficiently saturated with warps and blocks to make full use of all resources (e.g. all SMs, all SM partitions, etc.)
the actual chunk access pattern (distribution of addresses) does not result in partition camping or some other hard-to-predict effect

In that case, you can simply round the chunk size D up to the next multiple of 32, and do a calculation based on that.  What does that mean?
The predicted bandwidth (B) is:
Bd = the device memory bandwidth of your GPU as indicated by deviceQuery
B = Bd/(((D+31)/32)*32)

And the resultant units there is chunks/sec.  (bytes/sec divided by bytes/chunk).  The second division operation shown is "integer division", i.e. dropping any fractional part.
(&) In the case where we don't want this assumption, the worst case is to add an additional 32-byte segment per chunk.  The formula then becomes:
B = Bd/((((D+31)/32)+1)*32)

note that this condition cannot apply when the chunk size is less than 34 bytes.
All I am really doing here is calculating the number of 32-byte DRAM transactions that would be generated by a stream of such requests, and using that to "derate" the observed peak (100% coalesced/100% utilized) case.
Comment: Why not just invert the formula? Also, suggest giving the "bandwidth as indicated" a symbol, so as not to overflow the line.
Comment: Thanks! I'd like to *not* assume that the task itself is large enough (huge `N`) though. Since we are just looking for an upper bound on the bandwidth, I think we can get rid of this assumption, but the question is: Can we *tighten* your limit by, say, dividing it by `min(1, float(N)/number_of_SMs)` ? (or with some other appropriate constant)
Comment: Sorry, I don't know how to apportion bandwidth to individual SMs or consider the case where we are not saturating the GPU with such requests. I think the logic of a per-chunk rounding up is sound, however, even if you consider an individual chunk (given the other assumptions that are not in dispute.)
Comment: Your formula has the effective bandwidth drop the faster the indicated memory bandwidth increases. That's not right.
Comment: OK, I've made those changes.
Answer: Under @RobertCrovella's assumptions, and assuming the chunk sizes are multiples of 32 bytes and chunks are 32-byte aligned, you will get the same bandwidth as for a single chunk - as Robert's formula tells you. So, no benefit and no detriment.
But ensuring these assumptions hold is often not trivial (even merely ensuring coalesced memory reads).


Where to write public, common, utility functions in Drupal?

Question: At times you have to write little utility functions which will have a general scope (not restricted to the module you are working on) so that it can be called from anywhere in the project.
I know I can write it anywhere and include the php file from the caller, but is there a convention followed in Drupal?
For e.g. I am working on xyz.module which does xyz thing which will have a silly
function startsWith($haystack, $needle) // case-insensitive startsWith
{
    return strncasecmp($haystack, $needle, strlen($needle)) === 0;
}

Where shall I write that function?
Answer: As many API modules do, you can place your global helper functions within a dedicated module. (I'll be using MYHELPERMODULE in the following example.)
You then should follow the naming conventions:
function MYHELPERMODULE_startswith($needle, $haystack) {
  // do your magic
}

You can call this function from within all other modules, as long as your helper module is active. To assure it's active, add your helper module as dependency to the .info file of the module that is using the helper function:
dependencies[] = MYHELPERMODULE

Comment: I consider any module function that isn't a hook implementation and that does not begin with an underscore (_), a potential helper module.
Comment: @cilefen so all modules with hook functions should better start with an `_`?
Comment: He is speaking of function names only. Mentioning, that function names starting with an underscore are considered private for the containing module. Hooks are a completely different topic.


Erro ao executar update com subconsulta

Question: Tenho a seguinte situação, preciso efetuar um update em diversos campos com base no retorno de uma subconsulta que retorna um código principal. Essa subconsulta está é feita com join em duas tabelas para obtenção do código.
Ao efeturar, tenho o seguinte erro:
Mensagem 512, Nível 16, Estado 1, Linha 24
A subconsulta retornou mais de 1 valor. Isso não é permitido quando a subconsulta segue um =, !=, <, <= , >, >= ou quando ela é usada como uma expressão.
Essa é a consulta:
BEGIN TRANSACTION;
UPDATE Produto SET TpProduto = 'C' WHERE IdProduto = (
SELECT DISTINCT(p.IdProduto)
FROM dbo.Produto p
JOIN dbo.CodigoProduto  cp ON cp.IdProduto = p.IdProduto
WHERE cp.CdChamada IN(
'3VT9200-4ED30                 ',
'3VT9225-6AC00                 ',
'5SX11207                      ',
'6ES73921AJ000AA0              ',
'8910427                       ',
'9676812                       ',
'CON000280                     '

 )

)

Answer: esse select retornar mais de um valor
SELECT DISTINCT(p.IdProduto)

como comparar
WHERE IdProduto = (vários valores)

esse pedaço aqui precisa retornar apenas um valor
SELECT DISTINCT(p.IdProduto)
FROM dbo.Produto p
JOIN dbo.CodigoProduto  cp ON cp.IdProduto = p.IdProduto
WHERE cp.CdChamada IN(
'3VT9200-4ED30                 ',
'3VT9225-6AC00                 ',
'5SX11207                      ',
'6ES73921AJ000AA0              ',
'8910427                       ',
'9676812                       ',
'CON000280                     '

 )

verifica se não é isso.
Comment: Já resolvi, basta mudar a instrução de = para in na primeira consulta.
Comment: É isso mesmo, preciso comparar vários retornos, os que estão na subconsulta e atualizar os mesmos. Esse banco que estou mexendo é confuso, ele gera o código em tabelas diferentes e como são muitos dados pensei em pegar o retorno da subconsulta e ir atualizando.
Comment: marca como respondido, para ajudar outras pessoas.

Erro ao executar update com subconsulta


Controlling for variables in social sciences

Question: I know this is a completely hypothetical scenario but I just want to understand how the effect of a variable could be held constant and how the coefficients of two independent variables are estimated in a multitple regression.
Let us think about this hypothetical story.
Let us assume that there are two types of oils that increase hair length; olive and castor oil. Let's also assume that the two have totally different components and substances and function through totally different mechanisms, which means that they are not related at all, i. e there is no similar mechanism or substance in both that affect hair length. They are both totally unique and have a unique effect on the body, which increases hair length.
Let's assume that a scientist  bought a mixture of both oils and observed hair growth. So he wanted to test how they affect hair growth.  He did an experiment. When he used the mixture of both oils together
 he found out that for each 2 milligrams of the mixture (consisting of 1mg of each oil) , his hair grew by 1 cm.
 (Let's also for simplicity assume that there are no other factors affecting hair growth. Only the oils).
He runs two simple linear regressions each with only 1 type of oil alone and the results of the regressions show him that for each milligram of oje type of oil; hair length increases by 1cm. However, he did not trust the results as he knows that this 1 cm increase is a result of both oils and not one. Therefore, he decided to do two seperate experiments to estimate the effect of each one alone and therefore keeping the other one constant.
When he used castor oil alone, he found that  for each additional milligram; hair length increases by 0. 5 cm. He did the same experiment later using olive oil and also found the same effect, namely that an additional milligram of olive oil increases hair length by 0.5 cm. Thus the estimated effect of each one alone holding the other constant is 0.5. Now he knows that the 1 cm increase he witnessed before was partially because of olive and partially because of castor
and was now successful to estimate each one's unique effect on hair length by running two different experiments.
The problem is trying to find the unique effect if it was a social science phenomenon.
Let's assume these two oils are two oils that let the economy grow and not the hair anymore. Instead of castor oil and olive oil; they are human and physical capital (assuming that we know for sure that they increase the GDP which used to be the hair length in our model).
Now the problem is that in a social science, we cannot manipulate an experiment like the natural scientist doing with both oils. An economic researcher cannot only increase human capital alone and see its effect on growth and do the same for physical capital while holding human  capital constant. Instead, he deals with the data available and tries to control for variables. Therefore if he is in the natural scientist situation with exactly the same data but for the economic variables mentioned;he cannot do two seperate experiments. Instead, he only has the mixture of both increasing together exactly by the same amount. I know it sounds illogical to think that both independent variables are increasing together by the same amount but take the example of the oil mixture. Each time he adds it, it includes both oils, so they increase together.
Since the social scientist can't seperate the oils and run two different experiments, he has to include both in a model to be able to hold one constant (as a control variable) and therefore see the effect of castor  if oilve oil is held constant and see the effect of oilve oil if castor is held constant although in reality they were added together.
Some softwares when running a multitple regression with both variables estimate the coefficient of one of the oils to be 1 and the other 0, while other softwares don't run the regression as it is a case of perfect multicollinearity as olive and castor oil increase together exactly by the same amount.
The solution I know is dropping one of the variables, but the problem is that although they are mathematically correlated, in reality, each of them has a unique effect of 0.5 and if I drop one of them, then the effect of the other  will be 1 although it is only 0.5.
So, is there anyway to solve this? How can social scientists estimate the effect of different variables on an dependent variable while holding other variables constant? especially when there is a high multicollinearity but just due to chance and not causation.
It seems to me that in social sciences, we are following numbers and techniques that cannot estimate the truth.
I know I made many assumptions and it is too hypothetical. I know that in reality the effect could change when both are used together, but let's just assume this scenario for simplicty.
I would appreciate an answer that explains the concept of how to deal with this problem without going into too much math and algebra, which in this scenario failed to capture the true effects of both oils.
Comment: @cure. Thank you so much. Will look into it
Answer: Mostly through a thing called natural experiment. Social scientists look for the situations in nature, that are not an experiment, but with use of (whole arsenal of) econometric tools, they may isolate the effect of one variable as it was an experiment.
Most popular methods are:

Instrumental variable.
Regression discontinuity design (also spatial version).
Matching methods (PSM and more).
Using changes in time (panel and DD methods).

A good thing to start would be Mostly Harmless Econometrics: An Empiricist's Companion. While most of this book is mathematics, i would suggest reading introductory parts to the chapters (pages 83-84 especially).