text:
Q: How to use RestTemplate in Spring Boot application in multithreaded environment? I am having a problem in my Spring Boot application where I am using a RestTemplate which is autowired for making POST calls to a REST service. The code where I am initializing the REstTemplate bean is as follows:
@Bean(name = "template")
public RestTemplate restTemplate(RestTemplateBuilder builder) throws NoSuchAlgorithmException, KeyManagementException {

    TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] certs, String authType) {
                }
                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] certs, String authType) {
                }
            }
    };
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();

    // Conn Pool
            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
                    RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier))
                    .build());
            cm.setMaxTotal(Integer.MAX_VALUE);
            cm.setDefaultMaxPerRoute(50);

    CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLContext(sslContext)
            .setConnectionManager(cm)
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .build();
    HttpComponentsClientHttpRequestFactory customRequestFactory = new HttpComponentsClientHttpRequestFactory();
    customRequestFactory.setHttpClient(httpClient);
    return builder.requestFactory(() -> customRequestFactory).build();
}

The RestTemplate is then autowired:
@Autowired
@Qualifier("template")
private RestTemplate restTemplate;

And the RestTemplate is used thus:
restResponse = restTemplate.postForObject(targetUrl, obj, CustomRestResponse.class);

I am deploying the application to PCF where it is running with 6 instances. It's then giving me an error like this:
org.springframework.web.client.RestClientException: Error while extracting response for type [class com.test.model.CustomRestResponse] and content type [application/json;charset=UTF-8]; nested exception is org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected

To replicate the issue in my local environment, I created a multithreaded application which will spawn multiple threads and call the REST service simultaneously:
ExecutorService service = Executors.newFixedThreadPool(10);
    IntStream.range(0, 100).forEach(i -> service.submit(new RestTemplateTesterRunnable(i)));

And I was able to get the exception in my local system as well (Note that I don't have this multithreading code in the actual application. This is just for replicating the problem in my local since I can't run 6 instances automatically). The full stacktrace is as follows:
org.springframework.web.client.RestClientException: Error while extracting response for type [class com.test.model.CustomRestResponse] and content type [application/json;charset=UTF-8]; nested exception is org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:119)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:744)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:677)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:421)
at com.test.RestTemplateTester$RestTemplateTesterRunnable.run(RestTemplateTester.java:237)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected
at org.apache.http.impl.io.ChunkedInputStream.getChunkSize(ChunkedInputStream.java:263)
at org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream.java:222)
at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:183)
at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:210)
at org.apache.http.impl.io.ChunkedInputStream.close(ChunkedInputStream.java:312)
at org.apache.http.impl.execchain.ResponseEntityProxy.streamClosed(ResponseEntityProxy.java:142)
at org.apache.http.conn.EofSensorInputStream.checkClose(EofSensorInputStream.java:228)
at org.apache.http.conn.EofSensorInputStream.close(EofSensorInputStream.java:172)
at java.io.PushbackInputStream.close(PushbackInputStream.java:379)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._closeInput(UTF8StreamJsonParser.java:252)
at com.fasterxml.jackson.core.base.ParserBase.close(ParserBase.java:369)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4210)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3258)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:239)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:227)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:104)
... 9 more

However, I am not being able to solve the problem. I referred this question:
How to efficiently use RestTemplate in multithreading application?
and this one:
How to use RestTemplate efficiently in Multithreaded environment?
and in both of them, people are saying that RestTemplate is thread-safe and there shouldn't be a problem in using it in a multithreaded environment. However, what I am seeing is that this exception is still happening for me. I thought at first that this was happening due to my use of the CloseableHttpClient, as is given by this post:
ConnectionClosedException: Premature end of chunk coded message body with apache hhtpclient 4.5.5
However, as I am not directly using the client, which is internally used by Spring Boot, I didn't have much to do about it. But I looked into the internal working of the RestTemplate's postForObject() method in any case, which led me to this method:
@Nullable
protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback,
        @Nullable ResponseExtractor<T> responseExtractor) throws RestClientException {

    Assert.notNull(url, "URI is required");
    Assert.notNull(method, "HttpMethod is required");
    ClientHttpResponse response = null;
    try {
        ClientHttpRequest request = createRequest(url, method);
        if (requestCallback != null) {
            requestCallback.doWithRequest(request);
        }
        response = request.execute();
        handleResponse(url, method, response);
        return (responseExtractor != null ? responseExtractor.extractData(response) : null);
    }
    catch (IOException ex) {
        String resource = url.toString();
        String query = url.getRawQuery();
        resource = (query != null ? resource.substring(0, resource.indexOf('?')) : resource);
        throw new ResourceAccessException("I/O error on " + method.name() +
                " request for \"" + resource + "\": " + ex.getMessage(), ex);
    }
    finally {
        if (response != null) {
            response.close();
        }
    }
}

I am seeing that before returning, the response object is being closed, as was being told in the previous StackOverflow post I linked. Can this be the reason for the ConnectionClosedException in a multithreaded environment? If so, what is the solution? I tried to use evictIdleConnections() as given by the Javadocs:
https://hc.apache.org/httpcomponents-client-4.5.x/current/httpclient/apidocs/org/apache/http/impl/client/HttpClientBuilder.html#evictIdleConnections(long,%20java.util.concurrent.TimeUnit)
So the code became:
CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLContext(sslContext)
            .setConnectionManager(cm)
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .evictIdleConnections(10, TimeUnit.MILLISECONDS)
            .build();

However, this didn't help. I also saw that some people are using org.apache.commons.httpclient.MultiThreadedHttpConnectionManager, but I found that this is a deprecated connection manager, and the HttpComponentsClientHttpRequestFactory does not support it. Nevertheless, I somehow used it also, but with no results. Please hellp me in getting the actual reason for this exception, and how to resolve it.


text:
Q: Error deploying Django, unable to configure static files I tried deploying Django project to www.pythonanywhere.com, My website ran but could not load static files.
I did collectstatic command in hosting server console but got error.
my project file configuration as follows
myproject # parent directory
-DjangoApp1 # an app inside project
-Myproject main file(includes manage.py etc)
-DjangoApp2 # an app inside project
-DjangoApp3 (in this app my static files located `DjangoApp3/static/DjangoApp3` )

in settings.py file
STATIC_ROOT = os.path.join(BASE_DIR, "/static/")
STATICFILES_DIRS = ('/DjangoApp3/static/DjangoApp3/',)
STATIC_URL = '/static/'

when I run collectstatic method in local machine ,below error occured
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\DjangoApp3\\static'

A: This works
STATIC_ROOT = os.path.join(BASE_DIR, "/static/")
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'staticfiles'),)
STATIC_URL = '/static/'

I've covered the three in an answer here before

A: Try this:
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    (os.path.join(BASE_DIR, 'static')),
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Subversion: force users to update before commit How can we force users that are using TortoiseSVN to "Update" their branch before they can "Commit"?
We ran into this issue earlier today:

*

*Joe commits to Branch1, revision 101

*Bob downloads Branch1 and then commits to Branch1, revision 102

*Joe commits to Branch1, revision 103... and SVN never told him "You must update before you can Commit" as typically happens

Also:

*

*Joe was working in /svnrepo/ProjectXYZ/branches/Branch1/DirectoryA/

*Bob was working in /svnrepo/ProjectXYZ/branches/Branch1/DirectoryB/

Any ideas on reasons/ways SVN will skip this step of not making the user update first?

A: I suspected that once Bob made changes only in DirectoryB, then he made a commit from DirectoryB level, not from root level.
That means that none of files modified earlier by Joe, where affected by Bob's commit.
In other words all files modified by Bob where up to date, so no update was required.
I see 2 possible solutions:
1) make everyone commit from root level - i.e. "/svnrepo/ProjectXYZ/branches/Branch1" in that case
2) write a svn pre-commit hook http://svnbook.red-bean.com/en/1.7/svn.ref.reposhooks.pre-commit.html
** A little bit longer explanation of what I mean by commiting from levels, and why this matters in this case.
So lets say that Joe commited from root level
cd /svnrepo/ProjectXYZ/branches/Branch1
svn commit DirectoryA/Hello.java

Then what svn registered as modified were Branch1 directory, DirectoryA directory and Hello.java file
And then Bob commited from DirectoryB level
cd /svnrepo/ProjectXYZ/branches/Branch1/DirectoryB
svn commit Hello2.java

Then svn registered only DirectoryB and file Hello2.java as being changed.
As you can see there is no common part of these to sets of changes, so no update was required.


text:
Q: How to parse jquery.sheet's JSON in Java? I am using jquery.sheet plugin which accepts JSON. The JSON format is:
[
    { //repeats
        metadata: {
            columns: Column_Count,
            rows: Row_Count,
            title: ''
        },
        data: {
            r{Row_Index}: { //repeats
                c{Column_Index}: { //repeats
                    value: '',
                    style: '',
                    width: 0,
                    cl: {Classes used for styling}
                }
            }
        }
    }
];

A simple example may be:
[
    {
        metadata: {
            columns: 1,
            rows: 1,
            title: 'Private Limited'
        },
        data: {
            r0: {
                c0: {
                    value: 'A',
                    style: '',
                    width: 0
                }
            }
        }
    }
]

I need to parse this JSON in Java? I know I can use the google's gson library to parse. But I don't know how to do this.

