text:
Q: Predict Logistf I'm using a R package called logistf to make a Logistc Regression and I saw that there's no predict function for new data in this package and predict package does not work with this, so I found a code that show how making this with new data:
fit<-logistf(Tax ~ L20+L24+L28+L29+L31+L32+L33+L36+S10+S15+S16+S17+S20, data=trainData)
betas <- coef(fit)
X <- model.matrix(fit, data=testData)
probs <- 1 / (1 + exp(-X %*% betas))

I want to make a cross validation version with this using fit$predict and the probabilities that probs generate for me. Has anyone ever done something like this before?
Other thing that I want to know is about fit$predict I'm making a binary logistic regression, and this function returns many values, are these values from class 0 or 1, how can I know this? Thanks

A: While the code that you wrote works perfectly, there is a concise way of getting the same results seemingly:
    brglm_model <- brglm(formula = response ~ predictor , family = "binomial", data = train )
brglm_pred <- predict(object = brglm_model, newdata = test , type = "response")

About the CV, you have to write a few lines of code I guess:
#Setting the number of folds, and number of instances in each fold
n_folds <- 5
fold_size <- nrow(dataset) %/% 5
residual <- nrow(dataset) %% 5

#label the instances based on the number of folds
cv_labels <- c(rep(1,fold_size),rep(2,fold_size), rep(3,fold_size), rep(4,fold_size), rep(5,fold_size), rep(5,residual))

# the error term would differ based on each threshold value
t_seq <- seq(0.1,0.9,by = 0.1)
index_mat <- matrix(ncol = (n_folds+1) , nrow = length(t_seq))
index_mat[,1] <- t_seq

# the main loop for calculation of the CV error on each fold
for (i in 1:5){
        train <- dataset %>% filter(cv_labels != i)
        test <- dataset %>% filter(cv_labels == i )

        brglm_cv_model <- brglm(formula = response_var ~ . , family = "binomial", data = train )
        brglm_cv_pred <- predict(object = brglm_model, newdata = test , type = "response")

        # error formula that you want, e.g. misclassification
        counter <- 0

        for (treshold in t_seq ) {
               counter <- counter + 1
               conf_mat <- table( factor(test$response_var) , factor(brglm_cv_pred>treshold, levels = c("FALSE","TRUE") ))

               sen <- conf_mat[2,2]/sum(conf_mat[2,])

               # other indices can be computed as follows
               #spec <- conf_mat[1,1]/sum(conf_mat[1,])
               #prec <- conf_mat[2,2]/sum(conf_mat[,2])
               #F1 <- (2*prec * sen)/(prec+sen)
               #accuracy <- (conf_mat[1,1]+conf_mat[2,2])/sum(conf_mat)

               #here I am only interested in sensitivity
               index_mat[counter,(i+1)] <- sen

        }

}

# final data.frame would be the mean of sensitivity over each threshold value
final_mat <- matrix(nrow = length(t_seq), ncol = 2 )
final_mat[,1] <- t_seq
final_mat[,2] <- apply(X = index_mat[,-1] , MARGIN = 1 , FUN = mean)
final_mat <- data.frame(final_mat)
colnames(final_mat) <- c("treshold","sensitivity")

#why not having a look at the CV-sensitivity of the model over threshold values?
ggplot(data = final_mat) +
        geom_line(aes(x = treshold, y = sensitivity ), color = "blue")


text:
Q: Error: failed due to the following error: 80040154 when i call Req() class I use OTAClient.dll from HP for conencting with Quality Center.
My connection is correct:
TDConnection tdCon = new TDConnection();
tdCon.InitConnectionEx("http://....");
tdCon.Login("username", "userpass");
tdCon.Connect("****", "********");

But in this area i get error:
Req newReq = new Req();

I set platform target in x86 but didn't help me

A: Instead of COM object use the rest library. You could send xml documents with parameters for creating and updating requirements(Req) in QC. You can find documentation in QC.
You will use "post" method by HttpWebRequest for creating and updating, "get" method for getting session parameters.
In the rest library look to creating entity description. For maintaining connections you must save QCSessionId. Look to authentication description.
Good luck!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring Boot and Hibernate: for org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor I'm setting up a Spring Boot/Hibernate project for simple CRUD operation. For that I took help from several online tutorials and written the following code. But seems there is some version mismatch or similar dependencies in my POM.xml which I am unable to understand.
I getting a MAVEN build failure each time.
pom.xml dependecies:
<dependencies>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-hibernate3</artifactId>
    <version>2.0.8</version>
  </dependency>

  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-annotations</artifactId>
    <version>3.5.6-Final</version>
  </dependency>

  <dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
  </dependency>

  <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.1</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.22</version>
  </dependency>

  <dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.1</version>
  </dependency>

  <dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>2.2</version>
  </dependency>

  <dependency>
    <groupId>javax.transaction</groupId>
    <artifactId>jta</artifactId>
    <version>1.1</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
  </dependency>
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
  </dependency>
</dependencies>

<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
  </plugins>
</build>

</project>

HibernateConfigApplication.java
@SpringBootApplication
public class HibernateConfigApplication {

  @Autowired
  public static void main(String[] args) {
    //SpringApplication.run(HibernateConfigApplication.class, args);
    Connection conn = null;
    SessionFactory sessionfactory = HibernateUtil.getSessionFactory();
    if (sessionfactory != null) {
      System.out.println("Session Established");
      try {
        Object obj = Class.forName("oracle.driver.jdbc.OracleDriver");
        System.out.println("*************");
        System.out.println("obj" + obj);
      } catch (ClassNotFoundException e) {
        System.out.println("Where is your oracle JDBC driver");
        e.printStackTrace();
        return;
      }

      System.out.println("Oracle JDBC Driver Registered");
      Session session = null;

      try {
        session = sessionfactory.openSession();
      } catch (Throwable t) {
        System.out.println("Exception while getting session");
        t.printStackTrace();
      }

      if (session == null) {
        System.out.println("session Registered is null");
      }

      SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session.getSessionFactory();
      ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider();

      try {
        Connection connection = connectionProvider.getConnection();
        if (connection != null) {
          System.out.println("*********************");
          System.out.println("Connection Established");
          System.out.println("*********************");
        }

      } catch (SQLException e) {
        e.printStackTrace();
      }

      session.close();
    }
  }
}

The specific error are as follows:
I am unable to understand how to correct the classpath of the application so that it contains a single, compatible version
***************************
APPLICATION FAILED TO START
***************************

Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration.persistenceExceptionTranslationPostProcessor(PersistenceExceptionTranslationAutoConfiguration.java:49)

The following method did not exist:

    org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setProxyTargetClass(Z)V

The method's class, org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor, is available from the following locations:

    jar:file:/C:/Users/Admin/.m2/repository/org/springframework/spring-dao/2.0.8/spring-dao-2.0.8.jar!/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessor.class
    jar:file:/C:/Users/Admin/.m2/repository/org/springframework/spring-tx/5.1.8.RELEASE/spring-tx-5.1.8.RELEASE.jar!/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessor.class

It was loaded from the following location:

    file:/C:/Users/Admin/.m2/repository/org/springframework/spring-dao/2.0.8/spring-dao-2.0.8.jar

Action:

Correct the classpath of your application so that it contains a single, compatible version of org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor

