text:
Q: Spring REST service returns 500 servlets error I created a Service called DemandeRest.java :
    package services;

import metier.ServiceDemande;
import model.Demande;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemandeRest {
    @Autowired
    private ServiceDemande serviceDemande;

    @RequestMapping(value="/demandes", method=RequestMethod.POST )
    public void ajouter(@RequestBody Demande d) {
        serviceDemande.ajouter(d);
    }

    @RequestMapping(value="/demandes", method=RequestMethod.GET)
    public List<Demande> getAllDemande() {
        return serviceDemande.getAllDemande();
    }

}

Here is my POM
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.gestion</groupId>
  <artifactId>Gestion_Outillages</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>Gestion_Outillages</name>

  <dependencies>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations               </artifactId>
            <version>4.0.1.Final</version>
            <classifier>tests</classifier>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence                </groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager                 </artifactId>
            <version>4.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.8</version>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.1.0.CR2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.2.9.RELEASE</version>
        </dependency>

        <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.2.9.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.3.7.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.7.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>4.3.7.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>4.3.7.RELEASE</version>
</dependency>

        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-bundle</artifactId>
            <version>1.19</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20140107</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.19</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>1.8</version>
        </dependency>

        <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.0.1</version>
</dependency>
         <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

    </dependencies>
  <build>
        <finalName>SpringRestfulHelloWorldExample</finalName>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
        </plugins>

    </build>

</project>

My Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>Gestion_Outillages</display-name>
<servlet>
<servlet-name>springrest</servlet-name>
 <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
   <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/springrest-servlet.xml</param-value>
        </init-param>
  <load-on-startup>1</load-on-startup>
   </servlet>

    <servlet-mapping>
     <servlet-name>springrest</servlet-name>
      <url-pattern>/</url-pattern>
       </servlet-mapping>

</web-app>

springrest-servlet.xml :
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <mvc:annotation-driven/>
    <context:component-scan base-package="/Gestion_Outillages/src/main/java/services" />
     </beans>

The architecture : ACHI
The problem is :
I'm getting a 500 HTTP servlet error :
Etat HTTP 500 - "Servlet.init()" pour la servlet springrest a généré une exception

type Rapport d''exception

message "Servlet.init()" pour la servlet springrest a généré une exception

description Le serveur a rencontré une erreur interne qui l''a empêché de satisfaire la requête.

exception
javax.servlet.ServletException: "Servlet.init()" pour la servlet springrest a généré une exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)

cause mère
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping': Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.hasAnnotation(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/Class;)Z
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:778)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:843)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)

cause mère
java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.hasAnnotation(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/Class;)Z
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.isHandler(RequestMappingHandlerMapping.java:173)
    org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:213)
    org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:184)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:127)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:778)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:843)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)

note La trace complète de la cause mère de cette erreur est disponible dans les fichiers journaux de Apache Tomcat/9.0.0.M17.

Apache Tomcat/9.0.0.M17

Can you please help me to solve this problem : I don't know if it's a POM problem (Spring version is different from the one in Web.xml) also in springrest-servlet.xml file , in the base-package : I forgot the path of my controller com.example.services so i put the path of the folder.
Waiting for your help

A: Your versions of Spring MVC and Spring Core are inconsistent (4.3.7 vs 4.2.9).
AnnotatedElementUtils class has been added in Spring-Core 4.3.0
Switch all Spring libraries to common version.

A: I have a 404 problem , in this project , the other projects executes normally !!


text:
Q: How to store char array string to char-type pointer array? C++  //This is my logic

    int main() {
       char str1[];
       cin >> str1;
       int i = 0;
       int lengths1 = 0;
       while(str1[i] != '\0'){
       lengths1 ++;
       i++;
       }

       addString(str1, lengths1)
    }

    void addString(char str1[], int lengths1) {
       //How to store the strings to a 2d array?
}

Basically, I want to put char array strings into a 2d char array pointer to sort them.
My code will generate some char array string, and I want to store them in a 2d array whenever the string is generate, how can I do that? Thank you.

A: #include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    // if you know the number of strings beforehead, you can use an array of strings.
    std::string s1;
    std::string s2;
    std::string s3;

    //std::cin >> s1 >> s2 >> s3;

    // I'll assume these are the values.
    s1 = "cba";
    s2 = "bac";
    s3 = "abc";

    // the container that will contain the strings.
    std::vector<std::string> v;

    // to add a string to the container.
    v.push_back(s1);
    v.push_back(s2);
    v.push_back(s3);

    // use std::sort to sort the vector.
    std::sort(v.begin(), v.end());
}

I think what you want is something like this. I'd suggest that you use std::string instead of char[]. Also use std::vector instead of the normal arrays.
If you really want to use char[], you can write something like that:
#include <iostream>

void sort(char** strings, int sizeOfStrings)
{
    // some sorting algorithm.
}

int main()
{
    int numberOfStrings;
    std::cin >> numberOfStrings;

    char** strings = new char*[numberOfStrings];

    for (int i = 0; i < numberOfStrings; i++)
    {
        int lengthOfString;
        std::cin >> lengthOfString;
        // one additional character for the null terminator.
        strings[i] = new char[lengthOfString + 1];
        std::cin >> strings[i];
    }

    sort(strings, sizeOfStrings);

    for (int i = 0; i < numberOfStrings; i++)
        std::cout << strings[i] << '\n';

    // don't forget to free the allocated memory.

    for (int i = 0; i < numberOfStrings; i++)
        delete strings[i];

    delete[] strings;
}

You can choose the sorting algorithm that you need. note that since you're using char[], you'll have to use strlen to determine the size of each string, or you can store the size of the string along with the string in some way (possibly combine them in a struct).
Here is some of the sorting algorithms. This was the first search result when searching for sorting algorithms. I didn't read it and I don't know whether it's good or not.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MYSQL CSV Import - Cannot get geometry object from data you send to the GEOMETRY field I have  CSV file on my server in which the data looks as follows;
16777216,17039359,"APNIC Debogon Project"
17367040,17432575,"Tmnet, Telekom Malaysia Bhd."
17435136,17435391,"APNIC Debogon Project"
17498112,17563647,"CJ-HELLOVISION"
17563648,17825791,"Beijing Founder Broadband Network Technology Co.,L"
17825792,18087935,"Allocated to KRNIC Member."
18153984,18154239,"Double Cast"
18157056,18163711,"FAMILY NET JAPAN INCORPORATED"

I'm trying to insert this into my table which is structured as follows;
ipoid    INTEGER  11 NOT NULL PRIMARY KEY
beginip  INTEGER  14 NOT NULL UNSIGNED
endip    INTEGER  14 NOT NULL UNSIGNED
org      VARCHAR  255
ip_poly  POLYGON

I also have a spatial index created on the ip_poly field
I'm trying to insert the csv data with the following code
LOAD DATA INFILE "/home/GeoIPOrg.csv"
INTO TABLE crm_geo_org
FIELDS
TERMINATED BY ","
ENCLOSED BY "\""
LINES
TERMINATED BY "\n"
(@beginIp,@endIp,@org)
SET
ipoid      := NULL,
beginip := @beginIp,
endip   := @endIp,
ip_poly := GEOMFROMWKB(POLYGON(LINESTRING(
/* clockwise, 4 points and back to 0 */
POINT(@beginIp, -1), /* 0, top left */
POINT(@endIp,   -1), /* 1, top right */
POINT(@endIp,    1), /* 2, bottom right */
POINT(@beginIp,  1), /* 3, bottom left */
POINT(@beginIp, -1)  /* 0, back to start */
))),
org:= @org;

However when I try to do so I get this error
ERROR 1416 (22003): Cannot get geometry object from data you send to the GEOMETRY field
Any ideas?

A: In later versions of MySQL you don't need WKB/ WKT transformations to build the geometry objects.
Also, Polygon is an overkill here: MBR can be built from a single LineString just as well.
Change your ip_poly to iprange LINESTRING NOT NULL and use this:
LOAD DATA INFILE "/home/GeoIPOrg.csv"
INTO TABLE
        crm_geo_org
FIELDS
        TERMINATED BY
                ","
        ENCLOSED BY
                "\""
LINES
        TERMINATED BY "\n"
        (@beginIp, @endIp, @org)
SET     ipoid   := NULL,
        beginip := @beginIp,
        endip   := @endIp,
        iprange := GeomFromWKB(
                        LineString(
                                Point(@beginIp, -1),
                                Point(@endIp, 1)
                                )
                        ),
        org     := @org;


text:
Q: Invalid NullPointerException in Set From the Java docs of removeAll() in Set:

throws NullPointerException - if this set contains a null element and the
  specified collection does not permit null elements

If we go by the above statement, the following code should not throw a null pointer exception; however, when I run this program, I am getting one.
public class Test {
    public static void main(String[] args) {
        Set<String> s = new TreeSet<String>();
        s.add("A");
        s.add("B");
        Set<?> s1 = new HashSet<Object>();
        s1.add(null);
        s.removeAll(s1);
    }
}

Can some one tell me why I am getting an exception here?


text:
Q: Auto Build VSTS when code is pushed I have my repository on VSTS(visual studio team services). I have created steps where I can manually build from VSTS but I want to automate it:
Whenever I PUSH any code in VSTS it should auto build my code. What steps should I follow?
I have tried with the webhook trigger but it didn't work.
Tried below URL also.

A: You just need to enable the Continuous Integration in your build definition:
Edit your build definition -> Triggers Tab -> Enable continuous integration -> specify Branch Filter or Path Filter for which branch/file to trigger the CI build -> save.

A: Have a look at Continuous Integration. It's what you're looking for.

Continuous Integration
  Build every change to matching branches

You can setup your Build Definition to build each branch on a commit, or for instance only your master or develop branch.