A: Strictly speaking the sample you are referring to is not a valid JSON, e.g. it lacks "" around field ids as metadata [according to JSON defined in www.json.org][http://json.org/]
For this reason I would recommend that before you pass it to your Java (e.g. servlet) you should stringify this object, e.g. as shown in this answer. This way you are sure that this is a valid JSON. Later use jQuery to send it to servlet. There in your Java code you use the below code to get your json String turned into JSONArray on which you will operate further.
String json = request.getParameter(param);
JSONArray jsonArray = new JSONArray(json);

Then you can iterate over its elements as if it was any other collection.
for (int i = 0; i < jsonArray.length(); i++) {
   JSONObject jsonObject = jsonArray.getJSONObject(i);
   //work with the jsonObject
}

The JSONArray and JSONObject classes are taken from here.
The jar for the library is availalbe here.
You could use gson if you like. Though in this particular case this library is more then enough. I personally use gson if I have a bean object for a corresponding JSON String, otherwise json.org is more than enough.


text:
Q: Pymongo invalid syntax near $gte I am using Pymongo. I have successfully connected to my MongoDB. Collection name is test_collection. In the document, there is a key called request_time . I am trying to fetch the documents in a specific range of request_time.
In the mongodb shell, this command works,
db.getCollection('test_collection').find({ request_time: { $gte: new Date('2018-06-22'), $lt: new Date('2018-06-26') }});

But, when I am using pymongo. It is not accepting $ and giving syntax error.
collection = db['test_collection']

cursor = collection.find({request_time: { $gte: new Date('2018-06-22'), $lt: new Date('2018-06-26') }})

A: You write commands in Javascript in mongo shell, don't copy-paste them into python.
Python is not Javascript.
Python does not have neither new nor builtin Date type.
find method of the pymongo.collection.Collection class expects dictionary with string keys, put keys in quotes.
Use datetime.datetime if respective fields in documents from the mongo collection are ISODates.
import datetime
cursor = collection.find({"request_time": {
                          "$gte": datetime.datetime(2018, 6, 22),
                          "$lt": datetime.datetime(2018, 6, 26) }
                         })

A: Try put brasket in each condition
({ { $gte: new Date('2018-06-22') }, { $lt: new Date('2018-06-26') } })

A: Use '$gt' and '$lt' in code.
cursor = collection.find({request_time: { '$gte': new Date('2018-06-22'), '$lt': new Date('2018-06-26') }})


text:
Q: angularJS login connect to API backend I've found alot of text explaining this but i haven't quite found what i'm looking for. I'm hoping someone can point me in the right direction. I am building an Angular App that communicates with a RoR back-end. On the back-end there is a basic authentication with username and password. For the moment i've hardcoded the username and password into my app.js. I'm using Restangular so i set it up like so:
 var authenticationToken = btoa('username,password');

.config(function (RestangularProvider) {
  RestangularProvider.setDefaultHeaders({Authorization: 'Basic ' + authenticationToken});
}

But what I would like is for users to have to login when they open the app with username and password. So that my app can use those to send requests to the backend. I have no real idea how to set this up properly.
update
I figured out my problem. I'm using default headers, while I should be using individual headers. Which i can just set in my service call.

A: All you need to do is create a text input in Angular. Follow the example in the Angular documentation. Then in your controller/directive (whatever scope you store the username and password) just make the authentication call like you did in your question.


text:
Q: Change color of folded text in Sublime Is there any way to change color of the folded text in Sublime. Default color is yellowish.

A: Open your .sublime-color-scheme file, go down to the "globals" dict, and add something like
"fold_marker": "#06FF05",

which will make it bright green. Obviously, feel free to select your own color.
All of the globals options are in the color scheme documentation under Global Settings.


text:
Q: Spring application doesn't appear to be persisting data I'm trying to write something into my database but it's not working despite it reporting "Successfully completed request". After the success everything seems to work fine and my controller redirects me correctly.
Debug
DEBUG a.d.p.payment.PaymentServiceImpl - Requesting to persist new user'max_test@test.com'.
DEBUG a.d.p.payment.model.PaymentDAOImpl - Persisting com.app.payment.model.PaymentUser@86ceb985.
DEBUG o.s.o.j.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler - Creating new EntityManager for shared EntityManager invocation
DEBUG org.hibernate.impl.SessionImpl - opened session at timestamp: 13771737739
DEBUG o.h.e.def.AbstractSaveEventListener - delaying identity-insert due to no transaction in progress
DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
DEBUG o.s.b.f.s.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'redirectForm'
DEBUG o.s.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'redirectForm'; URL [/WEB-INF/jsp/redirectForm.jsp]] in DispatcherServlet with name 'payment'
DEBUG o.s.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/jsp/redirectForm.jsp] in InternalResourceView 'redirectForm'
DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request

appContext.xml (root context)
<context:annotation-config />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="username" value="test" />
    <property name="password" value="test" />
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <!--payment_test is the name of the schema -->
    <property name="url" value="jdbc:mysql://test1.com:3306/payment_test" />
</bean>

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="payment" />

    <property name="persistenceUnitManager">
        <bean class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager" >
            <property name="defaultDataSource" ref="dataSource" />
        </bean>
     </property>

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
            <property name="generateDdl" value="true" />
            <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />

        </bean>
    </property>
</bean>

<context:component-scan base-package="com.app.payment" />
<context:annotation-config />

<!-- Auto scan the components -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" />

<tx:annotation-driven />

PaymentUser
@Entity
@Table(name="PaymentUser")
public class PaymentUser {

    @Id
    @GeneratedValue
    private int id;
    ...
}

PaymentService
@Transactional("transactionManager")
@Service()
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private PaymentDAO paymentDAO;
        // ... service methods
}

Payment DAO
@Repository()
public class PaymentDAOImpl implements PaymentDAO {

    //@PersistenceContext(unitName="payment")
    @PersistenceContext()
    EntityManager em;
}

It seems like it doesn't even start a transaction. Hope thats enough info for somebody to help me. Thanks for any help.
UPDATE
Getting data works fine. Persisting (EntityManager em.persist()) and removing ( em.remove ) are not working. Could there be a right problem. Meaning just read rights and no write rights, but in this case there should be an error i thought.
UPDATE 2
Added <aop:scoped-proxy /> to my dataSource bean, but no changes. Like my debug msg said
DEBUG o.h.e.def.AbstractSaveEventListener - delaying identity-insert due to no transaction in progress

There is no transaction, but where should my transaction start?
I also checked issues Spring: Annotation-driven Transaction Manager
but I'm not sure what to do.
New appContext
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:annotation-config />
    <tx:annotation-driven />

    <!-- Auto scan the components
            <bean id="paymentDao" class="com.app.payment.model.PaymentDAOImpl" />
            <bean id="paymentService" class="com.app.payment.PaymentServiceImpl" />
    should do the same
    -->
    <context:component-scan base-package="com.appn.payment" />

    <bean
        class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" lazy-init="false" destroy-method="close">
        <aop:scoped-proxy />
        <property name="username" value="user" />
        <property name="password" value="pw" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://test1.com:3306/test" />
        <!--  <property name="testOnBorrow" value="true" />
        <property name="validationQuery" value="SELECT 1" />-->
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
         <property name="entityManagerFactory"
                    ref="entityManagerFactory" />
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="payment" />
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceUnitManager">
            <bean class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager" >
                <property name="defaultDataSource" ref="dataSource" />
            </bean>
         </property>

        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />
                <!-- <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />  -->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />

            </bean>
        </property>

        <property name="packagesToScan" value="com.app.payment" />
    </bean>

    <tx:annotation-driven />

</beans>

UPDATE 3
Tried to flush in my PaymentDAO em.flush() which leads me to the error message.
javax.persistence.TransactionRequiredException: no transaction is in progress   at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:792)

which is:
public void flush() {
        if ( !isTransactionInProgress() ) {
            throw new TransactionRequiredException( "no transaction is in progress" );
        }
        try {
            getSession().flush();
        }
        catch ( RuntimeException e ) {
            throw convert( e );
        }
    }

Do i need some kind of special session ?
Also logged it in my controller
log.info("Is transaction active " + TransactionSynchronizationManager.isActualTransactionActive());

which results to false... no sure why there is no active transaction...
UPDATE 4
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Repository
public class PaymentDAOImpl implements PaymentDAO {

    private final Logger log = LoggerFactory.getLogger(getClass());

    //@PersistenceContext()
    @PersistenceContext(unitName="payment")
    EntityManager em;

    @Override
    public void persist(PaymentUser user) {
        log.debug("Persisting {}.", user);
        em.persist(user);
        //em.flush();

    }

    @Override
    public void remove(PaymentUser user) {
        log.debug("Removing {}.", user);
        em.remove(user);
    }

    @Override
    public List<PaymentUser> getPaymentUsers() {
        log.debug("Fetching payment users.");
        return em.createQuery("FROM PaymentUser", PaymentUser.class).getResultList();
    }

    @Override
    public PaymentUser getPaymentUserById(String userId) {
        log.debug("Fetching payment users with id '{}'.",userId);
        return em.createQuery(
                "FROM PaymentUser WHERE userId = :userId", PaymentUser.class)
                .setParameter("userId", userId).getSingleResult();
    }

    @Override
    public void removePaymentUserById(String userId) {
        log.debug("Removing payment users with id '{}'.",userId);
        em.createQuery("DELETE FROM PaymentUser WHERE userId = :userId ", PaymentUser.class).
        setParameter("userId", userId).executeUpdate();

    }

    @Override
    public void mergePaymentUser(PaymentUser user) {
        log.debug("Merging payment user '{}'.",user);
        em.merge(user);
    }
}