2019-07-04 08:13:22.267 ERROR 6976 --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@55141def] to prepare test instance [com.example.hibernateConfig.HibernateConfigApplicationTests@5b56b654]

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125) ~[spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108) ~[spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) ~[spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) ~[spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) ~[spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) [surefire-junit4-2.22.2.jar:2.22.2]
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:273) [surefire-junit4-2.22.2.jar:2.22.2]
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) [surefire-junit4-2.22.2.jar:2.22.2]
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:159) [surefire-junit4-2.22.2.jar:2.22.2]
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384) [surefire-booter-2.22.2.jar:2.22.2]
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345) [surefire-booter-2.22.2.jar:2.22.2]
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126) [surefire-booter-2.22.2.jar:2.22.2]
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418) [surefire-booter-2.22.2.jar:2.22.2]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceExceptionTranslationPostProcessor' defined in class path resource [org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor]: Factory method 'persistenceExceptionTranslationPostProcessor' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setProxyTargetClass(Z)V
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:607) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:228) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:721) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:534) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742) ~[spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389) ~[spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:311) ~[spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:119) ~[spring-boot-test-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) ~[spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117) ~[spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    ... 27 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor]: Factory method 'persistenceExceptionTranslationPostProcessor' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setProxyTargetClass(Z)V
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    ... 45 common frames omitted
Caused by: java.lang.NoSuchMethodError: org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setProxyTargetClass(Z)V
    at org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration.persistenceExceptionTranslationPostProcessor(PersistenceExceptionTranslationAutoConfiguration.java:49) ~[spring-boot-autoconfigure-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    ... 46 common frames omitted

[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 17.466 s <<< FAILURE! - in com.example.hibernateConfig.HibernateConfigApplicationTests
[ERROR] contextLoads(com.example.hibernateConfig.HibernateConfigApplicationTests)  Time elapsed: 0.002 s  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceExceptionTranslationPostProcessor' defined in class path resource [org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor]: Factory method 'persistenceExceptionTranslationPostProcessor' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setProxyTargetClass(Z)V
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor]: Factory method 'persistenceExceptionTranslationPostProcessor' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setProxyTargetClass(Z)V
Caused by: java.lang.NoSuchMethodError: org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setProxyTargetClass(Z)V

[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR]   HibernateConfigApplicationTests.contextLoads » IllegalState Failed to load App...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 25.714 s
[INFO] Finished at: 2019-07-04T08:13:23+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project HibernateConfig: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\Admin\Desktop\Projects\HibernateConfig\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

A: *

*First of all create Spring boot application via https://start.spring.io/.

*Chose Dependencies WEB,JPA,Actuator,Devtools

*Then use EntityManager


text:
Q: Overriding vim keyword syntax in after/syntax file So I am working in a javascript project. And I have some code like this:

I am using the vim-javascript plugin and it has these lines on syntax/javascript.vim:
syntax keyword jsOperator delete instanceof typeof void new in of
syntax match   jsOperator /[\!\|\&\+\-\<\>\=\%\/\*\~\^]\{1}/

But I would like to add different syntax to these files in my after/syntax file, something like jsNew to new keyword so I could highlight it with different color. I am trying commands like this:
syntax keyword jsNew new containedin='jsOperator'

But it is not working. What would be the correct way to highlight the new keyword with no change to the syntax file that comes with the vim-javascript plugin?

A: I had success with these commands in my ../after/syntax/javascript.vim:
syntax keyword jsNew new
syntax cluster jsExpression add=jsNew
hi def link jsNew Special

now the 'new' keyword is highlighted with the color for the highlight group: Special.


text:
Q: How are new Stack Overflow ques always at the top of a google search I noticed an interesting thing today. I had posted a ques on the main stack Overflow website . This post  garnered 14 views and 0 votes. Definetely not  a popular PGE.
Yet as I searched related keywords to my ques on google the stack overflow website with my ques was ranked first amoung the rest.
How is Stack.Overflow doing this ?


text:
Q: EmptyDataText and EmptyDataTemplate in asp.net I have this code on a gridview
   <asp:GridView ID="ReconcileGridView" runat="server" EmptyDataText="Please Select Transaction Month And Date" AutoGenerateSelectButton="True"
                BackColor="White" BorderColor="#4A3C8C" BorderWidth="3px" GridLines="Both" BorderStyle="Solid"
                CellPadding="3" AllowPaging="True" OnPageIndexChanging="ReconcileGridView_PageIndexChanging"
                OnRowDataBound="ReconcileGridView_RowDataBound"  OnSelectedIndexChanged="ReconcileGridView_SelectedIndexChanged">
                <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
                <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
                <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
                <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
                <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
                <AlternatingRowStyle BackColor="#F7F7F7" />
                  <EmptyDataTemplate>
                    <center>
                        No Record Found
                    </center>
                </EmptyDataTemplate>

            </asp:GridView>

The Problem is on page Load i want the word Please Select Transaction Month And Date to appear and when a user inputs the a transaction month and date and no data was retrieved
No Record Found should show, how would i do that? on the code above only the word No Record Found shows, i Databind Empty Data on page load to make those messages appear.
please help on making that happen.

A: You have to place a separate Label control for word Please Select Transaction Month And Date
and on page load, you have to set the label control visible property true
and when user inputs the month and date then you can set the lable control property false.
make sense?

A: You have to place a separate Label control for "Please Select Transaction Month And Date" and on page load, you have to set the label control visible property true and when user inputs the month and date then you can set the label control property false.
Make sure not to bind your Gridview in the page load.
If you are placing the Gridview in an update panel and binding to null to clear it, then the EmptyDataTemplate will be shown. You most likely want to label to shown and not the EmptyDataTemplate. So you will need to hide the entire GridView (if not displaying headers) or you will need to add a cssClass to hide the EmptyDataTemplate at the appropriate points in the codebehind (alternatively use javascript).


text:
Q: In Bayesian Statistic how do you usually find out what is the distribution of the unknown? To estimate the posterior we have
$$p(\theta|x) = \frac{p(\theta)*p(x|\theta)}{\sum p(\theta ')*p(x|\theta ')}$$
$x$ is usually the experimentally sampled data, and $\theta$ is the model, but both $p(x|\theta)$ and $p(\theta)$ is unknown, how do you usually measure those two quantities?

A: These quantities are known as part of the model.
$p(\theta)$ is the prior, which you chose (a classic example is the Beta distribution), and $p(x|\theta)$ is the density function of $X|\theta$, for example the model is such that $X|\theta\sim\mathcal{N}(\theta,1)$.

A: The prior distribution is based on previous experience, data, intuition, whatever. If none of these are available, then a flat or non-informative prior is given.
Presumably, you know the distributional form of $p(x|\theta)$ based on your experiment.
If possible, it is desirable to pick a prior distribution $p(\theta)$ that is
"conjugate" to the likelihood (data) distribution $p(x|\theta)$.
That is, "mathematically compatible". In that case one can deduce
the posterior distribution $p(\theta|x)$ without having to compute the denominator.
Simple example:  Trying to predict the outcome of an election, a
campaign strategist chooses the prior distribution $Beta(\alpha_0 = 330, \beta_0 = 270)$ on the probability $\theta$ that the candidate
is going to win. This is based on a 'hunch' that $\theta$ is 'near'
0.55 and is most likely to lie somewhere in $(0.51, 0.59)$. [You can check that this beta distribution has about the right properties.]
A subsequent reliable poll shows $x = 620$ in $n = 1000$ favoring
the candidate. This gives a binomial likelihood. Ignoring the
constants that make the beta and binomial distributions sum to 1,
we have
$$p(\theta|x) \propto p(\theta)p(x|\theta)
\propto \theta^{\alpha_0 -1} (1-\theta)^{\beta_0 -1} \times
\theta^x (1-\theta)^{n-x}\\ =
\theta^{a_0 + x - 1}(1-\theta)^{\beta_0 - n - x -1}
= \theta^{\alpha_n -1}(1-\theta)^{\beta_n - 1},$$
where we recognize the posterior is proportional to ($\propto)$
the density of the distribution $Beta(\alpha_n, \beta_n),$
with $\alpha_n = 950$ and $\beta_n = 650.$
Then one can cut 2.5% of the area from each tail of the posterior
distribution to find the posterior probability interval $(0.57,0.62).$ This is different from the frequentist 95% CI
one would have obtained from the data alone. One can say that
the Bayesian approach has accomplished an appropriate melding
of prior opinion and data to produce a probability interval
estimate for $\theta.$
In practice, one would typically try several different prior
distributions in order to assess the influence of each on the
result. (Very roughly speaking, our strategist's prior distribution carries
about the same weight as a poll of 600 people with 330 in
favor of our candidate.)
If the consultant is from Mars and has no knowledge of human
elections, then the non-informative prior distribution might
have been something like $Beta(1,1)$ or $Beta(.5,.5)$ and
the endpoints of the posterior probability interval would closely approximate the endpoints of the frequentist CI based on the data
alone. (The philosophical interpretations of the Bayesian and
frequenist intervals are rather different, but that is for another
discussion.)
Another Answer suggests the prior might be beta and the likelihood normal.
Computationally speaking, that would be a bit messier because
beta and normal are not conjugate distributions and we would need
to compute the denominator of Bayes' theorem. Beta is conjugate to
binomial; normal is conjugate to normal (but not quite obviously so).
It is worth noting that graphs of densities of $Norm(\mu=.55,\sigma=.02)$ and $Beta(330, 270)$ are difficult
to distinguish [except, or course, the normal is not constrained
to $(0,1).$]
Acknowledgment: This example is similar to one in Chapter 8 of
Suess and Trumbo (2010), Springer.


text:
Q: How to group by multiple columns with complex types in Linq I'm trying to preform a group by to get all of the students, by college, grouped by status. The problem is the database I'm working with has hundreds of fields in the StudentInfo table, which is why I think this is failing.
I'm basically trying to get counts for the students by their statuses, and grouped by the college they are from.
When I execute this query, I get the following exception.
The key selector type for the call to the 'GroupBy' method is not comparable in the underlying store provider.
Now I believe this is because there are way too many fields on the StudentInfo table, but I can't do anything about that in this case. There has to be a way to do what I want.
I need the following fields returned, all of which are counts, except College.
College | Accepts | Webapps | Ays | Total
Can someone please point me in the right direction.
Here is my model
public class EnrollmentCountsBySchool
{
    // selected terms
    public int[] SelectedTerms { get; set; }
    // list of terms
    public IEnumerable<SelectListItem> Terms { get; set; }

    // selected programs
    public int[] SelectedPrograms { get; set; }
    // list of programs
    public IEnumerable<SelectListItem> Programs { get; set; }

    // selected statuses
    public string[] SelectedStatuses { get; set; }
    // list of statuses
    public IEnumerable<SelectListItem> Statuses { get; set; }

    // list of results
    public List<EnrollmentCountsBySchoolResult> Results { get; set; }

My Query (way to long, I know.)
 var results =
            (from student in db.StudentInfo
             join college in db.Colleges on student.College.Id equals college.Id
             where model.SelectedTerms.Contains(student.TermOfInterestId.Value) &&
                   model.SelectedPrograms.Contains(student.ProgramId.Value) &&
                   model.SelectedStatuses.Contains(student.Status)

             group student by new
             {
                 College = college.Name,
                 Accepts = (
                         from s in db.StudentInfo
                         join c in db.Colleges on student.College.Id equals college.Id
                         where model.SelectedTerms.Contains(student.TermOfInterestId.Value) &&
                               model.SelectedPrograms.Contains(student.ProgramId.Value) &&
                               model.SelectedStatuses.Contains(student.Status) &&
                               student.Status.ToLower().Contains("accepted") ||
                               student.Status.ToLower().Contains("applicant")
                         group s by new
                         {
                             College = c.Name,
                         } into accepts
                         select new
                         {
                             accepts.Key.College,
                             Count = accepts.Count()
                         }
                 ),
                 Webapps =
                 (
                         from s in db.StudentInfo
                         join c in db.Colleges on student.College.Id equals college.Id
                         where model.SelectedTerms.Contains(student.TermOfInterestId.Value) &&
                               model.SelectedPrograms.Contains(student.ProgramId.Value) &&
                               model.SelectedStatuses.Contains(student.Status) &&
                               student.Status.ToLower().Contains("webapp")
                         group s by new
                         {
                             College = c.Name,
                         } into webapps
                         select new
                         {
                             webapps.Key.College,
                             Count = webapps.Count()
                         }
                 ),
                 Ays = (
                         from s in db.StudentInfo
                         join c in db.Colleges on student.College.Id equals college.Id
                         where model.SelectedTerms.Contains(student.TermOfInterestId.Value) &&
                               model.SelectedPrograms.Contains(student.ProgramId.Value) &&
                               model.SelectedStatuses.Contains(student.Status) &&
                               !student.Status.ToLower().Contains("accepted") &&
                               !student.Status.ToLower().Contains("applicant") &&
                               !student.Status.ToLower().Contains("webapp")
                         group s by new
                         {
                             College = c.Name,
                         } into ays
                         select new
                         {
                             ays.Key.College,
                             Count = ays.Count()
                         }
                 ),
                 Total = (
                         from s in db.StudentInfo
                         join c in db.Colleges on student.College.Id equals college.Id
                         where model.SelectedTerms.Contains(student.TermOfInterestId.Value) &&
                               model.SelectedPrograms.Contains(student.ProgramId.Value) &&
                               model.SelectedStatuses.Contains(student.Status)
                         group s by new
                         {
                             College = c.Name,
                         } into totals
                         select new
                         {
                             totals.Key.College,
                             Count = totals.Count()
                         }
                 )

             }
                 into grouping
                 select new EnrollmentCountsBySchoolResult
                 {
                     College = grouping.Key.College,
                     Accepts = grouping.Key.Accepts.Count(),
                     Webapps = grouping.Key.Webapps.Count(),
                     Ays = grouping.Key.Ays.Count(),
                     Total = grouping.Key.Total.Count()
                 }).ToList();

A: I ended up re-writing the query to search by colleges and join students, then do the grouping and I got the results I was looking for.
       var results =
            from college in db.Colleges
            join student in db.StudentInfo on college.Id equals student.UniversityId
            where model.SelectedTerms.Contains(student.TermOfInterestId.Value) &&
                  model.SelectedPrograms.Contains(student.ProgramId.Value) &&
                  model.SelectedStatuses.Contains(student.Status)
            group college by new
            {
                College = college.Name,
                Accepts = (
                 from c1 in db.Colleges
                 join s1 in db.StudentInfo on c1.Id equals s1.UniversityId
                 where model.SelectedTerms.Contains(s1.TermOfInterestId.Value) &&
                       model.SelectedPrograms.Contains(s1.ProgramId.Value) &&
                       model.SelectedStatuses.Contains(s1.Status) &&
                       s1.UniversityId == college.Id &&
                       s1.Status.ToLower().Contains("accepted") || s1.Status.ToLower().Contains("applicant")
                 select c1
                ).Count(),
                Webapps = (
                    from c2 in db.Colleges
                    join s2 in db.StudentInfo on c2.Id equals s2.UniversityId
                    where model.SelectedTerms.Contains(s2.TermOfInterestId.Value) &&
                          model.SelectedPrograms.Contains(s2.ProgramId.Value) &&
                          model.SelectedStatuses.Contains(s2.Status) &&
                          s2.UniversityId == college.Id &&
                          s2.Status.ToLower().Contains("webapp")
                    select c2
                ).Count(),
                Ays = (
                    from c3 in db.Colleges
                    join s3 in db.StudentInfo on c3.Id equals s3.UniversityId
                    where model.SelectedTerms.Contains(s3.TermOfInterestId.Value) &&
                          model.SelectedPrograms.Contains(s3.ProgramId.Value) &&
                          model.SelectedStatuses.Contains(s3.Status) &&
                          s3.UniversityId == college.Id &&
                          !s3.Status.ToLower().Contains("accepted") && !s3.Status.ToLower().Contains("applicant") &&
                          !s3.Status.ToLower().Contains("webapp")
                    select c3
                ).Count()
            }
                into grouping
                select new EnrollmentCountsBySchoolResult
                {
                    College = grouping.Key.College,
                    Accepts = grouping.Key.Accepts,
                    Webapps = grouping.Key.Webapps,
                    Ays = grouping.Key.Ays,
                    Total = grouping.Count()
                };

        model.Results = results.OrderByDescending(o => o.Total).ToList();


text:
Q: Type mismatch word Private Sub RunSpellCheckOnSelection()

    MsgBox "Running check..."

    Dim wbDictionaryCollection As Excel.Workbook
    Dim wsDictionary           As Excel.Worksheet
    Dim rngWords               As Excel.Range

    Set wbDictionaryCollection = appExcel.Workbooks.Open(Application.ActiveDocument.Path & "\Dictionary.xlsx")
    Set wsDictionary = wbDictionaryCollection.Worksheets(strLanguage)
    Set rngWords = wsDictionary.Range("A1").CurrentRegion

    Dim PUNCTUATION As String
    PUNCTUATION = ".,:;'!?/\@#$%^&*(){}[]-_=+|<>`~" & Chr(13)

    Dim blnWordFound As Boolean

    Dim nDictionaryWords As Long
    Dim iDictionaryWord As String

    Dim nWords As Long
    Dim iWord  As Long

    Dim nPunctuation As Long
    Dim iPunctuation As Long

    nDictionaryWords = rngWords.Rows.Count
    nWords = Selection.words.Count
    nPunctuation = Len(PUNCTUATION)

    ' For every word in selection:
    For iWord = 1 To nWords

            ' Check if the word is in the dictionary:
            blnWordFound = False

            For iDictionaryWord = 1 To nDictionaryWords
                    ''''''''
                    If Selection.words(iWord).Text = Mid$(rngWords.Cells(iDictionaryWord, 1), 1, Len(rngWords.Cells(iDictionaryWord, 1) - 2)) Then

This line provides me a type mismatch error, and I don't realise what's wrong here..
I edited and added the rest of code ! And I obtain a type mistach error on the Mid function

A: You have two separate syntax errors in that statement, and each of them is repeated.
First, the Cells property of a Range object returns a Cell object, not a string. That's causing the type mismatch error. To correct it, use rngWords.Cells(...).Range.Text in both places.
The first error is hiding a second error: The Cells property of a range takes a single number of type Long as its argument, but you've supplied two numbers. If you click Debug > Compile Project, it will highlight the word Cells and explain "Compile error: Wrong number of arguments or invalid property assignment." I can't tell what you expected the ",1" to do, but it shouldn't be there.


text:
Q: Is my ssh key correct? It doesn't start with 'ssh-rsa' (Trying to set up private key validation, worried about being locked out of server) I am trying to set up private key validation on my server. I think this is a simple question, I just don't want to get locked out of the server by mistake! I generated an ssh key with ssh-keygen. It is just a long list of characters as such :
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAA..etc
-----END OPENSSH PRIVATE KEY-----

However, the video I am watching on deployment shows an ssh key like such:
ssh-rsa b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAA..etc USER@desktop2FBF

I am not sure if they look different because I am on a mac and the guide is using windows. But my key does not begin with ssh-rsa or end with USER@... Also, I see there are two files created with this command, the .pub one I cannot open, so I assume I am copying and pasting the key from the right file(the only one I can open).
Thanks for any help.

A: ssh keys come in pairs -- a public key and a private key -- and that is what ssh-keygen creates, in two separate files.  The file with the .pub extension is the public key, is generally smaller, and has the form you see on the video.  The private key has the form you descibe with BEGIN PRIVATE KEY.  They are intentionally very different so they don't get accidentally mixed up.
To use the key-pair, you will install the public key on the server, but you keep the private key private -- it never goes anywhere and is never copied; you just use it from your private machine to access the server(s) you've installed the public key on.
So in your case, you need to open the .pub file to get the public key and copy that to you server.  The private key you keep local (possibly installing it into your ssh agent)

A: Open the directory where you created the key.
There will be a file called [kleyname].pub, you will find something like this there [ssh-rsa b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAA..etc USER@desktop2FBF]


text:
Q: MySQL Slow Query Analysis and Indexing Recently, we've noticed a particular query popping up in our slow query logs taking quite some time.  I've analyzed it to the best of my ability, but can't figure out for the life of me why it's taking so long, and why the indexes we've set up aren't being used.
Here's a simplified (i.e., readable) version of the query for the purpose of example:
SELECT processstage.id AS processstage_id,
  processstage.job_id AS processstage_job_id,
  processstage.event_id AS processstage_event_id, ...
FROM processstage INNER JOIN jobevent ON jobevent.id = processstage.event_id
WHERE processstage.due_date <= '2009-10-28 16:07:59' AND (EXISTS (
  SELECT 1 FROM job
  WHERE jobevent.job_id = job.id AND job.brand_id = 1
)) ORDER BY processstage.due_date;

Also, for good measure, it's important to note the size of the table, processstage:
mysql> SELECT COUNT(id) FROM processstage;
+-----------+
| COUNT(id) |
+-----------+
|    596183 |
+-----------+

When I run EXPLAIN on the query, I find that the processstage table is reading over a huge number of rows (see "Using where; Using filesort"), as no index is being used (that I can tell):
mysql> EXPLAIN SELECT processstage.id AS processstage_id, processstage.job_id AS processstage_job_id, processstage.event_id AS processstage_event_id     FROM processstage INNER JOIN jobevent ON jobevent.id = processstage.event_id      WHERE processstage.due_date <= '2009-10-28 16:07:59' AND (EXISTS (SELECT 1      FROM job      WHERE jobevent.job_id = job.id AND job.brand_id = 1)) ORDER BY processstage.due_date;
+----+--------------------+--------------+--------+---------------------------------------------------+---------+---------+------------------------------+--------+-----------------------------+
| id | select_type        | table        | type   | possible_keys                                     | key     | key_len | ref                          | rows   | Extra                       |
+----+--------------------+--------------+--------+---------------------------------------------------+---------+---------+------------------------------+--------+-----------------------------+
|  1 | PRIMARY            | processstage | ALL    | ix_processstage_due_date,processstage_event_id_fk | NULL    | NULL    | NULL                         | 606045 | Using where; Using filesort |
|  1 | PRIMARY            | jobevent     | eq_ref | PRIMARY                                           | PRIMARY | 4       | processstage.event_id |      1 | Using where                 |
|  2 | DEPENDENT SUBQUERY | job          | eq_ref | PRIMARY,ix_job_brand_id                           | PRIMARY | 4       | jobevent.job_id       |      1 | Using where                 |
+----+--------------------+--------------+--------+---------------------------------------------------+---------+---------+------------------------------+--------+-----------------------------+
3 rows in set (0.00 sec)

Oddly enough, we've got indexes on the columns utilized in the query's WHERE clause:
mysql> SHOW INDEXES FROM processstage;
+--------------+------------+----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table        | Non_unique | Key_name                   | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+--------------+------------+----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| processstage |          0 | PRIMARY                    |            1 | id          | A         |      614150 |     NULL | NULL   |      | BTREE      |         |
| processstage |          1 | ix_processstage_job_id     |            1 | job_id      | A         |       47242 |     NULL | NULL   | YES  | BTREE      |         |
| processstage |          1 | ix_processstage_stop_date  |            1 | stop_date   | A         |      614150 |     NULL | NULL   | YES  | BTREE      |         |
| processstage |          1 | ix_processstage_order      |            1 | order       | A         |          16 |     NULL | NULL   | YES  | BTREE      |         |
| processstage |          1 | ix_processstage_start_date |            1 | start_date  | A         |      122830 |     NULL | NULL   | YES  | BTREE      |         |
| processstage |          1 | ix_processstage_milestone  |            1 | milestone   | A         |       12794 |     NULL | NULL   | YES  | BTREE      |         |
| processstage |          1 | ix_processstage_due_date   |            1 | due_date    | A         |       51179 |     NULL | NULL   | YES  | BTREE      |         |
| processstage |          1 | ix_processstage_process_id |            1 | process_id  | A         |       76768 |     NULL | NULL   | YES  | BTREE      |         |
| processstage |          1 | processstage_event_id_fk   |            1 | event_id    | A         |        3722 |     NULL | NULL   | YES  | BTREE      |         |
+--------------+------------+----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+

Any ideas as to why our indexes are going seemingly unused?  Perhaps I'm missing something very obvious or am approaching this entirely the wrong way.  Any input or suggestion is very much appreciated!

A: How many jobevents do you get where job.brand = 1? If it's a reasonable amount you could try the following queries to alleviate some joins and the sub query.
First  Query:
select distinct jobevent.id from jobevent
inner join job on job.id = jobevent.job_id
where job.brand = 1

followed by
select processstage.id as processstage_id,
  processstage.job_id as processstage_job_id,
  processstage.event_id as processstage_event_id, ...
from processstage
where processstage.due_date <= '2009-10-28 16:07:59' and
processstage.event_id in (list of event ids from the previous query)
order by processstage.due_date;

Previous Thoughts:
Have you tried doing a regular join to jobs instead of the dependent sub query? Something like:
SELECT processstage.id AS processstage_id,
  processstage.job_id AS processstage_job_id,
  processstage.event_id AS processstage_event_id, ...
FROM processstage
INNER JOIN jobevent ON jobevent.id = processstage.event_id
INNER JOIN job ON job.id = jobevent.job_id
WHERE processstage.due_date <= '2009-10-28 16:07:59' AND
job.brand = 1
ORDER BY processstage.due_date;

Do you have job events that don't have jobs?

A: try using USE INDEX. if mysql decides that it needs to read a certain fraction of the table, it will resort to a table scan. with USE INDEX, you're telling mysql to consider table scans very expensive.

A: Some ideas:

*

*Do an explicit type conversion from your string '2009-10-28 16:07:59' to a date. What may happen now is that your processstage.due_date are converted to strings before the comparison. Doing a type conversion (not sure about the systax in MySQL, but should be something like CAST (<your date string> as DATE) will help the optimizer figure out to use the index.

*How many records satisfy the date condition? If most of the table fits the condition or the index is not very selective, there may not be any advantage to using the index.


text:
Q: Is there any built in class with HTTP response codes and its categories? When I need to check if a response code is one of success codes (2xx), then I usually create a integer array and look thru it. For example,
public static final int[] SUCCESS_STATUS_CODES = new int[]{
        200, 201, 202, 203, 204, 205, 206, 207, 208, 226
};

I do the same for other response codes.
I was wondering if there is a built-in object which already holds all these codes and regularly updates them which I can use?
For example,
//pseudo code
if(responseCode is from success 2xx category)
   do something
else if (responseCode is from error 4xx category
   do something

A: org.springframework.http.HttpStatus has a method HttpStatus.is2xxSuccessful() returns a boolean. It's part of Spring, not built into Java, but hopefully will still be useful to some people.

A: As far as I know, there is no such class in the standard library.  The closest I know if is java.net.HttpURLConnection, which provides static constants for the various codes.
But you seem to be going to more work than you need to do. HTTP response code categories are built into their values.  You should be able to do something along these lines:
switch (responseCode / 100) {
    case 1:
        /* informational response */
        break;
    case 2:
        /* success response */
        break;
    case 3:
        /* redirection response */
        break;
    case 4:
        /* client error response */
        break;
    case 5:
        /* server error response */
        break;
    default:
        /* bad response code */
        break;
}

A: Bit late to the part but I would like to extend Jaxon's message:
    int responseCode = 200;
    HttpStatus httpStatus = HttpStatus.valueOf(responseCode);
    if (httpStatus.is2xxSuccessful())
    {
      // do something
    }


text:
Q: Same or different name for the field in a JSON-formatted input for an API that can take 2 different formats I have an API that takes an input like
{ 'fileContent': 'base64-encoded file here' }

I would like to accept also an URI with the file content.
Should I use the same fileContent field name, for example:
{ 'fileContent': 'https://example.com/filename' }

and then decode the base64 or download the URI in my code, or use a different field name, for example:
{ 'fileUri': 'https://example.com/filename' }

A: Using a different field name is more flexible and makes your code less buggy when checking the field contents.


text:
Q: Selecting first empty row with specific columns for each sheet VBA Is there any way that I can possibly make the function change to a specific column for each sheet in the ActiveWorkbookI tried various versions but can't seem to get it right.
Sub resetFilters()

Dim sht As Worksheet

On Error GoTo ErrorHandler

Application.ScreenUpdating = False

   'On Error Resume Next
        If ActiveSheet.FilterMode Then
    ActiveSheet.ShowAllData

  End If

Range("A3:T3").ClearContents
Application.ScreenUpdating = True

Call GetLastRow

Exit Sub
ErrorHandler:
Debug.Print "Error number: " & Err.Number & " " & Err.Description

End Sub
Private Function SelectFirstEmptyRowInColumnH(ByVal sheet As Worksheet, Optional ByVal fromColumn As Long = 8) As Long

    SelectFirstEmptyRowInColumnH = sheet.Cells(sheet.Rows.Count, fromColumn).End(xlUp).Row

End Function

Private Sub GetLastRow()
Dim selectLastRow As Long

selectLastRow = SelectFirstEmptyRowInColumnH(ActiveSheet, 8)
 Cells(selectLastRow, 8).Offset(1, 0).Select

 End Sub

A: A worksheet is an object and can't be passed as an argument ByVal. It must be ByRef, which is the default and can therefore be omitted. Note also that Sheet is a word reserved for VBA's use. In most cases VBA will be able to determine your intention and allow you to use its vocabulary the way you wish, but for you, when faced with the task of trouble shooting, it is a hell of a job to determine in each case whether Sheet means VBA's sheet or your own sheet. Select any word in your code and press F1 to let VBA show you the meaning it attaches to it and how to use it.
Other than that, note that your function returns the last used row. The first empty one is the next one after that. So, I would write that function somewhat like this:-
Private Function FirstEmptyRow(Ws As Worksheet, _
                               Optional ByVal Clm As Long = 1) As Long
    With Ws
        FirstEmptyRow = .Cells(.Rows.Count, Clm).End(xlUp).Row + 1
    End With
End Function

Observe that I changed the default for the optional column to 1. The default should be both the most logical choice and the one most commonly used. In the case of the last row that is the first column, column A.
Here is an alternative based on your comment (which I couldn't fully understand). This code looks for the word "Style" in Rows(3) of the ActiveSheet and returns the next blank row in the column where "Style" was found.
Private Function FirstEmptyRow() As Long
    ' 9 Apr 2017

    Dim Clm As Long

    With ActiveSheet
        On Error GoTo ErrHandler:
        Clm = WorksheetFunction.Match("Style", .Rows(3), 0)
        FirstEmptyRow = .Cells(.Rows.Count, Clm).End(xlUp).Row + 1
    End With
ErrHandler:
    Err.Clear
End Function

If the word "Style" isn't found an error will occur and the execution will jump to the Label ErrHandler: which does nothing. You might want to let it handle the situation in some way. As the function stands the row number it returns will be zero which will cause an error if you try to address that row.

A: you could use this function:
Private Function SelectFirstEmptyRowInColumnWithGivenHeader(ByVal sheet As Worksheet, Optional ByVal header As String = "Style") As Long
    Dim col As Variant
    With sheet
        col = Application.Match(header, .Rows(1), 0)
        If Not IsError(col) Then
            .Activate '<--| you must select a sheet to activate a cell of it
            .Cells(.Rows.Count, col).End(xlUp).Offset(1).Select
        End If
    End With
End Function

and exploit it in your main code as follows:
Sub main()
    Dim sht As Worksheet

    Application.ScreenUpdating = False '<--| this to prevent sheet activating slow down the code (and annoy you)
    For Each sht In Worksheets
        SelectFirstEmptyRowInColumnWithGivenHeader sht , "Style" '<--| you can omit the 2nd parameter and it'll be assumed the default column header
    Next
    Application.ScreenUpdating = True '<--| get default behavior back in place
End Sub

A: You can just pass the desired column number to the function.  Optional ByVal fromColumn As Long = 8 means that column 8 (column H) is the default column if no column number is passed when the function is called.  But passing a column number will override that default.
So in this line, passing the 8 is actually not required, although probably good for clarity, and could be written like so with the same result (returning the last row for column H):
selectLastRow = SelectFirstEmptyRowInColumnH(ActiveSheet)

To change the column number to 2 (column B) for example, you would change the line like so:
selectLastRow = SelectFirstEmptyRowInColumnH(ActiveSheet, 2)

I would also recommend that you genericize the name of the function to SelectFirstEmptyRowInColumn so to avoid confusion.

A: This simple code will help you.
Sub FindFirstEmptyRow()
Cells(Rows.Count, 1).End(xlUp).Offset(1).Select
End Sub
☺ ☺


text:
Q: How do I access the HTTP headers in the ServiceStack v4 ServiceClient? In ServiceStack v3 I could check the HttpStatusCode or Location headers with the LocalHttpWebResponseFilter:
var client = new JsvServiceClient(ServiceUrl);
client.LocalHttpWebResponseFilter = delegate(HttpWebResponse httpRes)
{
    Assert.AreEqual(httpRes.StatusCode, HttpStatusCode.Created);
};

Related post: POST to ServiceStack Service and retrieve Location Header
The filter is missing in ServiceStack v4. I couldn't find any alternatives. Is checking the HTTP headers still supported?

A: Just added the following to the v4.0 Release Notes Changes:

*

*The LocalHttpWebRequestFilter and LocalHttpWebResponseFilter in the Service Clients were renamed to just RequestFilter and ResponseFilter

*The Global HttpWebRequestFilter and HttpWebResponseFilter filters were also renamed to GlobalRequestFilter and GlobalResponseFilter respectively.


text:
Q: How to extract the number of hydrogens from a chemical formula (i.e. from C18H36P1 to get the 36) using Pandas I would like to be able to make a new column in a pandas dataframe that comprises the number of hydrogens from a chemical formula. Getting the number hydrogens from this chemical formula C18H36P1S1, would give 36. The Chemical formulas are general so you can't just feed the exact chemical formula, there are thousands of them in a column.

A: import re

REGEX = re.compile(r'H(?P<hydrogens>\d+)')
REGEX.search('C18H36P1S1').group('hydrogens')

returns:
'36'

A: You can use str.extract
df = pd.DataFrame({'formula':['C18H36P1S1']})
df['No Hydrogens'] = df['formula'].str.extract('.*H(\d+)[A-Za-z].*')

    formula     No Hydrogens
0   C18H36P1S1  36


text:
Q: Run command at time of object creation I have following code for a simple class (stack):
#lang racket

(define stackClass%
  (class object%
    (super-new)
    (init-field (mystack '(A B C)))

    (define/public (push n)
      (set! mystack (cons n mystack)))

    (define/public (pop)
      (cond [(empty? mystack)   #f]
            [else  (define res (car mystack))
                   (set! mystack (rest mystack))
                   res] ))

    (define/public (show)
      mystack)

    mystack   ; I want to output mystack at time of creation of class object; not working here;

    )); end class;

; USAGE:
(define sc (new stackClass%))
(send sc push 1)
(send sc push 2)
(send sc show)
(send sc pop)
(send sc show)

Output:
'(2 1 A B C)
2
'(1 A B C)

I want to output mystack at time of creation of class object. However, it is not working in this code, though there is no error being shown.
Using following instead of (init-field (mystack '(A B C))) also does not help:
(init (L '(A B C)))
(define mystack L)

How can I run a piece of code at the time of class creation?

A: Yes, your code is running fine. In addition, "mystack" is being evaluated. However, it produces no output. If you want to display something, you can use one of a number of functions. Try replacing mystack with (println mystack) in your code.


text: Q: Unable to create channel in hyperledger fabric I am able to create channel and do operations up to instantiate chain code in my local machine. When I work on AWS instance I am getting issue while creating channel


text:
Q: Time to time html display on Backend Time to time html display on Backend
I'm using Magento 2.4.3-p2 version and I'm getting this issue on my Admin Magento.
Please see attached image link.
Can someone help me with this on how to disable or remove this popup? Thank you


text:
Q: Range variable errors in Excel VBA ; "Object variable or With block variable not set" I don't know why I keep getting an error when I try to run this code. The error occurs after the MsgBox appears but after clicking "debug" on the error box, the Msgbox line is highlighted. I suspect there is a problem with the First and Last range variables.
I tested that the variables ws and Criteria are valid and I commented out the rest of the function to find the problem. I was using this code earlier and had no problem with it so I don't know what changed.
Function TotalUniqueValues(ws As Worksheet, Criteria As String) As Integer
    Dim Last As Range, First As Range, rng As Range

    Set Last = ws.Cells.Find(What:=Criteria, _
        After:=Range("B1"), _
        LookAt:=xlPart, _
        LookIn:=xlValues, _
        SearchOrder:=xlByRows, _
        SearchDirection:=xlPrevious, _
        MatchCase:=False)

    Set First = ws.Cells.Find(What:=Criteria, _
        After:=Range("B1"), _
        LookAt:=xlPart, _
        LookIn:=xlValues, _
        SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, _
        MatchCase:=False)

    MsgBox Last.Address

    Set rng = Range(First, Last)
End Function

A: It's likely the Last object never got set.
You can test it by putting this line before MsgBox Last.Address
if Last is Nothing then stop


text:
Q: JQuery Validate Regex Password Validation I have been reading about how to manipulate regex, and I do think I have the correct formula for my purpose, but I cannot seem to get it to work.
This is my code
$.validator.addMethod("pwcheck", function(value) {
    var regex = /^[a-zA-Z0-9]*$/;
    if (!regex.test(value)) {
        return false;
    }
});

I added this method to my password in the .validate({rules{}});
It is linked properly, but whatever I input in the text box I get the message I wrote in the .validate({messages{}});
the user should be only allowed to input letters and numbers, and seeing other methods posted on this site I tried to mimic and copy them, but it isn't working.

A: $.validator.addMethod("pwcheck", function(value) {
   return /^[A-Za-z0-9]*$/.test(value)
});


text:
Q: Least squares approximation I have data points which is mydata = {{0, 0}, {1, 1}, {2, 0}};
From this data, I need to do the least squares approximation by using Bernstein polynomials to produce a set of Bezier points. Before the approximation, I define the uniform parameter values. And now I'm stuck on how to implement the Bernstein polynomial to get the normal equation. I have to use the Bernstein polynomial in order to find define the bezier points.
   mydata = {{0, 0}, {1, 1}, {2, 0}};

   data = mydata;
   numdata = Length[data];

   Print["Input numdata =", numdata];
   Print["Data = ", MatrixForm[data]];

   uniformparams[numdata_] := (
   Do[
    params[[i + 1]] = (i/(numdata - 1)),
    {i, 0, numdata - 1}
    ];
   Print["Uniform params = ", params // N];
   );

   approx[n_, params_, data_] := (

   mat1 = Table[params[[1 - i]], {i, 1, numdata}];
   Print["mat1", MatrixForm[mat1]];

   mat2 = Table[params[[i]], {i, numdata}];
   Print["mat2", MatrixForm[mat2]];

   A = {mat1};
   B = {mat2};
   (*C={A,B};*)
   combine = Transpose[{A, B}];
   Print["complete mat", MatrixForm[combine]];

   rhsx = Take[{data}, All, 1];
   Print["rhs", MatrixForm[rhsx]];

   );


text:
Q: Does Audio Units support airplay? I want to play music when airplay mirroring is connected, but is seems impossible to do that, when airplay mirroring is connected I can't force audio out to speaker, because airplay mirroring will disconnected when I do that. I want to know whether audio unit is support airplay?

A: Yes, it does. I have an app that uses a low-level custom Audio Unit and I just tested it on my Apple TV and it works fine with both mirroring and selecting the Apple TV device from the MPVolumeView view.


text:
Q: Error: connect ECONNREFUSED , mocha , supertest I'm new  to  mocha and supertest , I'm trying to test  my API but I always get  connection refused error  .

var request = require('supertest');

 it("posts a new comment to /comment", function (done) {
    var comment = { username: 'riheb', userId: 'test1', userPhotoId: '12a', comment: 'update file  now' };

    request("http://localhost:3000")
      .post("/sp/place/582f148515035818e080e653/folder/582f16b3ef9caf029863331b/file/583d6b5243af5628b8491fd3/comment")
      .send(comment)
      .expect(200)
      .expect(" riheb comment is stored", done);
  });
});

Could you give any clue why this happend?
 With Thanks

A: If you want to use supertest library, you have to expose and inject your app (express) not a url (because you won't have an active server listening):
var request = require('supertest');
var app = require('../yourappexposed');

describe("Comments", function() {
 it("posts a new comment to /comment", function (done) {
    var comment = { username: 'riheb', userId: 'test1', userPhotoId: '12a', comment: 'update file  now' };
    request(app)
      .post("/sp/place/582f148515035818e080e653/folder/582f16b3ef9caf029863331b/file/583d6b5243af5628b8491fd3/comment")
      .send(comment)
      .expect(200)
      .expect(" riheb comment is stored", done);
    });
  });
});


text:
Q: Declaration error in Mysql DELIMITER //

create procedure del()
begin
    declare p_balance decimal(20,4), p_crdr bit, p_debit decimal(20,4), p_credit decimal(20,4);
end //

DELIMITER ;

  1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' p_crdr bit, p_debit decimal(20,4), p_credit decimal(20,4); end' at line 3

A: You can't declare multiple variables in one stamement
DELIMITER //

create procedure del()
begin
    declare p_balance decimal(20,4);
    declare p_crdr bit;
    declare p_debit decimal(20,4);
    declare p_credit decimal(20,4);
end //

DELIMITER ;


text:
Q: JS Toggle: закрытие текущего открытого кода при повторном нажатии другого элемента Имеется код:
$('.character__item-container-info-icon').on('click',function() {
    var parent = $(this).parent();
    parent.toggleClass('character__item-container-info_current');
});

Как сделать так, чтобы при повторном нажатии, но уже другого элемента, текущий открытый код закрывался?

A: Не уверен, что правильно понял "текущий открытый код закрывался", но если вы имеете ввиду "как сделать, чтобы при нажатии другого элемента, у родителя текущего убирался класс", то ответ верный:
$('.character__item-container-info-icon').on('click',function() {
    var parent = $(this).parent(),
        //запоминаем, есть ли класс в текущего родителя
        parentIsOpen = parent.hasClass('character__item-container-info_current');
    //убираем указанный класс у всех элементов, у которых он есть
    $('.character__item-container-info_current').removeClass('character__item-container-info_current');
    //добавляем класс родителю нашего элемента, если его не было
    if(!parentIsOpen)
        parent.addClass('character__item-container-info_current');
});


text:
Q: Hybris sort parameter in Solr A weird problem is occurring.In my project,in lower environments everything seems fine,but in the higher environment(production),a sort parameter is getting appended to the Solr query when I search for a specific text,of the form:
                    &sort=score+asc,age_int+asc

where age is an attribute defined in items.xml.How do I debug this issue as I cannot find anything in SolrSort field also in backoffice,and also since this issue only occurs in production?

A: If you are actually seeing this sort parameter appearing in the query URL string, then it originates from outside of Solr. I would check whatever client you are using to talk to Solr.
If you are seeing it in the Solr query, but it did not come from outside of Solr as an explicit parameter, it may be defined in solrconfig.xml, overlayconfig.json or params.json (last two for more recent versions of Solr). It is possible your production has those files and your development/QA do not.


text:
Q: How to change the path of conda base I am a Linux cluster user. While I installed a version of miniconda, the cluster had its own version of anaconda. When I do
conda info --envs

the output is
# conda environments:
#
         /home/user/miniconda3/envs/my_envs
base  *  /usr/local/anaconda

This type of settings may sometimes result in the "permission denied" error. Is there a method to change the path of the base environment to /home/user/miniconda3?

A: *

*Prepend condabin/conda into PATH. Write the following settings into your shell init files. ~/.bash_profile, ~/.bashrc for Bash, ~/.zshrc for ZSH.
export PATH="/home/user/miniconda3/condabin:$PATH"

Reopen a new shell. Check the result of which -a conda. Make sure the conda from /home/user/miniconda3/condabin takes precedence over other conda executables.

*Cleanup and redo conda init.
Open your shell init files. Remove the following content,
# >>> conda initialize >>>
...
# <<< conda initialize <<<

Save the configuration files.
Reopen a new shell, type /home/user/miniconda3/condabin/conda init once.
Done.

Update: But I still recommend you use the Anaconda already installed on your system. There's no need to install two conda packages.
Because conda is a python manger and a package manager. You can create environments with any version of Python you want with command conda.
The only difference between an Anaconda and a Miniconda installation is that, the "base" environment where conda is installed from Anaconda, is bundled with more pre-installed packages than the "base" env from Miniconda.
Configuring conda to store environments under your home directory is enough.
conda config --prepend pkgs_dirs /home/user/.conda/pkgs
conda config --prepend envs_dirs /home/user/.conda/envs

All you need is the execution permission of the command conda, the environments and pkg caches are stored under your home folder.

A: When one installs different distributions of Anaconda, the package shell scripts change the base environment. (That was what happened when I installed Miniforge3 to experiment with python for M1 Silicon)
Try to See: echo $PATH and one can see paths to active base environment but those paths wont be on ~/.bash_profile PATH
To change default/base environment follow below steps:
On Mac:

*

*Open your /Users/your username/.zshrc (in a TextEditor)

*There would be the paths to current base environment. Replace the path with the   one which should be the default one for your case.

*Close and Reopen Terminal.

*Run 'conda info --envs' and the base env would be changed to path mentioned in ~/.zshrc


text:
Q: Using jQuery widget in Dojo My web app mainly uses Dojo and I'm trying to implement jQuery's select2 (https://select2.github.io/). I read this and I know that it's possible to mix the two together but in my case, everything's built on top of Dojo and it's already a rather large web app. So is it still possible to implement a single jQuery widget into my Dojo based web app?
If not, would I have to go through the source code for select2 and convert into Dojo form?

A: I don't see why it wouldn't work. As long as there aren't any conflicts, you can use other libraries in conjunction with dojo. Now it may not be built with the AMD like everything else in dojo but it will still work fine.


text:
Q: Google cloud function call from postman returning google login auth check I'm making a call in Postman to a function I've uploaded to GCP. But the response I get is the HTML of a Google auth web page.

I've generated the auth token I need and include it in the headers. I've also removed auth blocks from the function in GCP just in case, and added Viewer permissions to allUsers in GCP. I'm still forbidden when I try to access from the browser - although according to this post that should resolve the issue at least in Postman.
Is there some way I can log in on Postman so I'm not prompted for the auth? Or bypass it altogether?

A: For allUsers the role should be Cloud Functions Invoker rather than Viewer.


text:
Q: How do delete permanently (not hide) some of my iBooks? I have several iBooks that I have no interest in reading again. I want to delete them completely, but have only been successful in hiding them. I don't even want them in my iCloud storage now, but can't figure out what to do. I have iOS 9 and probably hundreds of books.

A: Open iBooks and right-click on a book you want to delete. When you right click you get several options and bottom option is delete. It then asks you if you want to permanently book and it deletes it from iCloud as well.

A: As of iOS 11 & OS X 10.13 (High Sierra), there is no way to permanently delete items from iBooks. The closest option is to hide them, where they can only be restored (unhidden) from iBooks on OS X.


text:
Q: "Slim" directed polytopes: any established name for them? This is a "looking for context" question.
Let's say that a polytope is directed if its 1-skeleton is an oriented graph with no cycles, one source, one sink. (Edit: let us additionally assume that every face also has one source, one sink.) In this case, the vertices form a poset, and we can extend this poset structure to a (non-reflexive) relation on all the faces, by saying $F_1 < F_2$ if $\max (F_1) \leq \min (F_2)$. Then we can consider face-chains with respect to this new relation (notice that a vertex is comparable with itself so a vertex can repeat in a chain, while bigger faces can't). For a face-chain $(F_1 < \ldots < F_n)$ inside the face $F$, let's say that its dimension gain is $(\sum \dim F_i - \dim F)$. Note that dimension gains can be both positive and negative. Now, the definition:
Definition. A directed polytope is slim if a chain of length $n>1$ has dimension gain at most $n-2$.
Examples. Simplices and cubes with standard directions are slim. Associahedra with Tamari directions are slim.
Has this condition appeared in the literature previously?


text:
Q: PDF font subsetting and subset merging in Java I have a part in my code where I am programatically filling out PDF forms using iText Java based on user-entered data, and then I concat a number of such PDFs into one using iText again.
The PDF forms that are getting merged can be (and usually are) different.
The resulting PDF is way too large - looking at it, 98% of the space is taken by fonts.
The way I understand it, what happens is that the individual PDF forms have different font subsets, so when I merge them, I get massive amount of duplicate glyphs, except that the subsets are not identical, so I can't get rid of them without merging the subsets.
The other problem is that the PDF forms themselves might not even contain subsets, but heavily packed fonts that have 2000+ glyphs, so even if I manage to leave only one instance of that font in the PDF, that still can be many megabytes. Hence it seems that I need to be able to 1) create and 2) merge existing font subsets.
The quirk is that I do not control neither the PDF forms (that are being filled out) nor their number, nor the order in which they are concatenated, so it is not possible to solve this by controlling what kind of fonts are embedded in them.
Adobe Acrobat can of course solve such a problem - it can create and also merge font subsets - but I need a programatic, server-side solution. According to google hits, iText cannot do this. Is there another library that I could use (or anything else I can do)?


text:
Q: How to upload a large file (> 1GB) directly to Amazon S3 from a given URL using NodeJS without actually saving the file in local? I tried uploading a large file to S3 in many ways in NodeJS using aws-sdk but eventually ended up just uploading only 1mb of a file which is actually 1.2 GB.
So, I tried using  streaming-s3   in node js, the code is shown below.
I referred  https://www.npmjs.com/package/streaming-s3  for streaming-s3 package.
var streamingS3 = require('streaming-s3');
var request = require('request');
var url = 'XXXXXXXXX';
var rStream = request.get(url);

var uploader = new streamingS3(
  rStream,
  {accessKeyId: 'XXXXXXXXXXXXX',
    secretAccessKey: 'XXXXXXXXX'
  },
 {
    Bucket: 'XXXXXXXXX',
    Key: 'XXXXXXX',
    ContentType: 'text/html'
  },

  {
    concurrentParts: 2,
    waitTime: 10000,
    retries: 1,
    maxPartSize: 10 * 1024 * 1024
  }
);

uploader.begin();

When I run this code, the chunks from the file are not actually getting uploaded to S3 in streams.
Only 1mb is getting uploaded, but not the entire file.
Is there any other way to upload a file to S3 from a URL ?

A: Try using s3-upload-stream. It uses Multipart Uploads. For objects larger than 100mb it is recommended to use Multipart Uploads.

A: AWS has "managed upload" to take care of large file upload to S3. Tried a few mb of data and it gets uploaded albeit it takes a few seconds. S3-upload-stream does a great of optimzation and with larger parts (chunks) the optimzation is great. I hope that you arent using http to do that uploads, since 1GB files take a large amount of time to upload and http eventually times out, hence you couldn't see a response. The better way to do that, is to leverage the upload functionality to a worker and once done, send a notification through SSE (since you use nodejs - implementing SSE should be easier since its a javascript paradigm anyway). I can give a sample implementation with a few mb file here, but I urge to follow a different design incase of uploading 1GB files.
Here is an example that I use:
THis is with managedUpload - 10mb arnd 20sec,  50 mb file takes around 32s, 80mb takes (6MB chunks - 16parts)
   @VideoFileValidator
async managedUploadFileToFolder(bucket: BucketModel, fileObj: any) {

    return new Promise(async (resolve, reject) => {
        // first make sure that the bucket exists
        try {
            const bucketList = await this.listBuckets();
            if (bucketList.filter(item => item.Name.toUpperCase() === bucket.name.toUpperCase()).length >= 1) {
                // means there is a bucket and obj can be created
                // create obj params
                const metadata: AWS.S3.Metadata = JSON.parse(JSON.stringify(bucket.fileData.metadata));
                const keyFolder = bucket && bucket.folder ? APP_CONSTANTS.COMMON.APP_NAME + '/' + bucket.folder + '/'+bucket.fileData.name : 'tf-default-video';

                const putObjParam: AWS.S3.PutObjectRequest = {
                    Body: Readable.from(this.utilService.bufferToStream(fileObj['buffer'])).pipe(zlib.createGzip()),
                    Bucket: bucket.name,
                    Key: keyFolder,
                    ContentType: 'multipart/form-data',
                    Metadata: metadata,
                    StorageClass: 'STANDARD'
                }
                this.s3MangedUpload = new AWS.S3.ManagedUpload({
                    leavePartsOnError: false,
                    partSize:1024*1024*6,
                    queueSize: 16,
                    params: putObjParam,
                    tags: this.utilService.createTags(false,true)
                });
                this.s3MangedUpload.send((err, uploadData) => {
                    console.log('aws err obtained:', err);
                    if(err) {
                        reject(AppConfigService.getCustomError('FID-S3-CUSTOM', `Error uploading the data:${err.message} - code: ${err.code} - status: ${err.statusCode}`));
                    }
                    resolve(plainToClass(CommonOutputResponse, {timestamp: AppUtilService.defaultISOTime(),
                        status: 'Success', message: `${fileObj['originalname']} Uploaded successfully with alias ${bucket.fileData.name}`,
                        data: {
                            uploadedToHttps: uploadData.Location,
                            uploadedToFolder: `s3://${bucket.name}//${bucket.folder}`
                        }
                    }));
                });
                this.s3MangedUpload.on('httpUploadProgress', (progress) => {
                    console.log('progress:', progress);
                });

            } else {
                reject(AppConfigService.getCustomError('FID-S3-CUSTOM', `Object cannot be created since ${bucket.name} doesnt exist`));
            }
        } catch (err) {
            console.log('err:', err);
            reject(AppConfigService.getCustomError('FID-S3-CUSTOM', 'Object cannot be uploaded -' + err.message));
        }

    });
}

Code explained:
The decorator

@VideoFileValidator

*

*validates if the input from http is a valid video file of types - mp4, mkv, avi (validates based on the file extension, so no way to read that large buffer)

The method by itself uses AWS.S3.managedUpload -  defines the queue size as part of params and used the Bodyparam to define the stream
Note: The stream here is the one coming from http input. comes as a buffer and hence converted to stream
.send() takes care of the actual streaming of data. I am unsure if piping happens in the backend, but I guess that might be the case. We can check for upload progress, using the 'httpUploadProgress' event.
The s3-upload-stream on the other hand performs better with larger chunk sizes. I tried with the same 10mb and 50 mb files with the below configuration and was able to save a few seconds, so hopefully it might interest you. Again, uploading 1GB file, might needed a better architecture design
@VideoFileValidator
    async streamFileUpload(bucket: BucketModel, fileObj: any){
        const metadata: AWS.S3.Metadata = JSON.parse(JSON.stringify(bucket.fileData.metadata));
        const keyFolder = bucket && bucket.folder ? APP_CONSTANTS.COMMON.APP_NAME + '/' + bucket.folder + '/'+bucket.fileData.name : 'tf-default-video';

        const putObjParam: AWS.S3.PutObjectRequest = {
            Bucket: bucket.name,
            Key: keyFolder,
            ContentType: 'multipart/form-data',
            Metadata: metadata,
            StorageClass: 'STANDARD'
        }

    return new Promise(async (resolve, reject) => {

        const read = this.utilService.bufferToStream(fileObj['buffer']);
        const compress = zlib.createGzip();
        const upload = this.s3Upload.upload(putObjParam);
        upload.maxPartSize(1024*1024*6); // 20 MB
        upload.concurrentParts(15);

        upload.on('part', function (details) {
            console.log('still uploading ....',details);
        });

        upload.on('uploaded', function (details) {
            console.log('upload completed',details);
            upload.end();
            resolve(plainToClass(CommonOutputResponse, {timestamp: AppUtilService.defaultISOTime(),
                status: '200-OK', message: 'Uploaded succesfully',
                data: {
                    location: details['Location'],
                    uploadedTo: details['Bucket'],
                    withName: details['Key']+''+bucket.fileData.name
                }
            }));
        });

        upload.on('error', (error) => {
            console.log('error occured upploading the data:', error);
            upload.end();
            reject(AppConfigService.getCustomError('FID-S3-CUSTOM', 'Error occured:'+error['message']));
        })

        read.pipe(compress).pipe(upload);
    })

    }

"Part" - event to check on progress, "uploaded" - event that is emitted when file is uploaded completely. I more or less used the same configuration


text:
Q: Return the first integer present in the string I am trying to solve a challenge from jshero.net. The challenge is:

Write a function parseFirstInt that takes a string and returns the
first integer present in the string. If the string does not contain an
integer, you should get NaN. parseFirstInt('No. 10') should return 10
and parseFirstInt('Babylon') should return NaN.
The solution I came up with is:

function parseFirstInt(num){
let input=parseInt();
if(Number.isNaN(num)){
return NaN} else {
return num[0]}

}

But it doesn't work. It returns the following errors:

parseFirstInt('No. 10') does not return 10, but 'N'.
Test-Error! Correct the error and re-run the tests!

Do you guys have any ideea how to solve it?

A: I would definitely use regex for this.
Use what's written here in order to replace all Strings with nothing
Get the first integers in a string with JavaScript
Then after that I would check if the length is 0. If it is return NaN if not then parseInt

A: this should work :
    function parseFirstInt(text){

       for(let i=0;i<text.length;i++){
          if(text.charCodeAt(i)<58 && text.charCodeAt(i)>47){
              return text[i];
           }
       }
       return NaN;
    }

A: Using a /[-+]?[0-9]+/g in match() function, you can find and parse the first integer present in the string.

function parseFirstInt(num){
  const ints = num.match(/[-+]?[0-9]+/g)
  return ints ? Number(ints[0]): NaN
}

console.log(parseFirstInt('No. 10'));
console.log(parseFirstInt('NaN'));
console.log(parseFirstInt('No. -10'));


text:
Q: I can't solve system of differential equations with Dsolve Here is the code and the system, and it is supposedly analytically solvable.
$$\frac{dx(t)}{dt} = i(\frac{3w}{2}x + ke^{2iwt}y)$$
$$\frac{dy(t)}{dt} = i(kxe^{-2iwt} +\frac{3w}{2}y)$$
and my code attempt
DSolve[{x'[t] == I*((3*w/2) x[t] + y[t]*k*E^(2 I*w*t)), y'[t] == I*(k*x[t]*E^(-2*I*w*t) + 3*w*y[t]/2)}, {x[t], y[t]}, t]

I know it is something simple but I am not able to make it work. At least now it is not giving any errors, it simply does not compute anything. It just returns the same statement.

A: Yes, it appears you have an issue with your code, you have an extra x[t] in your second equation
DSolve[{x'[t] == I*((3*w/2) x[t] + y[t]*k*E^(2 I*w*t)), y'[t] == I*(k*E^(-2*I*w*t) + 3*w*y[t]/2)}, {x[t], y[t]},t] // FullSimplify

removing this and solving gives a solution:
$\left\{\left\{x(t)\to \frac{c_1 k e^{\frac{7 i t w}{2}}}{2 w}+c_2 e^{\frac{3 i t w}{2}}+\frac{4 k^2}{21 w^2},y(t)\to c_1 e^{\frac{3 i t w}{2}}-\frac{2 k e^{-2 i t w}}{7 w}\right\}\right\}$


text:
Q: Why am I having issues with dangerouslySetInnerHTML if I return a string inside of a forEach loop? I'm pretty new to React.
Within a map function in my render, I'm providing prodID as my argument, and that value is dynamic. When I attempt to pass that value into my function and return that value (the first, commented return), it sets the innerHTML correctly to my ID's value. However, when I attempt to use that ID to actually find a different value within forEach and return that, no output is rendered.
I assume this is happening because dangerouslySetInnerHTML is re-rendering the component before the forEach has completed?
getProductNameByID(id) {
    //return {__html: id};
    this.props.products.forEach(p => {
        if (p.id === id) {
            console.log(p.title);
            return {__html: p.title};
        }
    });
}

A: Note that your return is in a fat arrow function. It does not provide a return value for getProductNameByID(). forEach() does nothing with the return value from the callback function. Instead, you should use map():
this.props.products.map(p =>

p.title

);

Note that there is no need to use dangerouslySetInnerHTML.


text:
Q: JS error as: var is not defined. How can i send value on function Now I have this code to create sitemap.xml when I run /sitemap.xml
 database = firebase.database();
    var ref = database.ref('urls');
    ref.on('value', gotData, errData);

    function errData(err){
        console.log('Error!');
        console.log(err);
    }

function gotData(data){
    result = data.val()
    return Object.keys(result)
   .filter(key => result[key].last_res > 5)
   .map(key => ({url: '/' + result[key].url_site + '/'}));
    var urls = gotData(data);
}

when i try running console.log(urls) in gotData(data) function, it returns as
{ salmon:
   { count: 1,
     last_res: 10,
     url_site: 'salmon' },
  'salmon-food':
   { count: 1,
     last_res: 601,
     url_site: 'salmon-food' } }

I need to return 'urls' in gotData(data) to create sitemap.xml.
var sitemap = sm.createSitemap({
            hostname: 'xxx.com',
            cacheTime: 600000,
            urls: urls

        });
app.get('/sitemap.xml', function(req, res) {
    sitemap.toXML( function (err, xml) {
        if (err) {
            return res.status(500).end();
        }
        res.header('Content-Type', 'application/xml');
        res.send( xml );
    });
    });
}

But now its error on var = sitemap as
urls: urls -> urls is not defined

So how can I fix it?

A: You are assigning and returning in one line. You either need to define the variable and then return it, or just return the result directly without assigning to a variable.
return Object.keys(result)
  .filter(key => result[key].last_res > 5)
  .map(key => ({url: '/' + result[key].url_site + '/'}));

It's also not clear where you are defining the urls variable that you are passing in the sm.createSitemap() function. Make sure that it exists within the scope that you are defining var sitemap.
You are likely missing a line similar to the following:
var urls = gotData(data);


text:
Q: How to use controller outside folder App\Http\Controllers in Laravel? I have a controller WebController at folder App\Web\Controllers\WebController.

WebController

<?php namespace App\Web\Controllers;

use Illuminate\Http\Request;

class WebController extends Controller
{
    public index(){
        return view('layouts.master');
    }
}

Route

Route::get('home_page','WebController@index');

When i call this route, the following error appears:

Class App\Http\Controllers\WebController does not exist

A: It has to do with the routing system.
in App\Providers\RouteServiceProvider.php you will find the map() method:
/**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapWebRoutes();
        $this->mapApiRoutes();
    }

Down that class you will find the definition for the namespace of "Web Routes"
/**
 * Define the "web" routes for the application.
 *
 * These routes all receive session state, CSRF protection, etc.
 *
 * @return void
 */
protected function mapWebRoutes()
{
    Route::middleware('web')
         ->namespace($this->namespace) // 'App\Http\Controllers'
         ->group(base_path('routes/web.php'));
}

Now you just need to change the namespace() attribute to your liking
protected function mapWebRoutes()
{
    Route::middleware('web')
         ->namespace('App\Web\Controllers')
         ->group(base_path('routes/web.php'));
}

A: class WebController extends **Controller**

There is a problem with this relationship. You have to import controller into this file. You are missing
use App\Http\Controllers\Controller

Also, you route is wrong. Try this
Route::namespace('your namespace here')->group(function () {
   Route::get('/', 'your-controller-here@your-method');
 });

Do not change the configuration of the routeserviceprovider

A: You change default namespace in RouteServiceProvider.
protected $namespace = 'App\Http\Controllers';
App\Http\Controllers is default namespace you can change it to
protected $namespace = 'App\Web\Controllers';
and then your code should work

A: I would suggest either the above code from Devetoka by using the namespace, or for only 1 or two controllers (in my case), you can simply inject the full namespace in. This is tested and works.
Route::get('home_page','\App\Web\Controllers\WebController@index');


text:
Q: Problems with Textured Quad's texture showing up black I'm trying to draw a textured quad in XNA using the sample code from MSDN http://msdn.microsoft.com/en-us/library/bb464051.aspx
but instead of drawing it on XY plane i'm drawing it in XZ plane
I initialize that quad with this
this.quad = new Quad(Vector3.Zero, Vector3.Up, Vector3.Backward, 1, 1);
I've tried almost every combination of Normal and Left vector, no matter where the quad is drawn, the quad is completely black.
what am i doing wrong here? is the texture's information lost when i'm passing it around? am i mapping the texture positions wrong?
ps: Texture, lighting are enabled.
public class Quad
{
    public VertexPositionNormalTexture[] Vertices;
    public Vector3 Origin;
    public Vector3 Up;
    public Vector3 Normal;
    public Vector3 Left;
    public Vector3 UpperLeft;
    public Vector3 UpperRight;
    public Vector3 LowerLeft;
    public Vector3 LowerRight;
    public int[] Indexes;

    public Quad(Vector3 origin, Vector3 normal, Vector3 up,
             float width, float height)
    {
            this.Vertices = new VertexPositionNormalTexture[4];
            this.Indexes = new int[6];
            this.Origin = origin;
            this.Normal = normal;
            this.Up = up;

            // Calculate the quad corners
            this.Left = Vector3.Cross(normal, this.Up);
            Vector3 uppercenter = (this.Up * height / 2) + origin;
            this.UpperLeft = uppercenter + (this.Left * width / 2);
            this.UpperRight = uppercenter - (this.Left * width / 2);
            this.LowerLeft = this.UpperLeft - (this.Up * height);
            this.LowerRight = this.UpperRight - (this.Up * height);

            this.FillVertices();
    }

    private void FillVertices()
    {
            Vector2 textureUpperLeft = new Vector2(0.0f, 0.0f);
            Vector2 textureUpperRight = new Vector2(1.0f, 0.0f);
            Vector2 textureLowerLeft = new Vector2(0.0f, 1.0f);
            Vector2 textureLowerRight = new Vector2(1.0f, 1.0f);

            for (int i = 0; i < this.Vertices.Length; i++)
            {
                    this.Vertices[i].Normal = this.Normal;
            }

            this.Vertices[0].Position = this.LowerLeft;
            this.Vertices[0].TextureCoordinate = textureLowerLeft;
            this.Vertices[1].Position = this.UpperLeft;
            this.Vertices[1].TextureCoordinate = textureUpperLeft;
            this.Vertices[2].Position = this.LowerRight;
            this.Vertices[2].TextureCoordinate = textureLowerRight;
            this.Vertices[3].Position = this.UpperRight;
            this.Vertices[3].TextureCoordinate = textureUpperRight;

            this.Indexes[0] = 0;
            this.Indexes[1] = 1;
            this.Indexes[2] = 2;
            this.Indexes[3] = 2;
            this.Indexes[4] = 1;
            this.Indexes[5] = 3;
    }
}

my draw method:
        graphicsDevice.BlendState = BlendState.AlphaBlend;

        Effect.World = Matrix.Identity;
        Effect.View = Camera.View;
        Effect.Projection = Camera.Projection;
        Effect.TextureEnabled = true;
        Effect.Texture = OilTexture;

        Effect.EnableDefaultLighting();
        Effect.PreferPerPixelLighting = true;

        foreach (EffectPass pass in oilEffect.CurrentTechnique.Passes)
        {
            pass.Apply();

            graphicsDevice.DrawUserIndexedPrimitives<VertexPositionNormalTexture>
                    (PrimitiveType.TriangleList,
                    Vertices,
                    0,
                    4,
                    Indexes,
                    0,
                    2);
        }

--i solved my problem. something went wrong when i was passing the texture2d across 3 places, now i'm drawing it from the main draw and the texture shows up fine now.

A: There are lots of reasons the quad could be black, here are a few things I like to do to debug:

*

*Turn off lightning and set on vert color to ensure the orientation of the quad is as I expected.

*User a sample texture, if possible, to ensure texture data is valid (I get a lot of issues with different versions of pipelines failing
to load textures because the formats wasn't what I expected.  DDS has
sub formats that can be tricky if you are making your own data)

*Check if the texture is visible with lightning off

*Once you flip lightning on you want to make sure you have lightning values set for all the vertices

*Try turning up the ambient value of your system to full

If none of this works look closely at the area where you are passing the vertex lightning values, the vertex normal values, and the lighting down to the hardware.


text:
Q: We couldn't connect to the catalog server for this add-n I just realized that many add-ins cannot be loaded in Excel Online (Chrome):

Does anyone know what's happening?

A: This is a known issue reported through StackOverflow and other channels. We're investigating this as a high priority issue. We'll let you know when the issue is resolved.