text:
Q: How do I pass my Python script into Slurm sbatch? I have written I python script that I am meant to pass onto my University's Slurm sbatch system for computing. I have written a short shell script that is supposed to just enter the python script into the sbatch system, but I get an error that says:
python: can't open file 'retrieve.py': [Errno 2] No such file or directory
I'm not sure what to do about this even after reading a lot about the system online. The python script and shell script is located in the same folder, and my shell script just says the following for now:
#!/bin/bash

python retrieve.py

I intend to add more of the necessary information to the script file once I know it works, so I was just hoping for some help with solving this problem for now. Thanks!

A: I would guess that you are not in the wrong directory. Without additional options, the Slurm jobs uses the directory from where you submitted the job as the working directory. So if you submitted from another folder that might be a problem.
To start to debug this, you could put in an ls into your jobscript (before the python call) or do an echo $PWD to make sure you are in the correct directory.
Or even get the workdir of your job with sacct -j <JOBID> -o workdir (add -p if the path is too long and gets cut).


text:
Q: What are the benefits of using immutable samplers in Vulkan? Am I mistaken that in the case of immutable sampler it's set into the pipeline descriptor layout, whereas a non-immutable descriptor is a pointer to a sampler, and so essentially a non-immutable sampler is one extra indirection to read data from it? What kind of performance increase are we talking?

A: If there is any performance increase, it would likely be quite trivial and heavily hardware and algorithm dependent.
Vulkan is an explicit, low-level API. This allows it to better match the hardware, but it also means that you get to specify more precisely what it is that you want to do. In the vast majority of cases, the sampler you're using with a texture will be fixed for that particular use. As such, the API allows you to explicitly state this. While this can potentially allow for some hardware optimization, the main thing it allows you to do is to stop carrying around VkSampler objects when you don't need them. You specify them in the set layout, and you're done.


text:
Q: mod_fcgid, perl script output going to apache error_log I'm trying to get an old Perl script running again after installing mod_fcgid.  I had to install mod_fcgid for a new client, but it seems to have broken some of my other cgi scripts.
When going to the page, its now a 500 error.  I checked the error log, and the output from the script is in the error log... so the script is running but for some reason it still delivers a 500 Internal Server Error to the browser...
HTML headers are the first thing printed... so I'm not really sure why this error is occurring.
The Error Log:

[omitted:html output]
[Wed Dec 08 08:59:18 2010] [warn] (104)Connection reset by peer: mod_fcgid: read data from fastcgi server error.
[Wed Dec 08 08:59:18 2010] [error] [client x.x.x.x] Premature end of script headers: www_protect.cgi, referer: http://www.mywebsite.net/
[Wed Dec 08 08:59:21 2010] [notice] mod_fcgid: process /www/sites/somescript.cgi(6747) exit(communication error), terminated by calling exit(), return code: 0

fcgi.conf:

  AddHandler fcgid-script .fcgi .cgi
  #SocketPath /var/lib/apache2/fcgid/sock
  IPCConnectTimeout 45
  IPCCommTimeout 20
  OutputBufferSize 0
  MaxRequestsPerProcess 500
  IdleTimeout 3600
  ProcessLifeTime 7200
  MaxProcessCount 8
  DefaultMaxClassProcessCount 2

# Sane place to put sockets and shared memory file
SocketPath /var/run/mod_fcgid
SharememPath /var/run/mod_fcgid/fcgid_shm

A: Your configuration is telling Apache to serve all CGI scripts under FastCGI, which isn't possible. FastCGI isn't directly compatible with CGI scripts.
You should move the AddHandler directive into your client's VirtualHost, so it doesn't apply to the whole configuration, e.g.
<VirtualHost *:80>
    ServerName clienthost.com
    ...
    AddHandler fcgid-script .fcgi .cgi
</VirtualHost>

If your client's scripts are on the same VirtualHost as your other cgi scripts, you can restrict the FastCGI handling to a specific Location or Directory, e.g.
<Location /clientarea>
    AddHandler fcgid-script .fcgi .cgi
</Location>


text:
Q: Why do I need to use a pointer to a pointer in this single function and not anywhere else? I am learning about pointers and one of my professor's assignments is to write a program where main does nothing but call the other functions. The program's functions do all the work and are in this order:

*

*main: calls other functions; otherwise does almost nothing

*getSize: asks the user how many strings they want

*getSpace: gets an array in the heap of the size requested by user

*inputData: allows the user to input strings and stores them in the array

*printData: prints all the strings, one string per line

*destroy: returns all space to the heap

All these functions (besides main) must return void.
#include <iostream>
#include <string>
using namespace std;

void getSize(int *);
void getSpace(string **, int);
void inputData(string *, int);
void printData(string *, int);
void destroy(string *);

int main()
{
    int SIZE;
    string *ptrToArray;

    getSize(&SIZE);
    cout << endl;
    getSpace(&ptrToArray, SIZE);
    inputData(ptrToArray, SIZE);
    cout << endl;
    printData(ptrToArray, SIZE);
    destroy(ptrToArray);

    return 0;
}

I figured out that I had to use the address of my pointer that was going to hold the array in order to actually initialize and keep the value. What I don't get is why getSpace is the only place where I had to use a pointer to a pointer. As you can see in my prototypes, getSpace is the only function that accepts a pointer to a pointer.
void getSpace(string **ptrToptrToArray, int size)
{
    *ptrToptrToArray = new string[size];
}

Again, this code works, but I'm not sure why getSpace seems to be the only required place where I need a pointer to a pointer in order to change the array I'm pointing to, especially since inputData also changes the elements in the array.
Edit: Fixed return types from void * to void.

A: Because the pointers are passed by value.
Assume ptrToArray is a pointer variable that sits in E8 and points to some garbage location D8.
If you didn't pass it by it's address than what you would get in the get function is another variable ptrToptrToArray that sits in F8 and points to garbage D8 and when you change it's value the real pointer wouldn't change.
What you do now is store your pointer's address in the ptrToptrToArray and then change the value of the pointer that your pointer points to. (I like this sentence ;) )

A: *

*...where I need a pointer to a pointer in order to change the array I'm pointing to...

Wrong. getSpace doesn't change array, it changes the pointer. That's the diference.


text:
Q: How to set a Python codebase to use another Python codebase and package it to production? I have multiple Python codebases, 4 git repos, that use a common set of functionality that is copied in all 4 repos. When I modify one, I need to make the change in all 4 repos manually.
The repos structure is like so:
repo-1
\ src-1
\ test-1
\ other-1
\ common-code

repo-2
\ src-2
\ test-2
\ other-2
\ common-code

... (similar for repo-3 and repo-4)
Each repo conda-builds its own package and tests it agains a Docker image.
What is the right way to set these up correctly?

A: In addition to git submodule, which allows your 4 Git repositories to reference a fifth one (common), you will need, for each modification on common, to do:
cd project1
git submodule update --remote
git add .
git commit -m "update common"
git push

That way, your CI/CD can clone any of your main project with submodule (as Jenkins does, for instance)


text:
Q: How many registers does Intel® Core™ i7-3770T Processor have? I've been looking at this website: http://ark.intel.com/products/65525/Intel-Core-i7-3770T-Processor-8M-Cache-up-to-3_70-GHz
But I can't figure out the number of registers.

A: That's kind of an unusual question when evaluating an individual processor, as the number of registers is generally defined at the architectural level.
There are 16 general purpose registers in the x86-64 architecture.  Could you perhaps be more specific as to your question?


text:
Q: TinyMCE - Button to wrap selection not selecting surrounding tags In WordPress I have added a custom editor button to get the contents of a selection and wrap it in a shortcode. The content is not getting the tags surrounding the selection.
For example:

Heading text

becomes

[shortcode]Heading Text[/shortcode]

Not
[shortcode]
Heading Text
[/shortcode]

It does work for

Header

Sub-Header

becomes
[shortcode]
Header

Sub-Header
[/shortcode]

This is the code I have.
(function() {
tinymce.create('tinymce.plugins.zgwd', {
    init : function(ed, url) {
        ed.addButton('headerblock', {
            title : 'Add a Header Block',
            cmd: 'headerblock',
        });

        ed.addCommand('headerblock', function() {
            var selected_text = ed.selection.getContent({ format: 'html' });
            var return_text = '';
            if( !(selected_text && selected_text.length > 0) ) {
                selected_text = 'Add header block text here';
            }
            return_text = '[header-block]' + selected_text + '[/header-block]';
            ed.execCommand('mceInsertContent', 0, return_text);
        });

    },
    createControl : function(n, cm) {
        return null;
    },
});
tinymce.PluginManager.add('zgwd', tinymce.plugins.zgwd);
})();

How can I get the content including the
 tags (or similar). Am I using the wrong function to get the content or is there a setting I am missing somewhere? I tried .getnode() but get the same result.

A: If you want to do something with a single block tag, getNode is your best bet. If you look at this Fiddle with the console open in Dev Tools, try selecting one line, and then try selecting both. getNode() and getContent() behave a little differently based on selection.
getNode() Returns the selected element, but, if you have more than one element selected, it returns the common ancestor (in this case body).
getSelection() will return tags if you select multiple blocks, which is why it works when trying to surround more than one block tag.


text:
Q: How to register event while angularjs finish rendering UI E.g.
function SomeCtrl($scope) {
    $scope.list = [...]

    $scope.click = function() {
        var newdata = $someservice.get()
        angular.forEach(newdata, function(v){
              $scope.list.push(v)
        })
        //???
    }
}

HTML:

   ...

My question is when I add data to $scope.list, how Can I get a notify while data is updated to UI because I want the main div always scrolling to bottom?

A: try this
var module = angular.module('testApp', [])
   .directive('onFinishRender', function ($timeout) {
   return {
     restrict: 'A',
       link: function (scope, element, attr) {
        if (scope.$last === true) {
            $timeout(function () {
                scope.$emit('ngRepeatFinished');
            });
        }
    }
 }
});