UPDATE 5
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

     <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

        <!-- springapp servlet -->
    <servlet>
        <servlet-name>payment</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>payment</servlet-name>
          <url-pattern>/payment/*</url-pattern>
          <url-pattern>/paymentExternalData</url-pattern>
        <url-pattern>/paymentInternalData</url-pattern>
    </servlet-mapping>

    <!-- Welcome files -->
    <welcome-file-list>
         <welcome-file>payment.jsp</welcome-file>
         <welcome-file>payment.html</welcome-file>
    </welcome-file-list>

    <!-- S P R I N G -->

    <!-- Add Support for Spring -->
    <!-- Default applicationContext location: /WEB-INF/applicationContext.xml -->

    <!-- UTF-8 filter -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

UPDATE 6
payment-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:annotation-config />
    <tx:annotation-driven />

    <!-- Auto scan the components -->
    <context:component-scan base-package="com.app.payment" />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

appContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:annotation-config />
    <tx:annotation-driven />

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" lazy-init="false" destroy-method="close">
        <aop:scoped-proxy />
        <property name="username" value="test" />
        <property name="password" value="test" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://test1.com/test" />
        <property name="testOnBorrow" value="true" />
        <property name="validationQuery" value="SELECT 1" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
         <property name="entityManagerFactory"
                    ref="entityManagerFactory" />
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="payment" />
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceUnitManager">
            <bean class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager" >
                <property name="defaultDataSource" ref="dataSource" />
            </bean>
         </property>

        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />

            </bean>
        </property>
    </bean>

</beans>

A: Make sure that you don't have exact duplicate <context:component-scan .../> elements in both xml configurations. If you have this you are basically duplicating all your bean instances. What you initially had was all beans get loaded by the ContextLoaderListener and those are proxied due to the existence of <tx:annotation-driven />.
Now if you have the same <context:component-scan .../> in your payment-servlet.xml this is going to scan again for all beans creating another instance, however due to the fact that there is no <tx:annotation-driven /> it will not be proxied and no transactions applied.
What now happens is that as soon as you need one of your @Service annotated beans the DispatcherServlet looks first in its own ApplicationContext to see if there is bean to satisfy its needs. If there is it is going to be used (your current case) if there isn't it will consult the parent context (the one loaded by the ContextLoaderListener).
What you need to do is configure the ContextLoaderListener to scan for everything BUT @Controller annotated beans and the DispatcherServlet to scan ONLY for @Controller annotated beans. This can be done by configuring the <context:component-scan .../> correctly.
applicationContext.xml
<context:component-scan base-package="com.appn.payment">
  <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

payment-servlet.xml
<context:component-scan base-package="com.appn.payment" use-default-filters="false">
  <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

This will give you transactions and only single instances of your beans. You should remove the <tx:annotation-driven /> from the payment-servlet.xml file.
There is still an open JIRA issue to have this included in the reference guide. Also a thread in the Spring Community Forums explaining this.

A: Looking at your applicationContext.xml again, I noticed you're not assigning an entityManager with your transactionManager declaration. I'm not sure if Spring will implicitly set it, but if it doesn't it would explain why your persists are not working.
For example, change:
<bean id="transactionManager"
   class="org.springframework.orm.jpa.JpaTransactionManager" />

to

<bean id="transactionManager"
   class="org.springframework.orm.jpa.JpaTransactionManager">
  <property name="entityManagerFactory"
      ref="entityManagerFactory" />
</bean>

UPDATE
I've only configured Spring+JPA with Container-managed Entity (looks like your intention as well) - never really Application-managed.  From what I know, in Container-managed with Spring, you don't really need to configure a Persistent Unit. I'm not 100% sure if this will help but try changing how your entityManagerFactory is declared in applicationContext.xml.
<bean id="entityManagerFactory"
   class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">

   <property name="dataSource" ref="dataSource" />

   <property name="packagesToScan" value="com.app.payment" />

   <property name="persistenceProvider">
      <bean class="org.hibernate.ejb.HibernatePersistence" />
   </property>

   <property name="jpaProperties">
      <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
         <prop key="hiberate.show_sql">true</prop>
         ... //additional props
      </props>
   </property>
</bean>

A: When using annotation-driven transactions, you should put @Transactional annotation before your methods which are working with database. It could be either your DAO or Service methods. I can see that you have put @Transactional on top of PaymentServiceImpl but that is not the right place for that annotation.

A: It seems you miss the @Transactional annotation at the start of your DAO implementation class. It would explain why you don't have any transaction opened.
If it is not enough to solve your problem, could you give us your complete DAO implementation class ?

A: managed to find the problem.  Spring Docu "@EnableTransactionManagement and  only looks for @Transactional on beans in the same application context they are defined in." Meaing in my payment-servlet.xml i had no <tx:annotation-driven /> thats why there was no active transaction.

A: after creating transactionManager bean you should enable the transaction in Xml file,
< tx:annotation-driven transaction-manager="transactionManager" />
or
< tx:annotation-driven />
if u written 2nd one then you have to use @Transaction() in your DAO class,
if any method required the transaction then before that write
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
it tell that transaction is require and readOnly=false means you can read and write the data.


text:
Q: Firebase fails to initialise on release build, Flutter Am new to flutter and was trying around Firebase, but the app doesn't initialize Firebase on release
it throws an error, yet it works wen you just run the app. Am using android studio

** E/flutter (12950): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: MissingPluginException(No implementation found
for method Firebase#initializeC ore on channel
plugins.flutter.io/firebase_core)
E/flutter (12950): #0      MethodChannel._invokeMethod
(package:flutter/src/services/platform_channel.dart:156) E/flutter
(12950):  E/flutter (12950): #1
MethodChannel.invokeListMethod
(package:flutter/src/services/platform_channel.dart:344) E/flutter
(12950):
E/flutter (12950): #2      MethodChannelFirebase._initializeCore
(package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:30)
E/flutter (12950):
E/flutter (12950): #3      MethodChannelFirebase.initializeApp
(package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:75)
E/flutter (12950):
E/flutter (12950): #4      Firebase.initializeApp
(package:firebase_core/src/firebase.dart:44) E/flutter (12950):

E/flutter (12950): #5      main
(package:ug_campus_papers_example/main.dart:13) E/flutter (12950):
 E/flutter (12950):
**

Line 13 is the await Firebase.initializeApp();
My Main file is
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'App1 Test',
      home: StreamBuilder(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
          if (snapshot.hasData) {
            User user = FirebaseAuth.instance.currentUser;
            return Make1(user: user,);
          } else
            return SignInScreen();
        },
      ),
    );
  }
}

The pubspec.yaml file is as below
name: ug_camp_example
description: My Flutter app 1.

version: 3.0.1+3

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  firebase_core: "^0.7.0"
  firebase_storage: "^7.0.0"
  firebase_auth: "^0.20.1"
  cloud_firestore: "^0.16.0+1"
  ug_camp:
    path: ../

  cupertino_icons: ^1.0.2
  google_fonts:
  provider:
  file_picker: ^1.1.1
  flutter_plugin_pdf_viewer:
  sqflite:
  path:
  flutterwave:
  flutter_launcher_icons: ^0.7.4

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter_icons:
  image_path: "assets/images/apptest1.png"
  android: true
  ios: true

flutter:
  uses-material-design: true

A: Please try the following:

*

*Update your firebase packages to the latest versions. You're very outdated.

*Ensure you've added your google-services.json to the project.

You mentioned you are using Android Studio, although are you running on Android or iOS? I can provide more instructions depending on the platform.


text:
Q: Replace all occurrences of html tags and special unicode character from a string I have some text like this
Keeping up with friends is faster than ever.
• See what friends are up to
• Share updates, photos and videos
•

And I want text like this
Keeping up with friends is faster than ever.
 • See what friends are up to
 • Share updates, photos and videos

I cleaned out html tags by str.replace(/<[^>]+>/gm, ''), however I cannot remove special symbols.
I am calculating the length of string so special character before compiling in browser gave me different length.
Thanks

A: In this case, it's best to use an external library, like jQuery, to help you out.
In my example below, I'm using the jQuery function called text(). Here's the documentation: http://api.jquery.com/text/
As the name suggests, the jQuery text function reads the HTML as text.

var asText = $("#example").text();
$("#asText").text(asText);
$("#asTextLength").text(asText.length);

• Example & Test

A: The only "right" (complete) way to do this is to parse the document in to an HTML DOM, then create something that will read the DOM and format it to your definition of "simple".
There are many tools out there to do this outside of Javascript, and prior StackOverflow exchanges discuss some of them:

*

*Python convert html to text and mimic formatting

*Extracting text from HTML file using Python
I think "rolling your own" in Javascript will be painful, unless you set a VERY low bar, and only endeavor to "prettyify" a very limited amount of HTML.
That being said, why can't you just continue with the one tool you've got, and keep putting in "rules" to handle what you want to handle?
str.replace(/•/gm, '•')

etc., etc., etc., yada yada yada, ad nauseum...

A: You can use ng-bind-html e.g.

$scope.myHTML = 'Keeping up with friends is faster than ever.
• See what friends are up to
• Share updates, photos and videos
•';


text:
Q: How to decode json string in LUA? Currently i am working in C# console application with integration of lua,
My code is given below,
static void Main(string[] args)
    {
        Lua state = new Lua();

        var jsonConcate = @"[{ ""firstName"":""John"" , ""lastName"":""Doe"", ""email"":""NHP@123.COM"" },{ ""firstName"":""Anna"", ""lastName"":""Smith"", ""email"":""ASD@123.COM"" },{ ""firstName"":""Peter"" , ""lastName"":""Jones"", ""email"":""ZXC@123.COM""}]";

        state.DoString(@"
        function ScriptFunc (input)

            local json = require'json'

            local JSON_string = input

            return json.decode(JSON_string) end"
        );

        //            state.DoString(@"function ScriptFunc ( x, y )
        //  return x + y
        //end");

        //state.DoString(@"function concate(inputString) { var sample = JSON.parse(inputString); sample.forEach(function(a) { a.fullname = ['firstName', 'lastName'].map(function(k) { return a[k]; }).join(' ');});");
        var scriptFunc = state["ScriptFunc"] as LuaFunction;

        var res = scriptFunc.Call(jsonConcate);

        // LuaFunction.Call will also return a array of objects, since a Lua function
        // can return multiple values
    }

I am getting the error while calling the function like given below,
module 'json' not found:

no field package.preload['json']

i am not getting any idea about it.

A: You need to install a json module on your system.  Lua does not come with such a module by default.


text:
Q: docker compose different image size on x86 vs ARM On running docker compose on Intel Mac or AMD Windows, the image size is 482MB and this image works as intended.
However, on M1 PRO (ARM) Mac, the image size is 704MB and doesn't work.
Has anyone encountered this or has any idea why this is?
Thanks!


text:
Q: How to comment out a code on VS code terraform I wish to find out how to comment out a code on VS code in Terraform. I am new to the world of coding, and Amazon web services. I am still learning to use terraform.

A: Attaching the Terraform documentation for commenting
The Terraform language supports three different syntaxes for comments:
# begins a single-line comment, ending at the end of the line.
// also begins a single-line comment, as an alternative to #.
/* and */ are start and end delimiters for a comment that might span over multiple lines.
The # single-line comment style is the default comment style and should be used in most cases. Automatic configuration formatting tools may automatically transform // comments into # comments, since the double-slash style is not idiomatic.

A: The most common way to comment out code in Terraform is to add a hash at the start of the lines:
variable "var_1" {
  type    = string
  default = "value-1"
}

# variable "var_2" {
#   type    = string
#   default = "value-2"
# }

In the above example, Terraform will create the variable called var_1, but will not create the variable called var_2 because that variable has been commented out.
You can check out the Terraform Configuration Syntax.


text:
Q: Using jquery from local file work only if work connection to internet I have local library jquery
<script src="/js/jquery.js" type="text/javascript"></script>

i have ajax request
.post('/default/AjaxAsinc/addnew',{'new':$("#name").val()},function(data){
for(var i;i< data.length.i++)
{

}
},'json');

But it work only if connection to internet is active if connection is down
i see next exception
data is null
[Break on this error] for(var i=0;i<data.length;i++)

Any idea solve this problem ?
PS Browser Firefox not fetch any data from another site all data to responce is local

A: From looking at your code, the only place data is referenced is in your callback function "the response of your $.post().
I would check that data is valid and contains data before trying to for() loop through it.
$.post('/default/AjaxAsinc/addnew', {'new':$("#name").val()}, function(data) {
    if(data !== undefined && data.length > 0) {
        for(var i=0;i< data.length.i++) {

        }
    }
 },'json');


text:
Q: square, symmetric and skew-symmetric matrices, eigenspace Could someone help me with question 5; maybe give me a hint on how to approach.

Let n be a fixed fixed integer and let $V$ be the vector space of $(n×n)$-matrices.
A matrix $\;A$ is symmetric if $\;A=A^T$, and skew-symmetric if $\;A=−A^T$

*

*Show that the subset of symmetric matrices $W_1\subseteq V$, and  skew-symmetric matrices $W_2 \subseteq V$ are subspaces.

*Show that $W_1\cap W_2=0$, and that $W_1+W_2=V$.

*Show that the transformation $\;T:V\to V$, where $T(A)=A+A^T$, is linear.

*Show that $W_1$ and $W_2$ are eigenspaces of $T$.

*Show that there exists a basis of $V$, such that the matrix representation of the transformation $T$ in that basis, is a diagonal matrix.

*

*A subset $\;H⊆V$ is a subspace if:

*

*$\mathbf{0}\in H$

*$\mathbf{u,v}∈H \Leftrightarrow (\mathbf{u}+\mathbf{v}) \in H)$

*$\mathbf{u}∈H \Leftrightarrow (c\mathbf{u})\in H, c\in R$.

Symmetric matrices $W_1\subseteq V$:
$\mathbf{0}^T=\mathbf{0} \Leftrightarrow \mathbf{0}\in W_1$.
Let $\;B_1, B_2\in V$ be symmetric matrices. Then by definition $\;B_1=B_1^T$ and $\;B_2=B_2^T$.
$(B_1+B_2)^T=B_1^T+B_2^T=B_1+B_2=(B_1+B_2) \implies (B_1+B_2) \in W_1$.
Let $\;c \in R$. $(cB)^T=c(B^T)=cB \implies (cB)\in W_1$
Skew-symmetric matrices $W_2\subseteq V$:
$\mathbf{0}^T=\mathbf{0}=\mathbf{-0} \Leftrightarrow \mathbf{0}\in W_2$.
Let $\;C_1, C_2\in V$ be skew-symmetric matrices. Then by definition $\;C_1=-C_1^T$ and $\;C_2=-C_2^T$.
$(C_1+C_2)^T=C_1^T+C_2^T=-C_1-C_2=-(C_1+C_2) \implies (C_1+C_2) \in W_2$.
Let $\;c \in R$. $(cC)^T=c(C^T)=c(-C)=-(cC) \implies (cC) \in W_2$

*Let $A \in V$ be an arbitrary $(n×n)$-matrix. Then $A\in W_1 \Leftrightarrow A^T=A$ and $A\in W_2 \Leftrightarrow A^T=-A$. Therefore, $\;A\in (W_1\cap W_2) \implies A=-A \implies A=0$. $W_1\cap W_2=0$

Let $A\in V, B\in W_1 and C\in W_2$. Then $B^T=B$ and $C^T=-C$.
Suppose that $W_1+W_2=V$. Then $\;A=B+C$ which implies that $A^T=(B+C)^T=B^T+C^T=B+(-C)=B-C$.
We now have that $\begin{cases}A=B+C \\ A^T=B-C\end{cases} \implies \begin{cases}B=\frac{A+A^T}{2} \\ C=\frac{A-A^T}{2}\end{cases} \implies A = B+C=\frac{A+A^T}{2}+\frac{A-A^T}{2} \Leftrightarrow A=\frac{A+A^T+A-A^T}{2}=\frac{2A}{2}=A$. This proves that any arbitrary $(n×n)$-matrix can be written as the sum of a symmetric matrix and a skew-symmetric matrix, i.e. $W_1+W_2=V$

The transformation $\;T:V\to V$, where $T(A)=A+A^T$, is linear if and only if:
 - $\;T(\mathbf{u}+\mathbf{v})=T(\mathbf{u})+T(\mathbf{v}), \forall \mathbf{u}, \mathbf{v} \in V $
 - $\;T(c\mathbf{u})=cT(\mathbf{u})), \forall \mathbf{u}\in V, \forall c\in R $
In (2), we showed that any arbitrary $(n×n)$-matrix can be written as the sum of a symmetric matrix and a skew-symmetric matrix, i.e. $A=B+C, \forall A \in V, \forall B \in W_1, \forall C \in W_2$.
$T(A_1+A_2)=T(A_1)+T(A_2)=T(B_1+C_1)+T(B_2+C_2)=T(B_1)+T(C_1)+T(B_2)+T(C_2)=B_1+B_1^T+C_1+C_1^T+B_2+B_2^T+C_2+C_2^T=B_1+B_1+C_1-C_1+B_2+B_2+C_2-C_2=2B_1+2B_2=2(B_1+B_2)$
In (2), we showed that any arbitrary symmetric matrix $B$ can be written as $B=\frac{A+A^T}{2}$. So, $T(A_1+A_2)=2(B_1+B_2)=2(\frac{A_1+A_1^T}{2}+\frac{A_2+A_2^T}{2})=2\frac{A_1+A_1^T+A_2+A_2^T}{2}=(A_1+A_2)+(A_1^T+A_2^T)=(A_1+A_2)+(A_1+A_2)^T$
$T(cA)=cA+(cA)^T=cA+cA^T=c(A+A^T)$

*If a transformation $T$ has vectors $\mathbf{x}$, for which $T(\mathbf{x})=\lambda \mathbf{x}$, for some skalar $\lambda$, then these vectors $\mathbf{x}$ are called eigenvectors corresponding to that eigenvalue $\lambda$. Furthermore, if a subspace $H$ is the span of these eigenvectors, then $H$ is an eigenspace of $T$ for that eigenvalue.

Let $B\in W_1$ and $C\in W_2$.
$T(B)=B+B^T=B+B=2B \implies \lambda=2$
$T(C)=C+C^T=C-C=0C \implies \lambda=0 \Leftrightarrow W_2 \subseteq Nul(A)$

Could someone help me with question 5; maybe give me a hint on how to approach.

A: Hint: take an element $S$ of $W_1$; apply $T$ to it. How is $T(S)$ related to $S$?
Do the same for $W_2$.
(Go ahead and put your answers to these in as partial results for step 4 in your question, using the "edit" just below the question to  do so.)


text:
Q: jquery success function removing div My task is to get the html data from an ajax call  and upon success i want bind to a specific  tag and remove the rest of html data.
"Specific div tag here in this case is #divtest
 i wanted to remove are divtbldataresults ,divend