Notice that I didn't use .ready() but rather wrapped it in a $timeout. $timeout makes sure it's executed when the ng-repeated elements have REALLY finished rendering (because the $timeout will execute at the end of the current digest cycle -- and it will also call $apply internally, unlike setTimeout). So after the ng-repeat has finished, we use $emit to emit an event to outer scopes (sibling and parent scopes).
And then in your controller, you can catch it with $on:
$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
    //you also get the actual event object
    //do stuff, execute functions -- whatever...
});

A: Ravi posted a great directive to listen ngRepeat finish rendering. In addition I would create another directive to autoscroll content on update. The whole code then would be something like this:
// +1 to Ravi
app.directive('onFinishRender', function($timeout) {
    return {
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished');
                });
            }
        }
    }
});

// Scroll content on every ngRepeatFinished event
app.directive('autoScroll', function() {
    return {
        link: function(scope, element) {
            scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
                element[0].scrollTop = element[0].scrollHeight;
            });
        }
    };
});

Use it in HTML:

{{row}}

Demo: http://jsfiddle.net/C5xKv/


text:
Q: Align layout in column I am using bootstrap and I am trying to create the following layout:

I tried

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

APPLE INC (AAPL)

NASDAQ

I tried flexboxes, however my layout does not arrange.
How to arrange the text next to the image?
Any suggestions what I am doing wrong?

A: You were 95% the way there. I have finished it off for you.
Really all you were missing was some nested bootstrap to make a col-10 that contains the company details sitting alongside the logo.

.name {
  font-size: 2rem;
}

.tv-symbol-icon {
  border-radius: 50%;
  width: 100%;
}

.tv-flag-country {
  margin: 0 0.5em;
  border-radius: 50%;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

APPLE INC

NASDAQ

(AAPL)


text:
Q: Converting a R2jags object into a Stanreg (rstanarm) object I made a model using R2jags. I like the jags syntax but I find the output produced by R2jags not easy to use. I recently read about the rstanarm package. It has many useful functions and is well supported by the tidybayes and bayesplot packages for easy model diagnostics and visualisation. However, I'm not a fan of the syntax used to write a model in rstanarm. Ideally, I would like to get the best of the two worlds, that is writing the model in R2jags and convert the output into a Stanreg object to use rstanarm functions.
Is that possible? If so, how?

A: I think then question isn't necessarily whether or not it's possible - I suspect it probably is.  The question really is how much time you're prepared to spend doing it.  All you'd have to do is try to replicate in structure the object that gets created by rstanarm, to the extent that it's possible with the R2jags output.  That would make it so that some post-processing tasks would probably work.
If I might be so bold, I suspect a better use of your time would be to turn the R2jags object into something that could be used with the post-processing functions you want to use.  For example, it only takes a small modification to the JAGS output to make all of the mcmc_*() plotting functions from bayesplot work.  Here's an example.  Below is the example model from the jags() function help.
# An example model file is given in:
model.file <- system.file(package="R2jags", "model", "schools.txt")

# data
J <- 8.0
y <- c(28.4,7.9,-2.8,6.8,-0.6,0.6,18.0,12.2)
sd <- c(14.9,10.2,16.3,11.0,9.4,11.4,10.4,17.6)

jags.data <- list("y","sd","J")
jags.params <- c("mu","sigma","theta")
jags.inits <- function(){
  list("mu"=rnorm(1),"sigma"=runif(1),"theta"=rnorm(J))
}

jagsfit <- jags(data=jags.data, inits=jags.inits, jags.params,
                n.iter=5000, model.file=model.file, n.chains = 2)

Now, what the mcmc_*() plotting functions from bayesplot expect is a list of matrices of MCMC draws where the column names give the name of the parameter.  By default, jags() puts all of them into a single matrix.  In the above case, there are 5000 iterations in total, with 2500 as burnin (leaving 2500 sampled) and the n.thin is set to 2 in this case (jags() has an algorithm for identifying the thinning parameter), but in any case, the jagsfit$BUGSoutput$n.keep element identifies how many iterations are kept.  In this case, it's 1250.  So you could use that to make a list of two matrices from the output.
jflist <- list(jagsfit$BUGSoutput$sims.matrix[1:jagsfit$BUGSoutput$n.keep, ],
               jagsfit$BUGSoutput$sims.matrix[(jagsfit$BUGSoutput$n.keep+1):(2*jagsfit$BUGSoutput$n.keep), ])

Now, you'd just have to call some of the plotting functions:
mcmc_trace(jflist, regex_pars="theta")

or
mcmc_areas(jflist, regex_pars="theta")

So, instead of trying to replicate all of the output that rstanarm produces, it might be a better use of your time to try to bend the jags output into a format that would be amenable to the post-processing functions you want to use.

EDIT - added possibility for pp_check() from bayesplot.
The posterior draws of y in this case are in the theta parameters.  So, we make an object that has elements y and yrep and make it of class foo
x <- list(y = y, yrep = jagsfit$BUGSoutput$sims.list$theta)
class(x) <- "foo"

We can then write a pp_check method for objects of class foo.  This come straight out of the help file for bayesplot::pp_check().
pp_check.foo <- function(object, ..., type = c("multiple", "overlaid")) {
  y <- object[["y"]]
  yrep <- object[["yrep"]]
  switch(match.arg(type),
         multiple = ppc_hist(y, yrep[1:min(8, nrow(yrep)),, drop = FALSE]),
         overlaid = ppc_dens_overlay(y, yrep[1:min(8, nrow(yrep)),, drop = FALSE]))
}

Then, just call the function:
pp_check(x, type="overlaid")


text:
Q: How to add product to cart in all storeviews? I'm using this code:
I want to add a product to every cart. When I run the code below I always get the output: The stock item for Product is not valid.
I know it somehow has to do with the way I change the stores. Because if I don't change stores, the code works fine.
include_once('../app/Mage.php');
ob_start();
umask(0);
Mage::app();

    $stores = array_keys(Mage::app()->getStores());
        foreach($stores as $storeId){
            $store = Mage::app()->getStore($storeId);
            Mage::getModel('core/store')->load($storeId);
            Mage::app()->setCurrentStore($storeId);
            Mage::getSingleton('core/session', array('name'=>'frontend'));
            $session = Mage::getSingleton('customer/session');
            try{
                $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $v[0]);
                $v[0] = $product->getId(); // fix for Mage problem with stock load id then add
                $product = Mage::getModel('catalog/product')->load($v[0]);
                $quote = Mage::getSingleton('checkout/session')->getQuote();
                $cart = Mage::getModel('checkout/cart');
                $cart->init();
                $cart->addProduct($product, array('qty' => $v[1]));
                $cart->save();
                Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
            } catch (Exception $e) {
                $eReturn = $e;
                $returnJson['success']  = false;
                $returnJson['error']    = $eReturn;
                echo $eReturn;
            }
        }

A: You can't add a product to the cart in multiple store views.
I mean, you can but that's useless. The cart is not store view dependent. It's website dependent.
When you add a product to the cart in one store view it is added for all store views under the same website.
When you add the product for the second store view under the same website, you are practically increasing the qty for the quote that corresponds to the website.
That's why you end up with a qty issue.
You should try to add the product to the cart for one store view under each website.
So instead of looping through $stores = array_keys(Mage::app()->getStores()); you can loop through $websites = Mage::app()->getWebsites();.
And for each website get any store view assigned to it.


text:
Q: How to (simulate) bonemeal with commands I would like to run a command/series of commands where I can specify an x y and z coordinate of a block and then bonemeal will be used on that block.
By used I mean:

*

*Have the same Fertilizer effects described here

*Create new plants in the same way as is described here

*If the coordinates are of a block where bonemeal cannot be used, e.g. air, the command should do nothing

I would like to be able to run this command through any method which can be achieved both manually and automated i.e. run in a command block. For instance, 3 trigger commands for x, y, and z and then a run trigger command; summoning a specific entity at the coordinates; etc...
Note: I am running 1.14.3

A: There is no "bonemeal command". You need to place a dispenser with bonemeal in it and activate it.


text:
Q: How to gloss lines in a dialogue in one example using gb4e? It should look like this:

and this does not work:
\begin{exe}
\ex\label{tomatoes}
\gll Abe: Tomaten sind Obst.\\
{} tomatoes are fruit\\
Briselotta: Are you kidding me?\\
\gll Abe: Nein, natürlich nicht.\\
{} no naturally not
\end{exe}

Speaker B's line is always fine and makes no difference whatsoever, and speaker A's second statement and intended glosses are fine yet unorderly until the second \gll command is added, making everything that follows within the example disappear in the output (incidentally indenting the entire rest of the text as the example does not end anymore).  (In fact I would be grateful for knowing how to align the sentences following the names, too, as in (1), but oh well.  And the italics I guess I can handle).