data is html  "
THE ISSUE IS IT IS THROWING JAVASCRIPT ERROR, I WAS WONDERING DOES MY CODE HAVE SYNTAXT ISSUES OR AM I DOING SOMETHING WRONG .THANKS IN ADVANCE
$.ajax({
   type: "POST",
   cache: false,
   url: '@Url.Content("~/SyndromicQuery/QueryPeriod")',
   data: { selectedItem: selectedItem,
   startdate: startdate,
   enddate: enddate,
   queryid: queryid
},
success: function (data) {
   var jqObj = $(data);
   jqObj.find('divtbldataresults').remove();
   jqObj.find('divend').remove();
   $('canvas').remove();
   $("#divtest").empty().append(jqObj);

}

A: This could be because #divtest is a child of one of the page elements you are removing.

A: Seems that you're looking for: <divtbldataresults> or <divend> wich I hope you are not using!
If they are classes, try:
var jqObj = $(data);
   jqObj.find('.divtbldataresults').remove();
   jqObj.find('.divend').remove();

If they are id's, try:
var jqObj = $(data);
       jqObj.find('#divtbldataresults').remove();
       jqObj.find('#divend').remove();

Also, if they're first level (or direct) childs. try:
var jqObj = $(data);
       jqObj.filter('.divtbldataresults').remove();
       jqObj.filter('.divend').remove();


text:
Q: Python:Moving through linked list 'next' I'm working through Cracking the Coding Interview 6th ed and am unsure of their definition of 'next'
Their code defining "Linked List" can be found here. I'm trying out the second exercise, which is to find the kth from the end element of a random linked list.
My code:
from LinkedList import LinkedList

def kth_to_last(ll, k):
    num_seen = 0
    length_list = count_length(ll)

    val = ll.head

    # ISSUE IS HERE
    while val.next != None:
        print 'hi'
        val.next = val.next.next

    """
    while num_seen < (length_list - k):
        val = val.next
        num_seen += 1
    """
    return val.next

# Counts length of LL
def count_length(ll):
    val = ll.head
    count = 1
    while val.next != None:
        count += 1
        val.next = val.next.next
    return count

ll = LinkedList()
ll.generate(10, 0, 99)
print(ll)
kth_to_last(ll, 3)

It's counting through the list just fine, but for the first definition, I can't get it to move through the linked list (it won't print 'hi' at all).
I plan to do something like I have commented out (they also have 'tail' defined so I might try that out), but I'm confused why I can move through the list just fine within 'count_length,' but then I can't seem to move through it within 'kth_to_last'?
Edit: To clarify, if I print val.next within 'kth_to_last' it has a value of 'None'
Edit2:
If I comment out the "count_length," the next proceeds just fine. Could someone explain to me why calling this function alters next. Has it stuck me at the end of the list?
My code:
def kth_to_last(ll, k):
    """
    num_seen = 0
    length_list = count_length(ll)
    """

    # Start at head
    val = ll.head
    while val.next != None:
        print val.next
        val = val.next

This prints the list just fine

A: You should do val = val.next instead of val.next = val.next.next.  The way you're doing it, the list will be truncated to a single element when you call count_length.  Because you do count_length at the top of kth_to_last, by the time you get around to walking your list (where your 'hi' is), the list has already been reduced to a single node.
Remember, a linked list is a structure where each node's next property is a pointer to the next node.  Your code is modifying the value of next, which is changing the structure of your linked list.
When you process a linked list (in count_length, or in kth_to_last), what you want to do is point yourself at each node in turn.  You're not trying to modify the nodes themselves, so you won't assign to their value or next attributes.  The way to do this is to change what your pointer (val) is pointing at, and the thing that you want it to point at next is the next node along.  Therefore:
val = ll.head
while val is not None:
    # do something with val here
    val = val.next


text:
Q: Angular testing [$injector:unpr] Unknown provider: STARTUP_CONFIG I'm having trouble getting my tests to run due to dependencies not beeing injected correctly.
The error I'm getting is defined in the title. I've included the actual test code, the app.js & index.html file from my solution.
The problem lies with the deferred bootstrap which I'm not fimiliar with as it was included by one of my colleagues. If I remove the "app.config(function (STARTUP_CONFIG..." from the app.js file then the test runs fine
How can I correctly inject the STARTUP_CONFIG in my test?
test code
..
..
describe("test description...", function () {

var app;
var mockupDataFactory;

beforeEach(module('Konstrukt'));

beforeEach(inject(function (STARTUP_CONFIG,BUDGETS,APPLICATIONS) {
    //failed attempt to inject STARTUP_CONFIG
}));

beforeEach(function () {
    app = angular.module("Konstrukt");
});

beforeEach(function () {
    mockupDataFactory = konstruktMockupData.getInstance();
});

it('should be accessible in app module', function () {
    expect(app.pivotTableService).toNotBe(null); //this test runs fine
});

it('test decr...', inject(function ( pivotTableService) {
    ... //Fails here
..
..

app.js
  ..
    ..
    angular.module('Konstrukt', ['ngGrid', 'ngSanitize', 'ngRoute','pasvaz.bindonce', 'ngAnimate', 'nvd3ChartDirectives', 'ui.select', 'ngProgress', 'ui.grid', 'ui.grid.edit','ui.grid.selection', 'ui.grid.cellNav', 'ui.grid.pinning', 'ui.grid.resizeColumns']);

          var app = angular.module('Konstrukt');
          app.config(function (STARTUP_CONFIG, BUDGETS, APPLICATIONS) {

        var STARTUP_CONFIG = STARTUP_CONFIG;
        var BUDGETS = BUDGETS;
        var APPLICATIONS = APPLICATIONS;

      });
      ..
      ..

index.html
    ..
    ..

    <script>
  setTimeout(function(){
  window.deferredBootstrapper.bootstrap({
    element: window.document.body,
    module: 'Konstrukt',
    resolve: {
      STARTUP_CONFIG: ['$http', function ($http) {
        return $http.get('/scripts/_JSON/activeBudgets.JSON');
      }],
      BUDGETS: ['$http', function ($http) {
        return $http.get('/scripts/_JSON/activeBudgets.JSON');
      }],
      APPLICATIONS: ['$http', function ($http) {
        return $http.get('/scripts/_JSON/applications.JSON');
      }]
    }
  })
  } , 1500);
</script>

A: The deferredBootstrapper will not run in your unit tests, which means the constants it normally adds to your module won't be available.
You can add a global beforeEach that provides mocked versions of them:
beforeEach(function () {
  module(function ($provide) {
    $provide.constant('STARTUP_CONFIG', { something: 'something' });
    $provide.constant('BUDGETS', { something: 'something' });
    $provide.constant('APPLICATIONS', { something: 'something' });
  });
});


text:
Q: I have a few question about referencing and location nodes in Godot I'm making a game that's top down and has enemies. They don't shoot just walk at you. Well there supposed too. I just can't seem to get to enemies to be able to locate the player even if the player is the parent node.
This is the code here:
extends KinematicBody2D
var health: int = 100
var motion = Vector2()
var speed = 100

func _on_Area2D_body_entered(body):
    yield(get_tree().create_timer(0.1), 'timeout')
    if "Bullet" in body.name:
        health -= 20
    if health <= 1:
        queue_free()

func _physics_process(delta):
    var Player = get_parent().get_node("Player")

    position += (Player.position - position)/50
    look_at(Global.player.global_position)

    move_and_collide(motion)

but all I get from this is an error saying: Invalid get index 'position' (on base: 'null instance').
I don't understand what's going here. So far I've had to make the Player the parent but I also need to make it the main scenes parent so I can instance it so there are multiple of them. That's literally impossible in Godot standards. another question is I'm trying to make the enemies spawn around a moving camera but all they do is go to one corner.
My code is as showed in a camera 2d :https://youtu.be/klBvssJE5Qg
extends Node2D
onready var camera_x = $Player/playercamera.global_position.x
onready var camera_y = $Player/playercamera.global_position.y
var normal_zombie = preload("res://scenes/Enemy.tscn")
var player = null

func _on_Timer_timeout():
var enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))

while enemy_position.x < 510 and enemy_position.x > -510 and enemy_position.y < 310 and enemy_position.y > -310:
    enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))

var normal_zombie_instance = normal_zombie.instance()
normal_zombie_instance.position = enemy_position
add_child(normal_zombie_instance)

Last problem I'm facing is that I made it so the zombies had 100 health and would die at 0. Whenever a bunch spawn(ed) (I tried fixing it but ended up making it worse) and I killed 2 at the same time it would just crash. The codes here.
   func _on_Area2D_body_entered(body):
yield(get_tree().create_timer(0.1), 'timeout')
if "Bullet" in body.name:
    health -= 20
if health <= 1:
    queue_free()

If you read all of this your a legend. If you helped me out with all the questions I would've given you boba tea. To bad I don't know where you live and can't send it to you. Please someone answer :3
UwU
I have looked up many many ways to do it. I only use stack overflow if it's my last hope. Please help!!!

A: Before looking at anything else, you say you have this error:

Invalid get index 'position' (on base: 'null instance')

This is not hard to understand. You have a null and you are trying to get position of it.
And looking at the code, that got to be here:
func _physics_process(delta):
    var Player = get_parent().get_node("Player")

    position += (Player.position - position)/50
    look_at(Global.player.global_position)

    move_and_collide(motion)

More precisely, here:
position += (Player.position - position)/50

So Player is null. So this get_parent().get_node("Player") gave you null.
Please notice that get_parent().get_node("Player") is looking for a sibling. It literally wants to get a child called "Player" from the parent. A child from the parent. A sibling.
I'll also point out that get_parent().get_node("Player") is equivalent to get_node("../Player") which is equivalent to $"../Player". If you need to put the Player somewhere else, update the path accordingly.

Let us break this code down:
extends Node2D
onready var camera_x = $Player/playercamera.global_position.x
onready var camera_y = $Player/playercamera.global_position.y
var normal_zombie = preload("res://scenes/Enemy.tscn")
var player = null

func _on_Timer_timeout():
var enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))

while enemy_position.x < 510 and enemy_position.x > -510 and enemy_position.y < 310 and enemy_position.y > -310:
    enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))

var normal_zombie_instance = normal_zombie.instance()
normal_zombie_instance.position = enemy_position
add_child(normal_zombie_instance)

First of all, here you are taking a copy of these values when the Node is ready:
onready var camera_x = $Player/playercamera.global_position.x
onready var camera_y = $Player/playercamera.global_position.y

And second I don't see you update them or use them.
I would, instead have a reference to the camera. Which assuming these lines are correct would be like this:
onready var camera = $Player/playercamera

Which means that the Player is a child of this Node, and playercamera is a child of Player. If you need to put the camera somewhere else, you can update the path accordingly.
Then (I assuming the indentation problem was when posting the code here), you have this:
func _on_Timer_timeout():
    var enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))

    while enemy_position.x < 510 and enemy_position.x > -510 and enemy_position.y < 310 and enemy_position.y > -310:
        enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))

    var normal_zombie_instance = normal_zombie.instance()
    normal_zombie_instance.position = enemy_position
    add_child(normal_zombie_instance)

You are using position, which as I said in the other answer is relative to the parent. And the parent is not not the camera. Quite the opposite, the camera is a child of the Player, which is a child of this Node.
Instead set the global_position (or the global_transform.origin if you prefer) to camera.to_global(enemy_position) (where camera is the reference to the camera).
In the other answer mentioned to use camera.to_global if the camera was not the parent but you had a reference to it. You are not forced to make it a parent.
Note: The global_position is not relative to the parent, but to the world.

And about the crash (also assuming the indentation problem was posting the code here), you have this:
func _on_Area2D_body_entered(body):
    yield(get_tree().create_timer(0.1), 'timeout')
    if "Bullet" in body.name:
        health -= 20
    if health <= 1:
        queue_free()

I want you to imagine the following scenario:

*

*A first body enters.

*The execution for the first body reaches yield.

*After the timeout the execution for the first body resumes and reaches queue_free.

*A second body enters, the same frame that queue_free was called.

*The execution for the second reaches yield.

*Godot frees the Node (because you had called queue_free).

*After the timeout… Eh? Godot cannot resume the execution for the second body because the Node was freed.

That is not the only way it can happen. It is just the easier to explain because it is the most sequential scenario. It could also be something like this:

*

*A first body enters.

*The execution for the first body reaches yield.

*A second body enters.

*The execution for the second reaches yield.

*After the timeout the execution for the first body resumes and reaches queue_free.

*Godot frees the Node (because you had called queue_free).

*After the timeout… Eh? Godot cannot resume the execution for the second body because the Node was freed.

I bring this up because the way I described it earlier might suggest to you that you can avoid this problem simply by using is_queued_for_deletion but that is not the case.
Even if you were to fix that for this method, anything else that was pending in yield when the Node was freed would be an issue. Thus, you have two solutions:

*

*Don't call queue_free unless you know nothing is pending in yield.

*Don't use yield.

There are gotchas and caveats. I'll point you to Are Yields a Bad Code Practice in GDScript?.
I'll side on not using yield in this case. So my fix would be like this:
func _on_Area2D_body_entered(body):
    get_tree().create_timer(0.1).connect("timeout", self, take_damage, [20])

func take_damage(amount) -> void:
    health -= amount
    if health <= 1:
        queue_free()

In principle it is the same idea. You are creating a timer, and when the timer emits the "timeout" signal it will execute some code. The difference is that we didn't use yield, instead we connected to the signal, and when a Node is freed Godot disconnect any signals it might have connected.

I have said a couple times that you can update a path according to where the Nodes are relative to each other. You could also export a NodePath which I also mentioned in the other answer and set it via the inspector. For the camera example, it could be like this:
export var camera_path:NodePath
onready var camera = get_node(camera_path)

With the caveat that, as I mentioned earlier, the value of the onready variable is a copy taken when the Node is ready. So, changing the camera_path in runtime won't update the camera, you could handles that using setget if you need to.
I am going to, once more, point you to Nodes and scene instances, and see the documentation on NodePath too.


text:
Q: PHP: Streaming Images Outside of Webroot and Caching I'm using Apache and when I request an image directly for the first time, the status of the image is "200 OK". Subsequent requests have a status of "304 Not Modified", which is good because it saves bandwidth for both the client and server.
I'm working on a website that will allow users to upload images. These images need to be stored outside of the webroot not just to prevent hotlinking, but also so I can collect statistics on the images. So my thought was to use a PHP script like this to stream the images:
<?php

    $image_to_stream = '/path/outside/of/webroot/image.jpg';
    $cache_seconds = 2592000; // 30 days

    header("Cache-Control: max-age=$cache_seconds");
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $cache_seconds) . ' GMT');
    header('Pragma: cache');
    header('Content-Type: image/jpg');
    header('Content-length: ' . filesize($image_to_stream));

    readfile($image_to_stream);

?>

However, the script appears to always have a status of "200 OK" and the entire image gets streamed. Is there a way to fix this or should I be taking another approach or what? Thanks!

A: You need to handle the If-Modified-Since request header.
Basically, check the timestamp on that file locally.  If it has changed since the date specified in the If-Modified-Since header, return it.  Otherwise, send bac, a 304 not modified.
From the RFC:

A GET method with an If-Modified-Since header and no Range header requests that the identified entity be transferred only if it has been modified since the date given by the If-Modified-Since header. The algorithm for determining this includes the following cases:
a) If the request would normally result in anything other than a
           200 (OK) status, or if the passed If-Modified-Since date is
           invalid, the response is exactly the same as for a normal GET.
           A date which is later than the server's current time is
           invalid.
b) If the variant has been modified since the If-Modified-Since
           date, the response is exactly the same as for a normal GET.
c) If the variant has not been modified since a valid If-
           Modified-Since date, the server SHOULD return a 304 (Not
           Modified) response.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
You can send that with this PHP code:
header('HTTP/1.1 304 Not Modified', true, 304);


text:
Q: "Failed to open/Failed to load image" messages for EFI files I've just bought a new laptop Acer Aspire E5-575-584A with only one SSD and its comes with an Acer Linux distribution. I installed Lubuntu 16.04 fine, but when I installed Ubuntu GNOME 16.04.02 something happened. Finally I installed Ubuntu 14.04 and the error is still the same.
I am new to this and I'm confused about the UEFI-Legacy  installation. I've tried a lot of things but nothing works. My laptop cannot boot from ssd, only from a Liveusb/cd. But when I try for a new installation it seems that the ssd has the Ubuntu 14.04. I've got this message when I open it and I cannot find an answer on the web :
Failed to open \EFI\Microsoft\Boot\max64.efi - Not Found
Failed to load image \EFI\Microsoft\Boot\max64.efi - Not Found
Failed to star MokManager : Not Found
Failed to open \EFI\Microsoft\Boot\grub64x.efi - Not Found
Failed to load image \EFI\Microsoft\Boot\grubx64.efi : Not Found
start_image() returned Not Found

AND afters one-two seconds the message becomes:
Failed to open \EFI\Boot\max64.efi - Not Found
Failed to load image \EFI\Boot\max64.efi - Not Found
Failed to star MokManager : Not Found
Failed to open \EFI\Boot\grub64x.efi - Not Found
Failed to load image \EFI\Boot\grubx64.efi : Not Found
start_image() returned Not Found

This is my Boot Repair log

A: Your computer uses EFI firmware, and the Boot Repair output looks like the computer came with a Windows installation that you deleted and replaced with Ubuntu. I know you say it came with "an Acer Linux distribution," which is why I'm leading with what your Boot Repair output suggests, since the two are at odds. My suspicion is that, for whatever reason (maybe a defective firmware), Acer installed their Linux boot loader in a way that makes it look like the Windows boot loader, and the computer is still trying to boot via that boot loader. Other changes must have deleted follow-up boot loader programs, resulting in the error messages you're seeing.
I can think of several ways to fix this problem, but none of them is guaranteed to work, so you may need to try multiple approaches. I'll describe a couple that are most likely to work....
Method 1: Boot Repair

*

*Boot your Ubuntu installation medium in "try before installing" mode.

*Launch Boot Repair.

*Click the Advanced Options item.

*Select the "Backup and Rename Windows EFI Files" option.

*Click Apply to run Boot Repair.

Method 2: rEFInd

*

*Download the CD-R or USB flash drive version of my rEFInd boot manager from the links here.

*Create a medium using the image you downloaded.

*Boot into your firmware setup utility and disable Secure Boot. Unfortunately, how you do this varies from one system to another. See this page of mine for several examples of how to do it.

*Boot with the rEFInd medium.

*In rEFInd, select a Linux kernel image (Boot boot\vmlinuz...) to boot your current Ubuntu installation.

*Install rEFInd by using the Debian package or PPA.

*Reboot. If rEFInd comes up, you should be able to boot Ubuntu and you'll be good. If not....

*Boot with the rEFInd medium you prepared earlier, and boot to Ubuntu, as in step #5.

*Open a terminal and type sudo mvrefind /boot/efi/EFI/ubuntu /boot/efi/EFI/Microsoft/Boot.

*Reboot. With any luck, rEFInd will appear.