A: Found a satisfying solution using tables:
\begin{exe}
\ex
    \begin{tabular}[t]{p{1.5cm}lll}
    Abe: & \textit{Tomaten} & \textit{sind} & \textit{Obst.}\\
    & tomatoes & are & fruit\\
    \end{tabular}\\
 %
    \begin{tabular}[t]{p{1.5cm}l}
    Briselotta: & Are you kidding me?\\
    \end{tabular}\\
 %
    \begin{tabular}[t]{p{1.5cm}lll}
    Abe: & \textit{Nein,} & \textit{nat\"urlich} & \textit{nicht.}\\
    & no & naturally & not
    \end{tabular}
\end{exe}

Looks really nice:


text:
Q: How to remove AutoForm dropdown list "(Select One)" field? I'm working on a Meteor project and I am using the AutoForm package.
Now I want to remove the "(Select One)" field from the select dropdown list in my form. How can I do that?

A: You can use the firstOption attribute to specify a label, for example:
{{#autoForm id="selectForm" schema=Schemas.Select}}
     {{> afFormGroup name="favoriteYear" options=options firstOption="Please select your favorite year"}}
     <button type="submit" class="btn btn-primary">Submit</button>
{{/autoForm}}

or you can automatically select the first option (without an empty value) by setting the firstOption attribute to false:
{{#autoForm id="selectForm" schema=Schemas.Select}}
     {{> afFormGroup name="favoriteYear" options=options firstOption=false}}
     <button type="submit" class="btn btn-primary">Submit</button>
{{/autoForm}}


text:
Q: Support multiple html syntax for bold plugin in CKEditor In my application, the HTML can come from various sources and I would like to support the three following syntax for bold style :

*

*b element

*strong element

*span style='font-weight:bold' element

The two first syntax are well supported (bold command gets activated when selecting text).
The third one is properly displayed but the bold command does not recognize it (so it cannot be deactivated by the user except by using the remove format).
I tried to configure differently my CKEditor using coreStyles_bold like :
config.coreStyles_bold = { element: 'span', styles: {'font-weight':'bold'}, overrides:'b'};

OR
config.coreStyles_bold = { element: 'span', styles: {'font-weight':'bold'}, overrides:'strong'};

In this case span style='font-weight: bold' is well recognized but strong or b does not work anymore.
So the question is: how to configure CKEditor so it can support that three syntaxes at the same time?
Thanks

A:
So the question is: how to configure CKEditor so it can support that three syntaxes at the same time?

You can't configure CKEditor to allow all three tags. The coreStyles_bold setting allows specifying single tag which will override two others.
var editor = CKEDITOR.replace( 'editor1', {
    extraAllowedContent : 'span{font-weight};strong;b',
    coreStyles_bold : {
        element: 'span',
        styles: { 'font-weight': 'bold' },
        overrides : [ 'b', 'strong' ]
    }

Even if you specify overrides as empty table, other tags will still get overridden.


text:
Q: What is most efficient way to draw a single character/glyph in a given font at a given point in an android view's canvas? I have a large number of individual characters and their exact pre-computed positions in a view coordinate system, each to be drawn in one of a small number of fonts, in an android/Java canvas belong to a view.
But it appears that there's no low-level way of doing this in Java/android, like there is under iOS, where in iOS the CoreText library provides, e.g., a call:
CTFontDrawGlyphs(ctFont, allGlyphIDs[], allPos[], numGlyphs, drawingContext);

which is about as fast as possible (the glyph IDs have been precomputed by querying the font).
In android/Java, do I have to create individual text strings for each character, and then call drawText() or equivalent?  This seems like it will be very inefficient, given that in my case numGlyphs is usually in the thousands.


text:
Q: How do you check if a given input is a palindrome? I need to check if the input is a palindrome.
I converted the input to a string and compared the input with the reverse of the input using list slicing. I want to learn a different way without converting input to a string.
def palindrome(n):
   num = str(n)
   if num == num[::-1]:
      return True

A: There can be 2 more approaches to that as follows:

*

*Iterative Method: Run loop from starting to length/2 and check first character to last character of string and second to second last one and so on. If any character mismatches, the string wouldn't be palindrome.

Sample Code Below:
def isPalindrome(str):
    for i in xrange(0, len(str)/2):
        if str[i] != str[len(str)-i-1]:
            return False
    return True

*

*One Extra Variable Method: In this method, user take a character of string one by one and store in a empty variable. After storing all the character user will compare both the string and check whether it is palindrome or not.

Sample Code Below:
def isPalindrome(str):
    w = ""

    for i in str:
        w = i + w

    if (str==w):
        return True
    return False

A: Assuming that n is a number, you can get digits from right to left and build a number with those digits from left to right:
n = 3102
m = n
p = 0
while m:
     p = p*10 + m%10 # add the rightmost digit of m to the right of p
     m //= 10 # remove the rightmost digit of m

print(p) # 2013

Hence the function:
def palindrome(n):
    m = n
    p = 0
    while m:
         p = p*10 + m%10
         m //= 10
    return p == n

Note that:
if num == num[::-1]:
    return True

will return None if num != num[::-1] (end of the function). You should write:
if num == num[::-1]:
    return True
else:
    return False

Or (shorter and cleaner):
return num == num[::-1]

A: You can try the following approach:

*

*Extract all the digits from the number n

*In each iteration, append the digit to one list (digits) and at that digit at the beginning of another list (reversed_digits)

*Once all digits have been extracted, compare both lists

def palindrome(n):
    digits = []
    reversed_digits = []
    while n > 0:
        digit = n % 10
        digits.append(digit)
        reversed_digits.insert(0, digit)
        n //= 10
    return digits == reversed_digits

Note: this might not be the most efficient way to solve this problem, but I think it is very easy to understand.


text:
Q: Pulling changes for a branch from remote I'm currently working with 2 others engineers on the same branch. we're working of separate controllers(or just separate files), i'm unable to use git pull origin/<Branch> to update my branch with my teammate's commits.
Following error is shown:
fatal: 'origin/<Branch>' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

How do I pull my teammate's changes?
P.S. is it good practice for different engineer's to be working on the same branch?

A: Try git pull origin <Branch> (no /) That's the syntax shown in git-scm.com/docs/git-pull.
In case an error about "origin" persists, try git remote -v to check if the URL you mean is indeed abbreviated as "origin" or maybe has a typo.


text:
Q: ODE $y'+ x\sin( 2y) = x e^{-x^2} \cos^2 (y)$ I have the following ODE:
$$y'+ x\sin (2y) = x e^{-x^2} \cos^2 (y)$$
I'm stuck trying to get it into a linear form. I've tried $\sin (2y) = \sin y \cos y $ and then dividing the ODE by $( \cos  y ) ^{-1} $. This got me to nothing so I tried dividing by $( \sin y )^{-2} $ instead. I got stuck as well. I think I need to make a substitution but I don't know which one.
Thanks.

A: HINT
$$y'+x\sin(2y)=xe^{-x^2}\cos^2y\\\implies\sec^2y\  y' + 2x\tan y=xe^{-x^2}\ , \text{\{let $\tan y =t\implies \sec^2 y \ y'= t'$\}}\\\implies t' +2xt =xe^{-x^2}$$

A: $$y'+ x\sin( 2y) = x e^{-x^2} \cos^2 (y)$$
Multiply by $2x'$ and substitute $u=x^2$:
$$2+ 2xx'\sin( 2y) = 2xx' e^{-x^2} \cos^2 (y)$$
$$2+ u'\sin( 2y) = -( e^{-u})' \cos^2 (y)$$
$$2(\tan y)'+ 2u'\tan( y) = -( e^{-u})' $$
Multiply by $e^u$:
$$2(e^u\tan y)' = -e^u( e^{-u})' $$
$$2d(e^u\tan y) = -e^ud( e^{-u}) $$
Integrate.
$$\boxed {2e^{x^2}\tan y -x^2=C} $$

Note that you can also rewrite the DE as:
$$(e^{x^2} \tan  (y))'=x$$
And integrate.


text:
Q: Prisma + MongoDB -> Replica set Error Invalid "prisma.user.create()". Prisma needs to perform transactions, which requires your MongoDB server to be run as a replica set.
I used Nx (nx.dev) with MongoDB/Express with Prisma.

A: Apparently, after long hours of facing continuous issues in connecting Prisma and MongoDB(local), we have 3 ways of fixing this.
You have to use either Docker or MongoDB Atlas.
Docker - Docker
MongoDB Atlas - MongoDB Replica
Ps. Your MongoDB URL env should be looking like this -> mongodb://localhost:27017/<your-db-name>?retryWrites=true&w=majority.
I decided to finally choose the option 3.
Jumping from MongoDB to PostgreSQL which don't have any replica issues, but no noSQL :)

A: You can use "prisma": "2.26.0" and "@prisma/client": "2.26.0" instead of your current version. They don`t need a replica set.
Also you have to use @default(dbgenerated()) instead of @default(auto()) for this old version.


text:
Q: give name of a Variable from member of array I want give name of an variable from member of an array like below ... but it show's SyntaxError: Parse error
var nemads=new Array("akhaber","mafakher");
var nemads[i] = new stocks(nemads[i],urls[i],"");

what i can do ?

A: Kind of, like this:
var nemads=new Array("akhaber","mafakher");
var arr = {};

for (var i = 0; i < nemads.length; ++i)
{
    arr[nemads[i]] = "test" + i;
}

for (var i in arr)
{
    var item = arr[i];

    console.log(item);
}

console.log(arr["akhaber"]);

Output:
test0
test1
test0

A: you can go with eval() method also.
var arr = new Array("ab", "cd");

alert(arr[0]);    //output is ab

eval("div" + arr[0] + " = new Array('12','34')"); //this created a new var named 'divab'

alert(divab); //output is 12,34


text:
Q: IntersectsWith Error while creating game in Windows8 I'm creating a pacman game using windows 8 metro application c#.
I'm currently having some errors on the "IntersectsWith".
As shown below, I'm actually trying to make the pacman eat the pellets. Can anyone please tell me why is there an error on the code? :
Code:
        var rectPacman = pacman.GetRect(cnvMain);
        bool gotPellet = false;
        foreach (var pellet in pellets)
        {
            if (pellet.Visibility == Visibility.Visible)
            {
                var rectPellet = pellet.GetRect(cnvMain);
                var pelletCellPoint = pellet.GetCellPoint();

                if (rectPacman.IntersectsWith(rectPellet))
                {
                    gotPellet = true;

                    pellet.Visibility = Visibility.Collapsed;

                    AddPellet(pellet);
                    mazeValues[(int)pelletCellPoint.X, (int)pelletCellPoint.Y] = ' ';
                    break;
                }
            }
         }

Error showing:
'Windows.Foundation.Rect' does not contain a definition for 'IntersectsWith' and no extension method 'IntersectsWith' accepting a first argument of type 'Windows.Foundation.Rect' could be found (are you missing a using directive or an assembly reference?)

A: As stated by the compiler error, the type Windows.Foundation.Rect (http://msdn.microsoft.com/en-us/library/windows/apps/windows.foundation.rect)  has no InteresectsWith method.
System.Drawing.Rectangle (http://msdn.microsoft.com/en-us/library/system.drawing.rectangle.aspx) does, but it appears you're coding a WinRT application, the regular .Net system libraries don't apply.


text:
Q: Convert Map with Set of Strings as key to Map with Strings (Java) the question is not difficult, and I have already solved it in my own way, but I would like to hear your opinion, maybe there is some way to make this an improved option? Java 8-11.
Map<Set<String>, User> --> Map<String, User>

Imagine, that elements inside of the set are won't repeat. One more note: many unique keys can point to the same value.
I made this with the following code:
Map<String, User> result = new HashMap<>();
existingMap.forEach((set, user) -> set.forEach(item -> result.put(set, user)));

So, my question is - is there a better way to do it? I mean, maybe Stream API already has some methods to do it? in the scope of 'collect' method

A: This problem cannot be solved.
Consider the following:

*

*("Bill", "Tom", "Alice") -> User1

*("Bill", "Tom", "Jane") -> User2
This is valid for structure 1 (Map<Set<String>, User>) but invalid for structure 2 (Map<String, User>) as it will cause data loss (information about Bill and Tom will be lost).
An alternate structure you may consider is the conversion from Map<Set<String>, User> to Map<String, Set<User>>, which will not result in data degradation.
Edit: to assume data loss is acceptable as per the comments, a normal for loop solution would be:
Map<String, User> results = new HashMap<>();
for (Set<String> key : existing.keySet())
{
    User v = existing.get(key);
    for (String k : key)
    {
        results.put(k, v);
    }
}

A: If you want to use a collector, you can do a flatMap first, then toMap:
Map<String, User> result = existingMap.entrySet().stream().flatMap(
        entry -> entry.getKey().stream()
            .map(s -> Map.entry(s, entry.getValue()))
    )
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

Or if you just want to use collect only (this is more similar to your original approach):
Map<String, User> result = existingMap.entrySet().stream().collect(
    HashMap::new,
    (map, entry) -> entry.getKey().forEach(x -> map.put(x, entry.getValue())),
    HashMap::putAll
);


text:
Q: Inserting data into database using php and mysql I am currently having some troubles inserting data into my database. Everything I put in some data in my site it gives the error: 'Database Insert 1 Failed'. Moreover, when I remove the first query from the code I get the next error: 'Database Insert 2 Failed'. And so on...
What am I doing wrong? Are their any flaws in my code?
Description of my database:

*

*6 tables: user, naam, woon, sexe, jaar and hobby

*Each table has 'Lidnummer', which is set to A-I, primary key and Unique Value. It is a INTEGER with max-length 255

*Ingelogd is a BOOLEAN.

*Dag, maand and jaar are also integer with max-length 255

*Email has an Unique Value and is a char with max-length 255

*Rest of the variables are chars with max-length 255

How can I fix this? Thank you very much in advance!
Kind regards,
Ps. Code Below for those, who didn't notice ;) Also, if somebody needs some extra information, of course feel free to ask. I will provide it as well as possible.
Connect.php:
    <?php
$connection = mysqli_connect('localhost', 'root', '');
if (!$connection){
    die("Database Connection Failed" . mysql_error());
}
$select_db = mysqli_select_db($connection,'datingsite');
if (!$select_db){
    die("Database Selection Failed" . mysql_error());
}
?>

Register.php:
<?php
    Include('connect.php');

    if (isset($_POST['email']) && isset($_POST['wachtwoord'])){

        $lidnummer = NULL;
        $email = $_POST['email'];
        $wachtwoord = $_POST['wachtwoord'];
        $Ingelogd = 0;

        $Voornaam = $_POST['Voornaam'];
        $Tweedenaam = $_POST['Tweedenaam'];
        $Achternaam = $_POST['Achternaam'];

        $Woonplaats = $_POST['Woonplaats'];
        $Provincie = $_POST['Provincie'];

        $Ben = $_POST['Ben'];
        $Zoek = $_POST['Zoek'];

        $Dag = $_POST['Dag'];
        $Maand = $_POST['Maand'];
        $Jaar = $_POST['Jaar'];

        $Hobby1 = $_POST['Hobby1'];
        $Hobby2 = $_POST['Hobby2'];
        $Opleiding = $_POST['Opleiding'];

        $query = "INSERT INTO 'user' (Lidnummer, Email, Wachtwoord, Ingelogd)
        VALUES (
            '$lidnummer',
            '$email',
            '$wachtwoord',
            '$Ingelogd')";

        $query2 = "INSERT INTO  'naam' (Lidnummer, Voornaam, Tweedenaam, Achternaam)
        VALUES (
            '$lidnummer',
            '$Voornaam',
            '$Tweedenaam',
            '$Achternaam')";

        $query3 = "INSERT INTO  'woon' (Lidnummer, Woonplaats, Provincie)
        VALUES (
            '$lidnummer',
            '$Woonplaats',
            '$Provincie')";

        $query4 = "INSERT INTO  'sexe' (Lidnummer, Ben, Zoek)
        VALUES (
            '$lidnummer',
            '$Ben',
            '$Zoek')";

        $query5 = "INSERT INTO  'jaar' (Lidnummer, Dag, Maand, Jaar)
        VALUES (
            '$lidnummer',
            '$Dag',
            '$Maand',
            '$Jaar')";
        $query6 = "INSERT INTO  'hobby' (Lidnummer, Hobby1, Hobby2, Opleiding)
        VALUES (
            '$lidnummer',
            '$Hobby1',
            '$Hobby2',
            '$Opleiding')";

        $res = mysqli_query($connection, $query);
        if (!$res){
        die("Database Insert 1 Failed" . mysql_error());}

        $res2 = mysqli_query($connection, $query2);
        if (!$res2){
        die("Database Insert 2 Failed" . mysql_error());}

        $res3 = mysqli_query($connection, $query3);
        if (!$res3){
        die("Database Insert 3 Failed" . mysql_error());}

        $res4 = mysqli_query($connection, $query4);
        if (!$res4){
        die("Database Insert 4 Failed" . mysql_error());}

        $res5 = mysqli_query($connection, $query5);
        if (!$res5){
        die("Database Insert 5 Failed" . mysql_error());}

        $res6 = mysqli_query($connection, $query6);
        if (!$res6){
        die("Database Insert 6 Failed" . mysql_error());}

        if(($res)&&($res2)&&($res3)&&($res4)&&($res5)&&($res6)){
            $msg = "User Created Successfully.";
        }
    }
    ?>

<!DOCTYPE html>

<meta charset="utf-8" />

<title>Registreren op Chives</title>
<link href="../Css/inlog.css" rel="stylesheet"/>
<link href="../Css/styles.css" rel="stylesheet" />

<?php
    if(isset($msg) & !empty($msg)){
        echo $msg;
    }
 ?>

<form action="" method="post">

 Registreren

 Email:

    <input name="email" type="email" class="Input-box" required/>

 Wachtwoord:

    <input name="wachtwoord" type="password" class="Input-box"  required/>

    <fieldset class="" id="" >

Ik ben een:

                      <input type="radio" name="Ben" class="styled-radio" value="Man" required/>
                        Man

                        <input type="radio" name="Ben" class="styled-radio" value="Vrouw"/>
                        Vrouw

                </fieldset>
                <fieldset class="">

Ik zoek een:

                        <input type="radio" name="Zoek" class="styled-radio" value="Man" required/>
                        Man

                        <input type="radio" name="Zoek" class="styled-radio" value="Vrouw"/>
                        Vrouw

                        <input type="radio" name="Zoek" class="styled-radio" value="Beide"/>
                        Beide

                </fieldset>

 Woonplaats:

    <input name="Woonplaats" type="text" class="Input-box"  required/>

 Provincie:

    <input name="Provincie" type="text" class="Input-box"  required/>

 Hobby 1:

    <input name="Hobby1" type="text" class="Input-box"  required/>

 Hobby 2:

    <input name="Hobby2" type="text" class="Input-box"  required/>

 Voornaam:

    <input name="Voornaam" type="text" class="Input-box"  required/>

 Tweede naam:

    <input name="Tweedenaam" type="text" class="Input-box"  required/>

 Achternaam:

    <input name="Achternaam" type="text" class="Input-box"  required/>

 Geboortedag:

    <input name="Dag" type="Number" class="Input-box" min="0" max="31" required/>

 Geboortemaand:

    <input name="Maand" type="Number" class="Input-box" min="0" max="12" required/>

 Geboortejaar:

    <input name="Jaar" type="Number" class="Input-box" min="1920" max="2000" required/>

 Opleiding:

    <input name="Opleiding" type="Text" class="Input-box"  required/>

    <input type="submit" value="GA VERDER" class="Roundbutton" id="Login" />
</form>

A: Firstly, you're mixing APIs with mysql_error() - Use mysqli_error($connection) for all of them.
Those different APIs do not intermix with each other.
Then you're using the wrong identifiers for all your table names, being quotes.
Read up on the subject http://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
Adding or die(mysqli_error($connection)) to mysqli_query() would have signaled that.

*

*Remove the quotes from around the table names, or use ticks.

(if spaces are present, or hyphens, or a reserved keyword, then the ticks are required)
I.e.:
 $query = "INSERT INTO `user`

or remove them
 $query = "INSERT INTO user

*

*Follow the same method for all the table names in all your queries.

I must also note that your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.


text:
Q: Dynamic range Nth occurence Excel I have a table in Excel for which I would like to calculate average goals scored for n recent games with criteria being the team.
       Team         Score

         Real            4
         Real            4
         Barca           2
         Real            3
         Barca           2
         Real            3
         Barca           2

The problem is how to get the range dynamic in the averageif formula. A solution for the range could be =$B$2:ROW ( where the row() input should be e.g. the 3rd occurrence of "Real"
How can I solve this without VBA?

A: You can use this formula:
=AVERAGEIF($A$3:INDEX($A:$A,AGGREGATE(15,6,ROW($A$3:INDEX($A:$A,MATCH("ZZZ",$A:$A)))/($A$3:INDEX($A:$A,MATCH("ZZZ",$A:$A))=$D$2),E2)),$D$2,$B$3:INDEX($B:$B,AGGREGATE(15,6,ROW($A$3:INDEX($A:$A,MATCH("ZZZ",$A:$A)))/($A$3:INDEX($A:$A,MATCH("ZZZ",$A:$A))=$D$2),E2)))

It will average the score based on the two inputs, team and occurrence.

A: Append a calculation sheet, from which you read the ranges. Make those cells protected after write so it's not immediately editable by the user.


text:
Q: What do we refer to when we say algebraic structure? A set of all the operations on set $A$ is called an algebraic structure on set $A$?
Can anybody explain this statement to me.
What I understand from this is that, consider a set $\mathbb{N} $ then,
Algebraic structure on set $\mathbb{N}$ is the collection of all operators on $\mathbb{N}$ meaning,
Algebraic Structure $= \{+, \times, \cdots \} $?
I watched a couple of videos on YouTube about algebraic structure. Some of them seem to give some other different definitions of Algebraic Structures.
Can anyone explain what does it "precisely" refer to? The operator? Set of operators? The set $A$ itself?


text:
Q: Valgrind - All allocated memory freed, still Invalid free I am new to this forum as a member. My question is regarding the two versions of gcc compiler giving me different results. The gcc version 4.9.2 compiles and runs without a core dump. But, the gcc version 5.3 compiles without any warning, but on execution dumps core. I would much appreciate if someone could enlighten me on the difference. I have tried with malloc, it results in even more errors by both gcc versions. Thanks in advance. Please read below for more details.
The versions in question are
1. gcc version 4.9.2 20150212 (Red Hat 4.9.2-6) (GCC) (Fedora 21 - 3.19.5-200.fc21.i686) - Valgrind 3.10
2. gcc version 5.3.1 20151207 (Red Hat 5.3.1-2) (GCC) (Fedora 23 - 4.2.3-300.fc23.x86_64) - Valgrind 3.11
The code snippet is given below:
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>

char *somval[12][2] =
 {
  {"one", "ONE"},
  {"two", "TWO"},
  {"three", "THREE"},
  {"four", "FOUR"},
  {"five", "FIVE"},
  {"six", "SIX"},
  {"seven", "SEVEN"},
  {"eight", "EIGHT"},
  {"nine", "NINE"},
  {"ten", "TEN"},
  {NULL, NULL}
 };

typedef struct _getval
 {
  char **val1;
  char **val2;
 }GETVAL;

int main()
{
 int i;

 GETVAL *getval;
 getval = calloc(1, sizeof(GETVAL));
 getval->val1 = calloc(12, sizeof(int));
 getval->val2 = calloc(12, sizeof(int));

 for(i = 0; somval[i][1] != NULL; i++)
   {
    getval->val1[i] = calloc(101, sizeof(int));
    getval->val1[i] = somval[i][0];
    getval->val2[i] = somval[i][1];

    printf("%s = %s\n", getval->val1[i], getval->val2[i]);
   }

 for(i = 0; somval[i][1] != NULL; i++)
   {
    free(getval->val1[i]);
   }
 free(getval->val1);
 free(getval->val2);
 free(getval);

 return 0;
}

Compile the program with gcc or cc and valgrind ./a.out gives the following on gcc version 4.92. The program runs fine without a core dump and executed without valgrind.

==4818== Memcheck, a memory error detector
==4818== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==4818== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==4818== Command: ./a.out
==4818==
one = ONE
two = TWO
three = THREE
four = FOUR
five = FIVE
six = SIX
seven = SEVEN
eight = EIGHT
nine = NINE
ten = TEN
==4818== Invalid free() / delete / delete[] / realloc()
==4818==    at 0x40082CD: free (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==4818==    by 0x80485A1: main (in /users/netha/NTFiles/progs/cprog/test/a.out)
==4818==  Address 0x8048684 is not stack'd, malloc'd or (recently) free'd
==4818==
==4818==
==4818== HEAP SUMMARY:
==4818==     in use at exit: 4,040 bytes in 10 blocks
==4818==   total heap usage: 13 allocs, 13 frees, 4,144 bytes allocated
==4818==
==4818== LEAK SUMMARY:
==4818==    definitely lost: 4,040 bytes in 10 blocks
==4818==    indirectly lost: 0 bytes in 0 blocks
==4818==      possibly lost: 0 bytes in 0 blocks
==4818==    still reachable: 0 bytes in 0 blocks
==4818==         suppressed: 0 bytes in 0 blocks
==4818== Rerun with --leak-check=full to see details of leaked memory
==4818==
==4818== For counts of detected and suppressed errors, rerun with: -v
==4818== ERROR SUMMARY: 10 errors from 1 contexts (suppressed: 0 from 0)

----------------------------------------------------
Compile the program with gcc or cc and valgrind ./a.out gives the following on gcc version 5.3. The program runs fine without a core dump and executed with valgrind. Otherwise, the program dumps core without valgrind.

==29481== Memcheck, a memory error detector
==29481== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==29481== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==29481== Command: ./a.out
==29481==
one = ONE
two = TWO
three = THREE
four = FOUR
five = FIVE
six = SIX
==29481== Invalid write of size 8
==29481==    at 0x400645: main (in /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out)
==29481==  Address 0x51f60c0 is 0 bytes after a block of size 48 alloc'd
==29481==    at 0x4C2AA98: calloc (vg_replace_malloc.c:711)
==29481==    by 0x4005F0: main (in /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out)
==29481==
==29481== Invalid write of size 8
==29481==    at 0x40066E: main (in /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out)
==29481==  Address 0x51f60c0 is 0 bytes after a block of size 48 alloc'd
==29481==    at 0x4C2AA98: calloc (vg_replace_malloc.c:711)
==29481==    by 0x4005F0: main (in /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out)
==29481==
==29481== Invalid write of size 8
==29481==    at 0x400698: main (in /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out)
==29481==  Address 0x51f6130 is 0 bytes after a block of size 48 alloc'd
==29481==    at 0x4C2AA98: calloc (vg_replace_malloc.c:711)
==29481==    by 0x400609: main (in /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out)
==29481==
==29481== Invalid read of size 8
==29481==    at 0x4006B0: main (in /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out)
==29481==  Address 0x51f6130 is 0 bytes after a block of size 48 alloc'd
==29481==    at 0x4C2AA98: calloc (vg_replace_malloc.c:711)
==29481==    by 0x400609: main (in /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out)
==29481==
==29481== Invalid read of size 8
==29481==    at 0x4006C7: main (in /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out)
==29481==  Address 0x51f60c0 is 0 bytes after a block of size 48 alloc'd
==29481==    at 0x4C2AA98: calloc (vg_replace_malloc.c:711)
==29481==    by 0x4005F0: main (in /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out)
==29481==
seven = SEVEN
eight = EIGHT
nine = NINE
ten = TEN
==29481== Invalid free() / delete / delete[] / realloc()
==29481==    at 0x4C29E00: free (vg_replace_malloc.c:530)
==29481==    by 0x400722: main (in /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out)
==29481==  Address 0x400810 is in a r-x mapped file /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out segment
==29481==
==29481== Invalid read of size 8
==29481==    at 0x400718: main (in /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out)
==29481==  Address 0x51f60c0 is 0 bytes after a block of size 48 alloc'd
==29481==    at 0x4C2AA98: calloc (vg_replace_malloc.c:711)
==29481==    by 0x4005F0: main (in /XtraStorage/netha/jayami/progs/cprog/gtk_examples/a.out)
==29481==
==29481==
==29481== HEAP SUMMARY:
==29481==     in use at exit: 4,040 bytes in 10 blocks
==29481==   total heap usage: 13 allocs, 13 frees, 4,152 bytes allocated
==29481==
==29481== LEAK SUMMARY:
==29481==    definitely lost: 4,040 bytes in 10 blocks
==29481==    indirectly lost: 0 bytes in 0 blocks
==29481==      possibly lost: 0 bytes in 0 blocks
==29481==    still reachable: 0 bytes in 0 blocks
==29481==         suppressed: 0 bytes in 0 blocks
==29481== Rerun with --leak-check=full to see details of leaked memory
==29481==
==29481== For counts of detected and suppressed errors, rerun with: -v
==29481== ERROR SUMMARY: 34 errors from 7 contexts (suppressed: 0 from 0)

A: val1 and val2 are pointers but you're using sizeof(int) to allocate them. Same with *val1 and *val2.

A: Thanks for pointint it out. I have been allocating memory by sizeof(int) and none of the programs crashed until this new gcc version. I have updated the code and pasted it below with the valgrind results on gcc version 5.3. I replaced sizeof(int) with sizeof(void *)
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>

char *somval[12][2] =
 {
  {"one", "ONE"},
  {"two", "TWO"},
  {"three", "THREE"},
  {"four", "FOUR"},
  {"five", "FIVE"},
  {"six", "SIX"},
  {"seven", "SEVEN"},
  {"eight", "EIGHT"},
  {"nine", "NINE"},
  {"ten", "TEN"},
  {NULL, NULL}
 };

typedef struct _getval
 {
  char **val1;
  char **val2;
 }GETVAL;

int main()
{
 int i;

 GETVAL *getval;
 getval = calloc(1, sizeof(GETVAL));
 getval->val1 = calloc(12, sizeof(void *));
 getval->val2 = calloc(12, sizeof(void *));

 for(i = 0; somval[i][1] != NULL; i++)
   {
    getval->val1[i] = somval[i][0];
    getval->val2[i] = somval[i][1];

    printf("%s = %s\n", getval->val1[i], getval->val2[i]);
   }

 free(getval->val1);
 free(getval->val2);
 free(getval);

 return 0;
}

-------------------------------------------
Compile with cc or gcc and ran with valgrind gave the below result. Without valgrind the program did not dump core.

==31006== Memcheck, a memory error detector
==31006== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==31006== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==31006== Command: ./a.out
==31006==
one = ONE
two = TWO
three = THREE
four = FOUR
five = FIVE
six = SIX
seven = SEVEN
eight = EIGHT
nine = NINE
ten = TEN
==31006==
==31006== HEAP SUMMARY:
==31006==     in use at exit: 0 bytes in 0 blocks
==31006==   total heap usage: 3 allocs, 3 frees, 208 bytes allocated
==31006==
==31006== All heap blocks were freed -- no leaks are possible
==31006==
==31006== For counts of detected and suppressed errors, rerun with: -v
==31006== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)


text:
Q: Getting User Input for Yahoo Pipes Script I'm a bit of a noob at some of this so I was wondering if someone could help with what I hope is a simple question.
I've developed a Yahoo Pipe that takes as Input the name of a Label(s). This then should run the yahoo pipe to generate the output.
Below is a snippet of code that is generated when I run the the Yahoo Pipe from the Yahoo Pipes page.
Now my question is I want to run this pipe from my own site and get the user to Input the labels they want rather than having them leave the site and go to the Yahoo Pipes page.
<script src="http://l.yimg.com/a/i/us/pps/listbadge_1.4.js">{"pipe_id":"6c3a35f3d8e3cdb8ef270a3565d64ca3","_btype":"list","pipe_params":{"tags":"Cooking Beef Chicken"},"width":"600","height":"500"}</script>

I'd like to have a simple Form that the user fills out and for the code to generate the above script code from their input and execute.
I hope I've explained this as it's a little confusing.
To sum up, how do I get input from a user on a web page about which Labels they want to run the pipe against and for it to generate the correct code and execute.

A: It's a three part trick if you use a server side script
Information is sent from a regular form back to the page it comes from and that is extracted from the url like so
enter <?php $userInput    = $_GET["userInput"]); ?>here

Now the userInput can be written into a javascript src URL that makes the cross domain call to the pipe.
enter <script src="http://pipes.yahoo.com/pipes/pipe.run?_id=050fc8ccfefd18420680a86ebf4bf80e&_render=json&_callback=cbfunc&town=<?php echo $userInput; ?>"></script> here

When the pipe returns the data it wraps a 'callback' tag around it, in this case called cbfunc and this is used to trigger a javascript routine in the page head that extracts data the JSON string for you to do what you want with it.
enter function cbfunc(data){
    var data     = (data.value.items[0].content)
                } here

You can see a working example of this in action at http://bishop-test.appspot.com/ when you click on the map search. This link is also helpful for examaning the JSON output http://braincast.nl/samples/jsoneditor/


text:
Q: How to access MATLAB installed on a server? A pretty basic question. The MATLAB is installed on a linux based server. I have windows 7 installed on my system. I want to access MATLAB, how do i do that?
Shall i install some virtual machine or is there a simpler way? Please help.
Thanks.

A: MATLAB will run on Windows 7, so you could just install it on your Win7 machine. The other more complicated route would be to run a VNC client on the Win7 box and a matching server on the Linux side. Then you can have access to the remote linux desktop from Win7.
Reference here.


text:
Q: Breadcrumbs  wrapped in
* not clickable nextjs I am using this blog as a reference as I implement breadcrumbs for a nextjs app. Everything works well except the breadcrumbs are not clickable. I would like the user to be able to click on a breadcrumb and be redirected to its path.
My assumption is that wrapping the link in li tags is what brings this issue but am not sure why. Will appreciate a third eye
components/BreadrumbItem.jsx
import Link from "next/link";

const BreadcrumbItem = ({ children, href, ...props }) => {

  return (

      <Link href={href} passHref>

          {children}

      </Link>

  );
};

export default BreadcrumbItem;

components/Breadcrumb.jsx
import { Children } from "react";
import { Fragment } from "react";

const Breadcrumb = ({ children }) => {
  const childrenArray = Children.toArray(children);

  const childrenWtihSeperator = childrenArray.map((child, index) => {
    if (index !== childrenArray.length - 1) {
      return (
        <Fragment key={index}>
          {child}
          {">"}
        </Fragment>
      );
    }
    return child;
  });

  return (

{childrenWtihSeperator}

  );
};

export default Breadcrumb;

components/layout.tsx
const Layout = ({ children }: Props) => {

  const router = useRouter();

  const [breadcrumbs, setBreadcrumbs] = useState();

  useEffect(() => {
    const pathWithoutQuery = router.asPath.split("?")[0];
    let pathArray = pathWithoutQuery.split("/");
    pathArray.shift();

    pathArray = pathArray.filter((path) => path !== "");

    const breadcrumbs = pathArray.map((path, index) => {
      const href = "/" + pathArray.slice(0, index + 1).join("/");
      return {
        href,
        label: path.charAt(0).toUpperCase() + path.slice(1),
        isCurrent: index === pathArray.length - 1,
      };
    });
//@ts-ignore
    setBreadcrumbs(breadcrumbs);
  }, [router.asPath]);

  return (
    <>
     <Breadcrumb>
        <BreadcrumbItem isCurrent={router.pathname === "/"} href="/">
          Home
        </BreadcrumbItem>
        {breadcrumbs &&
        //@ts-ignore
          breadcrumbs.map((breadcrumb) => (
            <BreadcrumbItem
              key={breadcrumb.href}
              href={breadcrumb.href}
              isCurrent={breadcrumb.isCurrent}
            >
              {breadcrumb.label}
            </BreadcrumbItem>
          ))}
      </Breadcrumb>
    </>
  )
}

export default Layout;


text:
Q: calculate combination in C# without recursive function i would like to calculate all the combination possible, but i don't want to use recursive function just some simple code in C# ?
Here is example :
                     col1     col2   col3
       valueinf=      5        6      7
       valuesup=     10       20     30

i want this for result:
        res1 = 5+6+7
        res2 = 5+6+30
        res3 = 5+20+7
        res4 = 5+20+30
        res5 = 10+6+7
        res6 = 10+6+30
        res7 = 10+20+7
        res8 = 10+20+30

the number of colonne is variable but i wil allways have 2 lines one inferior and one superior.
I don't know how to begin the algorithm. Some help will be gratefull just to begin

A: Well, will-nilly you have to loop:
using System.Linq;

...

private static IEnumerable<int> Sums(IEnumerable<int[]> columns) {
  if (columns is null)
    throw new ArgumentNullException(nameof(columns));

  int[][] data = columns.ToArray();
  int[] pos = new int[data.Length];

  do {
    yield return Enumerable.Range(0, data.Length).Sum(i => data[i][pos[i]]);

    for (int i = pos.Length - 1; i >= 0; --i)
      if (pos[i] == data[i].Length - 1)
        pos[i] = 0;
      else {
        pos[i] += 1;

        break;
      }
  }
  while (!pos.All(p => p == 0));
}

The very same idea if you want to print formulae:
private static IEnumerable<string> Formulae(IEnumerable<int[]> columns) {
  if (columns is null)
    throw new ArgumentNullException(nameof(columns));

  int[][] data = columns.ToArray();
  int[] pos = new int[data.Length];

  do {
    yield return string.Join("+", Enumerable
      .Range(0, data.Length).Select(i => data[i][pos[i]]));

    for (int i = pos.Length - 1; i >= 0; --i)
      if (pos[i] == data[i].Length - 1)
        pos[i] = 0;
      else {
        pos[i] += 1;

        break;
      }
  }
  while (!pos.All(p => p == 0));
}

Demo:
List<int[]> columns = new List<int[]>() {
  new int[] {5, 10},
  new int[] {6, 20},
  new int[] {7, 30},
};

var sums = Sums(columns);
var formulae = Formulae(columns);

Console.WriteLine(string.Join(Environment.NewLine, sums
  .Select((v, i) => $"res{i+1} = {v}")));

Console.WriteLine();

Console.WriteLine(string.Join(Environment.NewLine, formulae
  .Select((v, i) => $"res{i+1} = {v}")));

Outcome:
res1 = 18
res2 = 41
res3 = 32
res4 = 55
res5 = 23
res6 = 46
res7 = 37
res8 = 60

res1 = 5+6+7
res2 = 5+6+30
res3 = 5+20+7
res4 = 5+20+30
res5 = 10+6+7
res6 = 10+6+30
res7 = 10+20+7
res8 = 10+20+30

Edit: To find the best fit you can exploit the very same principle:
private static (int[] pos, int diff, string formula) BestFit(int target, IEnumerable<int[]> columns) {
  if (columns is null)
    throw new ArgumentNullException(nameof(columns));

  int[][] data = columns.ToArray();
  int[] pos = new int[data.Length];

  int bestDiff = -1;
  int[] bestPos = null;

  do {
    int diff = Math.Abs(target - Enumerable.Range(0, data.Length).Sum(i => data[i][pos[i]]));

    if (diff < bestDiff || bestPos == null) {
      bestPos = pos.ToArray();
      bestDiff = diff;
    }

    for (int i = pos.Length - 1; i >= 0; --i)
      if (pos[i] == data[i].Length - 1)
        pos[i] = 0;
      else {
        pos[i] += 1;

        break;
      }
  }
  while (!pos.All(p => p == 0));

  return (
    bestPos,
    bestDiff,
    string.Join("+", Enumerable.Range(0, data.Length).Select(i => data[i][bestPos[i]]))
  );
}

Demo:
  int[][] data = new int[][] {
    new int[] {5, 10},
    new int[] {6, 20},
    new int[] {7, 30},
  };

  var fit = BestFit(20, data);

  Console.Write($"delta = {fit.diff}; formula = {fit.formula}");

Outcome:
  delta = 2; formula = 5+6+7


text:
Q: Calculate number of distinct instances occurring in a given time period I have dummy data
structure(list(id = c(1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 6, 7, 7,
7), policy_num = c(41551662L, 50966414L, 43077202L, 46927463L,
57130236L, 57050065L, 26196559L, 33545119L, 52304024L, 73953064L,
50340507L, 50491162L, 76577511L, 108067534L), product = c("apple",
"apple", "pear", "apple", "apple", "apple", "plum", "apple",
"pear", "apple", "apple", "apple", "pear", "pear"), start_date =
structure(c(13607, 15434, 14276, 15294, 15660, 15660, 10547, 15117, 15483,
16351, 15429, 15421, 16474, 17205), class = "Date"), end_date = structure(c(15068,
16164, 17563, 15660, 15660, 16390, 13834, 16234, 17674, 17447,
15794, 15786, 17205, 17570), class = "Date")), .Names = c("id",
"policy_num", "product", "start_date", "end_date"), row.names = c(NA,
-14L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x0000000000320788>)

id policy_num product start_date   end_date
 1   41551662   apple 2007-04-04 2011-04-04
 1   50966414   apple 2012-04-04 2014-04-04
 2   43077202    pear 2009-02-01 2018-02-01
 3   46927463   apple 2011-11-16 2012-11-16
 3   57130236   apple 2012-11-16 2012-11-16
 3   57050065   apple 2012-11-16 2014-11-16
 4   26196559    plum 1998-11-17 2007-11-17
 5   33545119   apple 2011-05-23 2014-06-13
 5   52304024    pear 2012-05-23 2018-05-23
 5   73953064   apple 2014-10-08 2017-10-08
 6   50340507   apple 2012-03-30 2013-03-30
 7   50491162   apple 2012-03-22 2013-03-22
 7   76577511    pear 2015-02-08 2017-02-08
 7  108067534    pear 2017-02-08 2018-02-08

Based on it, I'd like to calculate the following variables (grouped by user_id):
1) Number of currently held product (no_prod_now) - number of distinct products, whose end_date > currently evaluated start_date. Simply, number of products held by user_id at the time of start_date
2) Number of currently held active policies (no_policies_now) - as above, but applied to policy_num
3) Number of policies opened within 3 months prior the current start_date (policies_open_3mo)
4) policies_closed_3mo - as above, but number of closed policies in the past 3 months
The desirable output would look like this:
 id policy_num product start_date   end_date no_prod_now no_policies_now policies_closed_3mo
  1   41551662   apple 2007-04-04 2011-04-04           1               1                   0
  1   50966414   apple 2012-04-04 2014-04-04           1               1                   0
  2   43077202    pear 2009-02-01 2018-02-01           1               1                   0
  3   46927463   apple 2011-11-16 2012-11-16           1               1                   0
  3   57130236   apple 2012-11-16 2012-11-16           1               1                   1
  3   57050065   apple 2012-11-16 2014-11-16           1               1                   2
  4   26196559    plum 1998-11-17 2007-11-17           1               1                   0
  5   33545119   apple 2011-05-23 2014-06-13           1               1                   0
  5   52304024    pear 2012-05-23 2018-05-23           2               2                   0
  5   73953064   apple 2014-10-08 2017-10-08           2               2                   0
  6   50340507   apple 2012-03-30 2013-03-30           1               1                   0
  7   50491162   apple 2012-03-22 2013-03-22           1               1                   0
  7   76577511    pear 2015-02-08 2017-02-08           1               1                   0
  7  108067534    pear 2017-02-08 2018-02-08           1               1                   1
policies_open_3mo
                0
                0
                0
                0
                0
                1
                0
                0
                1
                0
                0
                0
                0
                0

I'm looking for the solution implemented ideally in data.table, as I'm going to apply it to big data volumes, but base R or dplyr solutions I could always convert to data.table, o would be also valuable, thanks!

A: This is quite tricky but can be solved with a number of non-equi self-joins.
Edit: It has turned out that update on join doesn't work together with non-equi self-joins as I had expected (see here). So, I had to revise the code completely to avoid updates in place.
Instead, the four additional columns are created by three separate non-equi self-joins and are combined for the final result.
library(data.table)
library(lubridate)

result <-
  # create helper column for previous three months periods.
  # lubridate's month arithmetic avoids NAs at end of month, e.g., February
  DT[, start_date_3mo := start_date %m-% period(month = 3L)][
    # start "cbind()" with original columns
  , c(.SD,
      # count number of products and policies held at time of start_date
      DT[DT, on = c("id", "start_date<=start_date", "end_date>start_date"),
         .(no_prod_now = uniqueN(product), no_pols_now = uniqueN(policy_num)),
         by = .EACHI][, c("no_prod_now", "no_pols_now")],
      # policies closed within previous 3 months of start_date
      DT[DT, on = c("id", "end_date>=start_date_3mo", "end_date<=start_date"),
         .(pols_closed_3mo = .N), by = .EACHI][, "pols_closed_3mo"],
      # additional policies opened within previous 3 months of start_date
      DT[DT, on = c("id", "start_date>=start_date_3mo", "start_date<=start_date"),
         .(pols_opened_3mo = .N - 1L), by = .EACHI][, "pols_opened_3mo"])][
           # omit helper column
           , -"start_date_3mo"]
result

    id policy_num product start_date   end_date no_prod_now no_pols_now pols_closed_3mo pols_opened_3mo
 1:  1   41551662   apple 2007-04-04 2011-04-04           1           1               0               0
 2:  1   50966414   apple 2012-04-04 2014-04-04           1           1               0               0
 3:  2   43077202    pear 2009-02-01 2018-02-01           1           1               0               0
 4:  3   46927463   apple 2011-11-16 2012-11-16           1           1               0               0
 5:  3   57130236   apple 2012-11-16 2012-11-16           1           1               2               1
 6:  3   57050065   apple 2012-11-16 2014-11-16           1           1               2               1
 7:  4   26196559    plum 1998-11-17 2007-11-17           1           1               0               0
 8:  5   33545119   apple 2011-05-23 2014-06-13           1           1               0               0
 9:  5   52304024    pear 2012-05-23 2018-05-23           2           2               0               0
10:  5   73953064   apple 2014-10-08 2017-10-08           2           2               0               0
11:  6   50340507   apple 2012-03-30 2013-03-30           1           1               0               0
12:  7   50491162   apple 2012-03-22 2013-03-22           1           1               0               0
13:  7   76577511    pear 2015-02-08 2017-02-08           1           1               0               0
14:  7  108067534    pear 2017-02-08 2018-02-08           1           1               1               0

Note that there are discrepancies for policies opened within 3 previous months before start_date between OP's expected result and the result here. For id == 3, there are 2 policies starting both on 2012-11-16, so it's one additional policy to count for each row. For id == 5, all start_date differ by more than 3 months, so there shouldn't be an overlap.
Also, rows 5 and 6 both show a value of 2 for policies closed within 3 previous months before start_date because id == 3 has two policies ending on 2012-11-16.


text:
Q: How to add Ship To address to an existing customer? I am using the QuickBooks PHP DevKit. I tried the xml below but it only replaces the existing ship to address
<?xml version="1.0" encoding="utf-8"?>
    <?qbxml version="2.0"?>
    <QBXML>
        <QBXMLMsgsRq onError="stopOnError">
            <CustomerModRq requestID="IDhere">
                <CustomerMod>
                    <ListID>123456</ListID>
                        <EditSequence>1424079129</EditSequence>
                        <ShipAddress>
                            <Addr1>Line 1 here</Addr1>
                            <Addr2>Line 2 here</Addr2>
                            <City>City</City>
                            <State>Province</State>
                            <PostalCode>1223</PostalCode>
                            <Country>Philippines</Country>
                        </ShipAddress>
                </CustomerMod>
            </CustomerModRq>
        </QBXMLMsgsRq>
    </QBXML>

I also tried adding the original ship address to (2  tags) but to no avail.
Thanks!

A: Did you refer to the QuickBooks OSR documentation?

*

*https://developer-static.intuit.com/qbSDK-current/Common/newOSR/index.html
If you refer to the docs, you'll see a tag to send multiple shipping addresses exists, called ShipToAddress:
<!-- must occur 0 - 50 times -->
<ShipToAddress>
  <Name >STRTYPE</Name> <!-- required -->
  <Addr1 >STRTYPE</Addr1> <!-- optional -->
  <Addr2 >STRTYPE</Addr2> <!-- optional -->
  <Addr3 >STRTYPE</Addr3> <!-- optional -->
  <Addr4 >STRTYPE</Addr4> <!-- optional -->
  <Addr5 >STRTYPE</Addr5> <!-- optional -->
  <City >STRTYPE</City> <!-- optional -->
  <State >STRTYPE</State> <!-- optional -->
  <PostalCode >STRTYPE</PostalCode> <!-- optional -->
  <Country >STRTYPE</Country> <!-- optional -->
  <Note >STRTYPE</Note> <!-- optional -->
  <DefaultShipTo >BOOLTYPE</DefaultShipTo> <!-- optional -->
</ShipToAddress>

Note that only some versions of QuickBooks support this (at a minimum you must have QuickBooks 2013 or newer to use this -- and even then only some editions of QuickBooks will have been updated to support this functionality -- it was added as a placeholder in the docs prior to the software actually supporting it).