You may optionally re-enable Secure Boot, and you may want to delete redundant boot loader files from /boot/efi/EFI/*/ directories or edit refind.conf in /boot/efi/EFI/refind/ or /boot/efi/EFI/Microsoft/Boot to uncomment and add boot loaders to the dont_scan_dirs or dont_scan_files lines.

A: It happened to me when trying to boot from live USB with Ubuntu LTS 18.10 on a Huawei Matebook Pro.
What worked for me is to just disable secure boot on bios.

A: I've had the same issue after burning elementary os 6 to a USB using etcher ,  then booting from the flash drive i was prompted with this error .
My bios settings include
-secure boot enabled
-legacy mode disabled
My workaround was
-power on the PC
-press a function key -ESC in my case- to enter startup menu
-Run UEFI Application
-Choose the portable drive to boot from e.g. USB:Kingston DataTraveler
-File browser : EFI / Boot > BOOT > GRUVBOX64.EFI


text:
Q: Repository commit count wrong Repo: sumitridhal/n-th-digit-of-e
Count shown in github profile and commit count in repository not matching.
Due to this some of latest commits are missing from repository.
Is there any way i can retrieve all my commits?

A: If you rebase and then force push, you need to try and restore the previous master HEAD which was overwritten by the new (and shorter) history.
Check git reflog: you should see your old commit before rebase.
Or See "Does github remember commit IDs?": you can query the push events to get back an old commit that way.
In both instances, you can at least create a branch based on that commit (either local branch on your PC, or a remote branch directly through the GitHub web interface), in order to see if you get back your history.
The number will still be off, but at least your missing commits will be there, and you can try again to cherry-pick/order them as you want.


text:
Q: Round rectangle corners and shadows in Android 4.x? I want to create something close to Material Theme in app that is supposed to work with Android 4.x and 5.x.
I have tried to use Material theme, but I need api 21 for that. My current minimum api is 15 and I want to keep that.
Do I have to create shadows as PNG images or there is easier way?
I want to keep application compatybile with Android 4.x and I have no time to maintain two versions (for Android 4.x and 5.x).

A: I wouldn't call it an easy way, but you can mimic real animated shadows on any device above Android Cupcake. Here's how it works:

*

*draw your view to an off-screen bitmap with LightingColorFilter set to 0,0

*blur the black shape (the off-screen bitmap) using the ScriptIntrinsicBlur class and elevation value as radius

*draw the bitmap beneath the view

It requires adding custom elevation attributes, custom views capable of rendering shadows, and using render script and the compatibility library (for older devices).
If you'd like to see that solution in action, check my library:
https://github.com/ZieIony/Carbon


text:
Q: SPF: Which IP is being looked at during evaluation? Let's say I have:

*

*public IP address A: sending host

*public IP address B: mail relay for A

*public IP address C: receiver MX

What IP does C look at?
Does he try to find the IP of A in the "Received" headers (e.g. by trying to find the first non-private IP)? Or does he use the source IP address of the connection established in this case from B?
I see that for example googlemail seems to do the latter. While it looks like one of our local providers seems to do the former.
https://www.rfc-editor.org/rfc/rfc7208 does not really enlighten me concerning this basic point. I did find the circumstantial phrase

Because SPF evaluation is based on the IP address of the "last" sending SMTP server

in section 10.3. but I guess there needs to be a clearer definition somewhere.

A: Received: from headers are not reliable except when placed there by servers under your control, so it would make no sense to examine them.  Even if they were reliable, many come from internal movements of email inside the sender's infrastructure, about which SPF has nothing to say, so it would be inappropriate to examine those.
In fact, that sentence you quote is precise and unambiguous: when your server is performing an RFC-compliant SPF check on an inbound email, all it cares about is the address of the server that is trying to submit the email.  Or, as s4.1 of the RFC you point to says:

The check_host() function takes these arguments:
     - the IP address of the SMTP client that is emitting
                the mail, either IPv4 or IPv6

If that address is from a range permitted by the appropriate record, the email should pass; if not, its fate should fall to the all record, and it should be handled accordingly.
It is certainly possible that some providers examine the purported chain of relay addresses more deeply, but that is (a) not part of the SPF RFC, and (b) entirely their own business.


text:
Q: SSIS Config File Not valid error during the scheduling the package I have Created my one Package with Config file and working very good in BIDS, DTEXEC.EXE and DTEXECUI.exe on remote server But we are using some third Party tool for scheduling the jobs( I cant say). and It wont run in it, it creates an error "the config file is invalid and errors for file location path." what should I do?
Appreciate your help.

A: Given that your package works fine from BIDS and when you manually execute it, this strongly smells of a permission issue.
You will need to look at the Active Directory user that runs the mysterious third party scheduling tool. You will need to ensure that account (domain\ThirdPartySchedulerService) has read access to DriveLetter:\path\to\config.dtsconfig
Also note that if there is an assumption about a drive letter being mapped, it may not apply to service accounts. Similar statement about access to network shares.


text:
Q: SPParameters Not Matching Stored Procedure I have posted this question in the Logi Analytics DevNet but it is a graveyard there and I am hoping I can get an answer here. I am using Logi Info v12.2.116.
I am using a stored procedure to get data to fill my reports. The stored procedure calls an RPG program. I have done this many times, but today when I created a new stored procedure, a new report, the parameters for some reason do not match up. I have restarted Logi as well... Sometimes it doesn't pick up new stored procedures until it reboots but that didn't work either. I have never seen this error before:

The number of parameter values set or registered does not match the number of parameters

Here is the code for my parameters:
<DataLayer Type="SP" Command="myStoredProcedure">
<SPParameters NullValue="'">
<SPParameter SPParamDirection="Input" ID="GAct" SPParamSize="2" SPParamType="dt-129" Value="RE" />
<SPParameter SPParamDirection="Input" ID="rsDetail" SPParamType="dt-129" Value="N" SPParamSize="1" />
<SPParameter SPParamDirection="Input" ID="rsFromDate" SPParamSize="10" SPParamType="dt-7" Value="@ Request.paramFromDate~" />
<SPParameter SPParamDirection="Input" ID="rsToDate" SPParamSize="10" SPParamType="dt-7" Value="@ Request.paramToDate~" />
<SPParameter SPParamDirection="Input" ID="rsDepts" SPParamSize="256" SPParamType="dt-129" Value="@ Request.paramAllDepartments~" />
</SPParameters>

Here is the stored procedure definition:
1 IN GACT         CHARACTER 2   No default
2 IN RSDETAIL     CHARACTER 1   No default
3 IN RSFROMDATE   DATE          No default
4 IN RSTODATE     DATE          No default
5 IN RSDEPTS      CHARACTER 256 No default

What in the world is causing this problem? Yes I am connecting to the same partition/library. Yes the program and stored procedure work perfectly fine when being called outside of Logi. Yes I am calling the right stored procedure.

A: Change:
<SPParameter SPParamDirection="Input" ID="GAct" SPParamSize="2" SPParamType="dt-129" Value="RE" />

To:
<SPParameter SPParamDirection="Input" ID="GAct" SPParamSize="2" SPParamType="dt-200" Value="RE" />

Char is generally considered to be a single character and is likely what is causing your issue. Also, unrelated, but I typically just use size 0 on all my SPParams to avoid truncation issues.


text:
Q: Populating a ListView from SharedPreferences What I'm looking to do is populate a ListView from an AlertDialog entry.  I've tried to do this with SharedPreferences, previously I've had the last entry just saving into the ListView (if I entered more than one String), so when I left the activity and returned all that appeared in the list was my last entry.
However I figured that problem out and have modified the save procedure to change the "Key" field of the stored preference by incrementing an attached Int variable.
To give you the full picture of what's happening:
First post so pic is here : http://imgur.com/yGLQx
This is the output of multiple entries to the ListView.
If you remain within the Activity, the ListView is populated with the entries from the user, however after leaving the activity and returning to it, its like the entries have been registered, but the String values have not been saved.
Here is my code:
public class ManageLinguisticPhrases extends ListActivity {

private static final String PHRASE = "Phrase_";

private SharedPreferences prefs;
private String prefName = "myPhrasesStorage";

ArrayList <String> listItems = new ArrayList <String>();
ArrayAdapter <String> adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    adapter = new ArrayAdapter <String> (this, android.R.layout.simple_list_item_1, listItems);
    setListAdapter(adapter);

    prefs = getSharedPreferences(prefName, MODE_PRIVATE);
    LinkedList<String> phrasesCollection = new LinkedList<String>();
    int phraseCount = prefs.getInt("phrase_count", 0);

    for(int i = 1; i <= phraseCount; i++) {
        phrasesCollection.add(prefs.getString(PHRASE + i, "<< Enter a phrase >>"));
    }

    listItems.addAll(phrasesCollection);
    adapter.notifyDataSetChanged();

}

@Override
protected Dialog onCreateDialog(int id)
{

    final EditText input = new EditText(this);
    final String text = input.getText().toString();

    switch (id)
    {
    case 0:
        return new AlertDialog.Builder(this)
        .setIcon(R.drawable.ic_launcher)
        .setTitle("Please enter the new data")
        .setView(input)
        .setPositiveButton("Save", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int whichButton)
            {
                listItems.add(input.getText().toString());
                adapter.notifyDataSetChanged();

                prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                    //increments index by 1
                    editor.putInt("phrase_count", prefs.getInt("phrase_count", 0) + 1);
                    //save new phrase in myPhrasesStorage with key "name[index]"
                    editor.putString(PHRASE + (prefs.getInt("phrase_count", 0) + 1), text);

                editor.commit();

            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int whichButton)
            {

            }
    })

            .create();
    }
    return null;
}

private void CreateMenu(Menu menu)
{
    MenuItem mnu1 = menu.add(0, 0, 0, "Add data");
    {
        mnu1.setAlphabeticShortcut('a');
        mnu1.setIcon(android.R.drawable.ic_menu_add);
    }
    MenuItem mnu2 = menu.add(0, 1, 1, "Edit data");
    {
        mnu2.setAlphabeticShortcut('b');
        mnu2.setIcon(android.R.drawable.ic_menu_edit);
    }
    MenuItem mnu3 = menu.add(0, 2, 2, "Delete data");
    {
        mnu3.setAlphabeticShortcut('c');
        mnu3.setIcon(android.R.drawable.ic_menu_delete);
    }

}

private boolean MenuChoice(MenuItem item)
{
    switch (item.getItemId())
    {
        case 0:

            showDialog(0);

        return true;
    }
    return false;
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    super.onCreateOptionsMenu(menu);
    CreateMenu(menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    return MenuChoice(item);
}

So yeah take a look, tell me if I'm doing something ridiculous, and let me know!
Cheers for the help!

A: Maybe contents of rows are being shown, but their font color is black! Test it by clicking on them or set background color for listview.

A: How many phrases are you saving into shared prefs? If it's more than just a few (say, 10), I would suggest that you use a sqlite database instead. Shared preferences are not designed for large lists of data.
Anyways, I think I may have found your problem. When you click the "Save" button, this code runs:
listItems.add(input.getText().toString());
adapter.notifyDataSetChanged();

You already set the adapter to use the listItems array at the beginning, and (I believe) now adapter has it's own internal array that it's using to hold the data. Try this:
adapter.add(input.getText().toString());
adapter.notifyDataSetChanged();

In fact, I don't think you really need the listItems array as an instance variable, and you should be able to get rid of phrasesCollection entirely. Back at the beginning in your onCreate method, try this:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    prefs = getSharedPreferences(prefName, MODE_PRIVATE);

    int phraseCount = prefs.getInt("phrase_count", 0);
    ArrayList <String> listItems = new ArrayList <String>();

    for(int i = 1; i <= phraseCount; i++) {
        listItems.add(prefs.getString(PHRASE + i, "<< Enter a phrase >>"));
    }

    adapter = new ArrayAdapter <String> (this, android.R.layout.simple_list_item_1, listItems);
    setListAdapter(adapter);

}

Hopefully this helps.

A: So I found the solution, I made it overcomplicated first time round with the ArrayList Iterator.
The solution now basically adds manual entries to the ListView from an AlertDialog, entries are stored in an ArrayList listItems.
Updated source code:
public class ManageLinguisticPhrases extends ListActivity
{

    private static final String PHRASE = "Phrase_";

    private String prefName = "myPhrasesStorage";
    private SharedPreferences prefs;

    private ArrayList <String> listItems = new ArrayList <String>();
    private  List<String> phrasesCollection = new LinkedList<String>();

    private String phraseText = "test";
    private static int count = 0;

    private ArrayAdapter <String> adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        adapter = new ArrayAdapter <String> (this, android.R.layout.simple_list_item_1, listItems);
        setListAdapter(adapter);

        prefs = this.getSharedPreferences(prefName, MODE_PRIVATE);

        for(int i = 0; i <= prefs.getAll().size(); i++) {
            phrasesCollection.add(i, prefs.getString(PHRASE + i, "Ola, Tudo bem?"));
        }

        listItems.addAll(phrasesCollection);
        adapter.notifyDataSetChanged();

    }

    @Override
    protected Dialog onCreateDialog(int id)
    {

        final EditText input = new EditText(this);

        switch (id)
        {
        case 0:
            return new AlertDialog.Builder(this)
            .setIcon(R.drawable.ic_launcher)
            .setTitle("Please enter the new data")
            .setView(input)
            .setPositiveButton("Save", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog,    int whichButton)
                {
                    phraseText = input.getText().toString();
                    listItems.add(phraseText);

                    adapter.notifyDataSetChanged();

                    prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                    SharedPreferences.Editor editor = prefs.edit();

                    //save new phrase in myPhrasesStorage with key "Phrase_[count]"
                    editor.putString(PHRASE + count + "", phraseText);
                    count++;

                    editor.commit();

                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog,    int whichButton)
                {

                }
        })

                .create();
        }
        return null;
    }

    private void CreateMenu(Menu menu)
    {
        MenuItem mnu1 = menu.add(0, 0, 0, "Add data");
        {
            mnu1.setAlphabeticShortcut('a');
            mnu1.setIcon(android.R.drawable.ic_menu_add);
        }
        MenuItem mnu2 = menu.add(0, 1, 1, "Edit data");
        {
            mnu2.setAlphabeticShortcut('b');
            mnu2.setIcon(android.R.drawable.ic_menu_edit);
        }
        MenuItem mnu3 = menu.add(0, 2, 2, "Clear ALL data");
        {
            mnu3.setAlphabeticShortcut('c');
            mnu3.setIcon(android.R.drawable.ic_menu_delete);
        }

    }

    private boolean MenuChoice(MenuItem item)
    {
        switch (item.getItemId())
        {
            case 0:

                showDialog(0);

            return true;

            case 2:

                prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();

                editor.clear();
                editor.commit();

                listItems.clear();
                adapter.notifyDataSetChanged();

                Toast.makeText(this, "All phrases deleted",
                        Toast.LENGTH_LONG).show();

            return true;
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);
        CreateMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        return MenuChoice(item);
    }
}

Enjoy!


text:
Q: Xamarin forms Realm Platform user login Exception on iOS only I downloaded the QuickJournal sample app. Set up my account and added a user in Realm Cloud.
After that, I added this simple code to login the user.
Uri authURL = new Uri("$$InstanceUrlHere");
Credentials credentials = Credentials.UsernamePassword("Ali", "123", createUser: false);
try
{
    //trying to login using realm default authticaion: username and password
    var user = await User.LoginAsync(credentials, authURL);
    await Application.Current.MainPage.DisplayAlert("Confirmation", "User Identitiy from Realm Login: " + user.Identity, "Ok");
}
catch(Exception ex)
{
    await Application.Current.MainPage.DisplayAlert("Error", "Error while Trying to login", "Ok");
    System.Diagnostics.Debug.WriteLine("Error while Trying to login: " + ex);
}

Code is working fine on Android Emulator. But, on iOS, I am getting the following error on the LoginAsync step:
System.TypeInitializationException: The type initializer for 'Realms.Sync.SharedRealmHandleExtensions' threw an exception. —> System.EntryPointNotFoundException: realm_install_syncsession_callbacks
at (wrapper managed-to-native) Realms.Sync.SharedRealmHandleExtensions+NativeMethods.install_syncsession_callbacks(Realms.Sync.SharedRealmHandleExtensions/NativeMethods/RefreshAccessTokenCallbackDelegate,Realms.Sync.SharedRealmHandleExtensions/NativeMethods/SessionErrorCallback,Realms.Sync.SharedRealmHandleExtensions/NativeMethods/SessionProgressCallback,Realms.Sync.SharedRealmHandleExtensions/NativeMethods/SessionWaitCallback)
at Realms.Sync.SharedRealmHandleExtensions…cctor () [0x0004e] in :0

I found this similar question but it's old and not helping my case:
realm in Xamarin, System.EntryPointNotfoundException when trying to use realm


text:
Q: Compressing string I tried send some data(variable 1 - 4 MB) by http headers,but returned the following error in ajax.response:
HTTP Error 400. The size of the request headers is too long.
there something that I can do or the method single is compressing the data? if yes,how I do this?
any help is appreciated. Thanks in advance!

A: If you're sending around that much data, put it in the body of the request (e.g, in a HTTP POST), not in the headers. Increasing the header size limit (as cwallenpoole suggests) will still cause problems with users who are behind web proxies.

A: Personally, I would just up the size of the acceptable header. MS suggests the same and gives instructions on how to raise it to 16 MB if necessary (see MaxRequestBytes).

A: Most http server accept about 8-16KB for the header. Therefore, if your data is too large, just use POST method to send it.


text:
Q: 3d audio representation of objects on a map OK, I'm going to try to explain the issue I am having in a few lines.
I am a blind game developer, and as such I make games using only audio and not graphics, so other blind people can play.
I am trying to build a binaural audio scene in a game. However, the sounds that play only represent their center position on the screen, x/2 and y/2.
This works fine for persons, cars, and other small objects however, when there is a door or a wall, that occupies 5 squares or the whole x or y in the case of walls, I am clueless as to how to implement this into sound.
Does anyone have any ideas?
I don't think this has nothing to do with the sound library that I use, rather it's to do with maths or geometry etc.
I thought about creating multiple coppies of the sound, one for each position, but people say it's a really bad idea.
So what do you suggest?
Thanks.

A: I would create a set of audio filters which gets applied to sound of any object to indicate attributes like its size and whether its moving towards or away from POV
Experiment with defining these audio filters to be possibly modulating its volume up and down  or maybe modulating the frequency of an object's audio
These audio filters are applying an agreed upon audio texture to the object's audio


text:
Q: Horizontal AJAX posts loader, detect when scrollbar reaches the end I've set up a div (#reviewspostscont) with overflow-x:scroll, now i want to load posts with AJAX but I cant't detect when the scrollbar gets to the very right end.
Down below is the code I have so far, I can't understand whats wrong with it.
Thanks in advance,
Matt
   $('#reviewspostscont').scroll(function(){
   var $this = $(this);
   scrollPercentage = 100 * $(this).scrollLeft() / ($('#reviewspostscont').width() - $(this).width());

                if  (scrollPercentage == 100){
                    alert('end!');  // just to test the code, then AJAX
                }
        });

A: The issue is around how you calculate the total scroll width. I have added a JSFiddle. Basically, instead of:
scrollPercentage = 100 * $(this).scrollLeft() /
    ($('#reviewspostscont').width() - $(this).width());

You should have:
scrollPercentage = 100 * $(this).scrollLeft() /
    ($(this)[0].scrollWidth - $(this).width());


text:
Q: ALSA - unmuting devices? I have been trying to capture audio, within a native linux program running on an Android device via adb shell.
Since I seemed to be getting only (very quiet) noise, i.e. no actual signal (interestingly, an Android/Java program doing similar did show there was a signal on that input),
I executed alsa_amixer, which had one entry that looked like the right one:
Simple mixer control 'Capture',0
  Capabilities: cvolume cswitch penum
  Capture channels: Front Left - Front Right
  Limits: Capture 0 - 63
  Front Left: Capture 31 [49%] [0.00dB] [off]
  Front Right: Capture 31 [49%] [0.00dB] [off]

"off". That would explain the noise.
So I looked for examples of how to use alsa_amixer to unmute the channels, I found different suggestions for parameters like "49% on" or "49% unmute", or just "unmute" none of which works. (if the volume% is left out, it says "Invalid command!", otherwise, the volume is set, but the on/unmute is ignored)
I also searched how to do this programatically (which I'll ultimately need to do, although the manual approach would be helpful for now), but wasn't too lucky there.
The only ALSA lib command I found which sounds like it could do something like that was "snd_mixer_selem_set_capture_switch_all", but the docs don't day what the parameter does (1/0 is not on/off, I tried that ;) )

A: The manual approach to set these things via alsa_amixer does work - but only if android is built with the 'BoardConfigCommon.mk' modified, at the entry: BOARD_USES_ALSA_AUDIO := false, instead of true.
Yeah, this will probably disable ALSA for android, which is why it wouldn't meddle with the mixer settings anymore.
To you android programmers out there, note that this is a very niche use case of course, as was to be expected by my original post to begin with.
This is not what most people would want to do.
I just happen to tinker with an android device here in unusual ways ;-)

A: Just posting the code as question giver suggested, also don't like external links.
#include <alsa/asoundlib.h>

int main()
{
    snd_mixer_t *handle;
    snd_mixer_selem_id_t *sid;

    snd_mixer_open(&handle, 0);
    snd_mixer_attach(handle, "default");
    snd_mixer_selem_register(handle, NULL, NULL);
    snd_mixer_load(handle);

    snd_mixer_selem_id_alloca(&sid);
    snd_mixer_selem_id_set_index(sid, 0);
    snd_mixer_selem_id_set_name(sid, "Capture");
    snd_mixer_elem_t* elem = snd_mixer_find_selem(handle, sid);

    snd_mixer_selem_set_capture_switch_all(elem, 0);
    snd_mixer_selem_set_capture_dB_all(elem, 0, 0);

    snd_mixer_close(handle);
}