text:
Q: Reflections from Maven Mojo I'd like to use Google Reflections to scan classes from the compiled project from my Maven plugin. But plugins by default don't see the compiled classes of the project. From Maven 3 documentation I read:

Plugins that need to load classes from the compile/runtime/test class path of a project need to create a custom URLClassLoader in combination with the mojo annotation @requiresDependencyResolution.

Which is a bit vague to say the least. Basically I would need a reference to a classloader that loads the compiled project classes. How do I get that?
EDIT:
Ok, the @Mojo annotation has requiresDependencyResolution parameter, so that's easy but still need the correct way to build a classloader.

A: @Component
private MavenProject project;

@SuppressWarnings("unchecked")
@Override
public void execute() throws MojoExecutionException {
    List<String> classpathElements = null;
    try {
        classpathElements = project.getCompileClasspathElements();
        List<URL> projectClasspathList = new ArrayList<URL>();
        for (String element : classpathElements) {
            try {
                projectClasspathList.add(new File(element).toURI().toURL());
            } catch (MalformedURLException e) {
                throw new MojoExecutionException(element + " is an invalid classpath element", e);
            }
        }

        URLClassLoader loader = new URLClassLoader(projectClasspathList.toArray(new URL[0]));
        // ... and now you can pass the above classloader to Reflections

    } catch (ClassNotFoundException e) {
        throw new MojoExecutionException(e.getMessage());
    } catch (DependencyResolutionRequiredException e) {
        new MojoExecutionException("Dependency resolution failed", e);
    }
}


text:
Q: Auto Arrange UIViews when adding them programmatically? I want to add programmatically an unknown number of sub views into a UIView. Is it possible to use auto layout to auto arrange these subviews, like the below picture:

I am using iOS8, objective-c, XCode, iPad
Thanks,

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to login with application user in jboss 7.2 using jboss-cli? I am asking this question because there were recently some password changes to the user. I am trying to figure out the most current password which means, I have to try both. The application for this has not been deployed yet, so I need a way to validate this in Jboss itself. I am using JBOSS AS 7.2.

A: as far as I know, jboss-cli only allows authentication for users in ManagementRealm by default, so probably the easiest way is to check the properties files.
You say you have two passwords, which means there is not much work to do:

*

*Open JBOSS_HOME/standalone/configuration/application-users.properties

*Notice the instructions: username=MD5("username:ApplicationRealm:password")

*Try to hash your user with both passwords and check which of the hashes is present in the properties file.
Best regards
Jan


text:
Q: How to optimize number of threads per number of cores I'm trying to get a better idea of how many threads should run on n number of cores. I know this a complicated question in which the answer depends on a number of factors, such as how much shared state there is, and how much sleeping and waiting on resources each thread does.
To simplify things, let's say we have 2 cores and just one process that can divide its work into threads with no shared state. Let's say each thread just performs computation after computation with no sleeping and no waiting on resources. Would the ideal number of threads in this case be 2?
Let's complicate things a bit and say that the threads have to do some sort of disk I/O. How does this change our answer? I would think that we could have more than 2 cores in this case.
Or let's say they don't do any sleeping or waiting on resources, but instead there's some memory that they both have access to that requires synchronization. How does this change our answer? I would think that in this case we may actually prefer 1 thread over 2, depending on how much synchronization is required.

A: This is a hard question to answer in the general matter. It really depends on more specifics in the case. What to remember is that it costs to do context-switches - if you're only doing computations it would be wasteful to have 2 threads running on one core (as you wouldn't really gain anything - only lose in the context switches). On the other hand if you are waiting for resources and at the same time can continue with other calculations, it is a good idea to have a thread wait for those resources to not make the entire execution lag behind.

A: When it comes to IO you don't think in terms of threads per core. You think in terms of threads per physical device. Each individual device has different optimal DOP's (magnetic disk = 1, SSD at least 4, network much higher).
For CPU bound work the optimal number is 1 (per core).
In mixed cases or cases where it is more complicated than that no general answer can be given. The system can behave in surprising ways (like collapsing under load!). The approach here is to test different DOPs and use the best. Generally, there will be exactly one optimum while both 1 and infinity perform much worse. So you only need to find the single maximum which is quite easy.


text:
Q: use sphinx to generated pdf by latex, how to change the chapter font size and secion font size? When I use sphinx to generated pdf , I do not know how to set package to change the chapter font size and section font size,main text font size??
How can I do this ?


text:
Q: What does "No Ads VAST response after one or more Wrappers" mean exactly? When working with the VAST (and VPAID) protocols for showing video advertisements, the following error message occurs quite often:
"No Ads VAST response after one or more Wrappers"
While I have been searching the internet a lot about this, the official VAST documentation or any other resource do not seem to provide any information about the exact meaning of this error message.
Actually, most error messages are not explained like the error message itself should be self explanatory. For me they are not.
For example the Google DFP documentation:
https://support.google.com/dfp_premium/answer/4442429?hl=en
Could anyone provide me with a clear explanation of this error message in specific, and maybe a resource that does explain all VAST response codes in more depth?

A: The response means exactly what it says.
After one or more VAST wrapper requests, with a final outcome of zero ads, the player should respond with 303 - No ads VAST response after one or more Wrappers. Also includes number of empty VAST responses from fallback.
A successful VAST response contain 0..n Ads and therefore 0..n wrappers. If each of these ads in a wrapper chain is a wrapper and ...

*

*each of the wrappers resources finally responded with a

*

*VAST of 1..n wrapper or

*empty VAST or

*timeout or

*basically everything except for an non-wrapper Ad and

*the wrapper limit (depth) wasn't reached ...

the player should respond with that error.

Example:  Ignoring specific VAST version implementation details
Resource 0

<VAST>
    <Ad><Wrapper><VASTAdTagURI>http://[resource_1]...</VASTAdTagURI></Wrapper></Ad>
    <Ad><Wrapper><VASTAdTagURI>http://[resource_2]...</VASTAdTagURI></Wrapper></Ad>
</VAST>

Resource 1

<VAST>
    <Ad><Wrapper><VASTAdTagURI>http://[resource_3]...</VASTAdTagURI></Wrapper></Ad>
</VAST>

Resource 2

<VAST></VAST>

Resource 3

<VAST></VAST>

@see VAST 3.0 - Section 2.4.1 and 2.4.2

2.4.2.1 Ad Server Details: <Error> Element
  An <Error> element is also provided at the root VAST level and is primarily used to report a "No Ad" response. See section 2.4.2.4 for more information.
2.4.2.4 No Ad Response
  When the ad server does not or cannot return an Ad, the VAST response should contain only the root <VAST> element with optional <Error> element.
  The VAST <Error> element is optional but if included, the video player must send a request to the URI provided when the VAST response returns an empty InLine response after a chain of one or more wrapper ads. If an [ERRORCODE] macro is included, the video player should substitute with error code 303.
  Besides the VAST level <Error> resource file, no other tracking resource requests are required of the video player in a nodad response in either the Inline Ad or any Wrapper ads.


text:
Q: Error VT-x not available for Vagrant machine into a Virtualbox In my MacBook Pro I installed an ubuntu machine (64 bits) via VirtualBox.
Inside this Ubuntu machine, I installed the Vagrant to be able to create 3 VMs (VirtualBox) via command line in the terminal.
I give the "vagrant up" command to create the machines, but I get back the error message "VT-x is not available".
It seems that my device is not enabled to do virtualization, however, in the settings of my VirtualBox, everything is correct ... at least, I followed the step by step.
Is the problem on my mac? Have you seen this error? I have seen in some cases that you have to enable virtualization in BIOs, but my Ubuntu VM opens normally. I also checked out in other post that is not possible to get a VirtualBox VM inside a VirtualBox VM, is this correct?
#Vagrantfile

Vagrant.configure("2") do |config|

#DEVOPS
  config.vm.define "devops" do |devops|
    devops.vm.hostname = "devops"
    devops.vm.box = "ubuntu/xenial64"
    devops.vm.box_check_update = false
    devops.vm.network "private_network", ip: "192.168.99.10", dns:
"8.8.8.8"

    devops.vm.provider "virtualbox" do |dev|
    dev.memory = "4092"
   end
  end

#DOCKER
  config.vm.define "docker" do |docker|
    docker.vm.hostname = "docker"
    docker.vm.box = "ubuntu/xenial64"
    docker.vm.box_check_update = false
    docker.vm.network "private_network", ip: "192.168.99.20", dns:
"8.8.8.8"

    docker.vm.provider "virtualbox" do |doc|
    doc.memory = "2048"
   end
  end

#AUTOMATION
  config.vm.define "automation" do |automation|
    automation.vm.hostname = "automation"
    automation.vm.box = "centos/7"
    automation.vm.box_check_update = false
    automation.vm.network "private_network", ip: "192.168.99.30",
dns: "8.8.8.8"

    automation.vm.provider "virtualbox" do |aut|
    aut.memory = "4092"
   end
  end

  config.vm.provision "shell", inline: <<-SHELL
    test -d /root/.ssh/ || mkdir /root/.ssh/
    echo "-----BEGIN RSA PRIVATE KEY-----
--- PRIVATE KEY MASKED ----
-----END RSA PRIVATE KEY-----" > /root/.ssh/id_rsa
    echo "ssh-rsa
---MASKED--- > /root/.ssh/authorized_keys
    chmod 600 /root/.ssh/id_rsa
  SHELL
end


text:
Q: What distribution does the mean of a random sample from a Uniform distribution follow? For example, let $X_1,\cdots,X_n$ be a random sample from $f(x|\theta)=1,\theta-1/2 < x < \theta +1/2$.
Clearly, $X_i \sim U(\theta-1/2 , \theta +1/2)$. Some intuition would suggest that $\bar{X}\sim f(x|\theta)=1,\theta-1/2 < x < \theta +1/2$. However, I do not think that this is actually correct. What distribution would $\bar{X}$ follow?

A: No, it's not uniform. Intuitively, you would expect that the uncertainty over $\bar X$ decreases as $n$ increases. Also the central limit theorem suggests, as $n$ increases, the distribution approaches normal distribution. Which means, you'll have a peak around $\theta$, and it's going to narrow down as $n\rightarrow\infty$.
For a simple counter-example, if $n=2$, $\bar X$ is going to have triangular distribution, with its center at $\theta$, with the same limits.

A: The Irwin-Hall distribution is the distribution of a sum of $n$ uniform random variables. Therefore, an analytic expression for the density of the mean of $n$ uniform random variables is
$$\frac{1}{n!} \sum_{k=0}^n (-1)^k \binom{n}{k} (x-k)_+^{n-1}$$
By shifting this expression, you get the density of yours.

A: This is one case where using Fourier transforms makes for simple solutions.  Your density function is $\mathrm{rect}(\theta)$ with its Fourier transform $\mathrm{sinc}(f)$ (where $\mathrm{sinc}(f)=\frac{\sin \pi f}{\pi f}$ with the obvious continuation $\mathrm{sinc}(0)=1$).  Adding $n$ variables with that distribution leads to convolving the distribution $n$ times with itself (and dividing by $n$), so the resulting distribution has the Fourier transform $\bigl(\mathrm{sinc}(f)\bigr)^n\over n$.  Doing the inverse transform then delivers
$$\int_{-\infty}^\infty \cos(2\pi f\theta){\bigl(\mathrm{sinc}(f)\bigr)^n\over n}\,\mathrm{d}f$$.  In contrast to the piece-wise defined function in the $\theta$ domain, this is a single expression and thus properties like the moments of the function can be derived from this representation through the Fourier domain.

A: First, you might want to look at Wikipedia on Irwin-Hall distribution.
Unless $n$ is very small $A = \bar X =
\frac{1}{n}\sum_{i=1}^{n} X_i,$ where
$X_i$ are independently $\mathsf{Unif}(\theta-.5,\theta+.5)$ has $A \stackrel{aprx}{\sim}\mathsf{Norm}(\mu = \theta, \sigma = 1/\sqrt{12n}).$
[The approximation is quite good for $n \ge 10.$ In fact, in the early days of computation when it was expensive to do operations other than pain arithmetic, a common way to simulate a standard normal random variable was to evaluate $Z = \sum_{1=1}^{12} X_i - 6,$ where $X_i$ were generated as independently standard uniform.]
The following simulation in R uses a million samples of size $n = 12$ with $\theta = 5.$
set.seed(2020)  # for reproducibility
m = 10^6;  n = 12;  th = 5
a = replicate(m, mean(runif(n, th-.5,th+.5)))
mean(a);  sd(a); 1/sqrt(12*n)
[1] 5.000153      # aprx 5
[1] 0.08339642    # aprx 1/12
[1] 0.08333333    # 1/12

Thus the mean and standard deviations are consistent
with the results of the Central Limit Theorem.
In R, the Shapiro-Wilk normality test is limited to
5000 observations. We show results for the first 5000
simulated sample means. Those observations are consistent with a normal distribution.
shapiro.test(a[1:5000])

    Shapiro-Wilk normality test

data:  a[1:5000]
W = 0.99979, p-value = 0.9257

The histogram below compares the simulated distribution of $\bar X$ with the PDF of $\mathsf{Norm}(\mu=5, \sigma=1/12).$
hdr = "Simulated Dist'n of Means of Uniform Samples: n = 12"
hist(a, br=30, prob=T, col="skyblue2", main=hdr)
 curve(dnorm(x, 5, 1/sqrt(12*n)), add=T, lwd=2)
 abline(v=5+c(-1,1)*1.96/sqrt(12*n), col="red")

This suggests that $$P\left(-1.96 < \frac{\bar X - \theta}{1/\sqrt{12n}} < 1.96\right) = 0.95,$$ so that a very good approximate 95% confidence interval for $\theta$ is of the form $(\bar X \pm 1.96/\sqrt{12n}).$


text:
Q: Problems with Directx Header file Hi I am trying to use the Visual Studio 2013 Graphics debugger and tried to create an event group. Bute I ran into a problem while including d3d11_1.h header file . I copied the header to my include directory in June 2010 SDK's include file. But the following error pops up.
1>c:\program files (x86)\microsoft directx sdk (june 2010)\include\dxgi1_2.h(1271): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files (x86)\microsoft directx sdk (june 2010)\include\dxgi1_2.h(1271): error C2143: syntax error : missing ',' before '*'
1>c:\program files (x86)\microsoft directx sdk (june 2010)\include\dxgi1_2.h(1275): error C2061: syntax error : identifier 'DXGI_RGBA'
I am have also copied over dxgi1_2.h in the include directory . What is causing this problem ? Is it a conflict problem ? Can any one give me any pointer on how to create this event group ?

A: The error was due to the header orders, you placed the DirectX headers before windows headers, so some types defined in windows.h was not visible when the compiler process directx headers.
You should include windows.h in prior to the direct3d headers.
#include <windows.h>
#include <d3d11_1.h>
...


text:
Q: A question on difference between an computationally created sinusoid signal and the recorded signal (when played out through a speaker)? I have created the following signal(in Matlab), a 5000 Hz sinusoid multiplied with a bump (just to limit it in time) so that it forms a short beep. Now if i observe the spectrum of this computationally created signal (in matlab) there is an impulse like structure at 5000Hz and nothing else.
Now i perform this experiment. I play this signal in matlab through a sound card into a speaker and record the sound played on the speaker through a microphone. The surprising thing is that if i observe the spectrum of this recorded signal, i find a impulse like structure at 5000Hz as expected but there is a another impulse like structure of much lower amplitude at 10000Hz and an even much smaller one at 15000Hz. I wonder how it can be explained.
When I repeated this experiment with 2000Hz I found same observation at 4000Hz and 8000Hz.

A: What you are seeing are harmonics. (Multiples of the fundamental frequency). These indicate that your system has distortion. Harmonic distortion, loosely speaking, is a change in the shape of the input due to a nonlinear behavior in the signal chain. It adds frequencies which are not present in the original signal.
Inside Matlab, your generated waveform is pure data, and so it has no distortion (except for the tiny errors in the floating-point representation). The distortion happens in your analog chain: in your audio interface output, amplifier, speaker, microphone, microphone preamp, audio interface input.
See if you can fine tune the gains of these components to reduce these harmonics. The gain structure over multiple parts in the signal path should be balanced. Loosely speaking, you don't want some part not having enough gain and cranking up another part to compensate.
Also another thing to see is whether the distortion goes away if you make the signal much smaller. Some forms of distortion stay loud as the signal is decreased (e.g. cross-over distortion in a class-AB amplifier.). Some forms of distortion diminish or go away. (e.g. clipping.)
You need, surprise surprise, quality hardware if you want to recapture a pure signal without distortion. How much did you spend on your audio interfaces, speakers, mic, etc.
A professional quality audio interface can set you back $1000 and up. Good set of studio monitor speakers, likewise. Good microphone: hundred bucks minimum.

A: Not much to add to Kaz's answer, except for maybe a note on simulating distortion inside Matlab. You can experiment more things about distortion, and faster, if you simulate it within Matlab. You can do this until you grasp some intuition of it, and then once in a while do real-life experiments (which take longer).
For instance, if \$y\$ is your undistorted signal (the one with the pure sinusoid), whose amplitude goes from -1 to +1, you can easily create a distorted version \$y_d\$ of it, doing this:
% This is jus one possible way to distort a signal.
gamma=0.8;  % gamma=1 means no distortion.
yd=sign(y).*(abs(y).^gamma);

And you would see something like this, in Matlab:

(Spectra in dB, and using a Blackman Harris window.)
For this type of distortion, the only harmonics created are odd (odd multiples of 5 kHz). Other types create odd and even harmonics.

A: If you're getting harmonics, that suggests the presence of distortion.  One way to test for distortion by ear is to generate a signal containing two sine waves, one at a fixed amplitude and frequency (e.g. 2000Hz) and the other one sweeping from e.g. 300Hz to 800Hz.  In the absence of distortion, only be one sweeping frequency should be audible, but the presence of distortion will usually create other frequencies, some of which will sweep in the opposite direction.  A small amount of distortion may not cause noticeable aliasing, but the presence of aliasing is a dead giveaway to distortion.


text:
Q: jQuery lightbox multiple items to look like Mac dashboard I'm wondering if it's possible in any existing lightbox to pop up a look similar to the mac dashboard where multiple divs could be "on" in the front with the main webpage with a gray overlay.
Basically something where a user clicks an icon on the main webpage to call, and then 4 separate content boxes are popped on top, but not in a window like a gallery.
I'm thinking the top background used could be set to transparent and the individual items could be divs on the popped area, but before I reinvent the wheel, I thought I'd see if there's something like this that I just haven't found in my searches.

A: I ended up using colorbox with a background behind my divs. It doesn't look like the mac with items having the bg behind them showing between them, but after talking to the designer I'm working with, that wasn't something they really needed anyhow. I think it MAY be possible changing some of the CSS though for the bg of the "popped" window. Colorbox seems to be pretty nice about making it clear what the CSS is doing and there are multiple example skins.


text:
Q: Old file fragment understanding - For those up for a challenge I am trying to grab PVS (rendering with line of sight) information from an old game format. It has documentation and I have been able to translate everything into C++ code up to this point. This part however confuses the heck out of me. I spent a few hours today trying to understand where to start but alas, I have nothing. Again, this is only for those that might be up for a challenge or can lend some advice or even pseudocode for how I would accomplish this.
Thank you
Data6 entries (There are Size6 of these):
Data6Size1 : WORD
Tells the number of entries in the Data6Data field.
Data6Data : Either BYTEs or WORDs
This is a complicated field. It contains run-length-encoded data that tells the client which regions are "nearby". The purpose appears to be so that the client can determine which mobs in the zone have to have their Z coordinates checked, so that they will fall to the ground (or until they land on something). Since it's expensive to do this, it makes sense to only do it for regions that are visible to the player instead of doing it for all mobs in the entire zone (repeatedly).
I've only encountered data where the stream is a list of BYTEs instead of WORDs. The following discussion describes RLE encoding a BYTE stream.
The idea here is to form a sorted list of all region IDs that are within a certain distance, and then write that list as an RLE-encoded stream to save space. The procedure is as follows:

*

*Set an initial region ID value to zero.

*If this region ID is not present in the (sorted) list, skip forward to the first one that is in the list. Write something to the stream that tells it how many IDs were skipped.

*Form a block of consecutive IDs that are in the list and write something to the stream that tells the client that there are this many IDs that are in the list.

*If there are more region IDs in the list, go back to step 2.
When writing to the stream, either one or three bytes are written:

*

*0x00..0x3E skip forward by this many region IDs

*0x3F, WORD skip forward by the amount given in the following 16-bit WORD

*0x40..0x7F skip forward based on bits 3..5, then include the number of IDs based on bits 0..2

*0x80..0xBF include the number of IDs based on bits 3..5, then skip forward based on bits 0..2

*0xC0..0xFE subtracting 0xC0, this many region IDs are nearby

*0xFF, WORD the number of region IDs given by the following WORD are nearby

It should be noted that the values in the range 0x40..0xBF allow skipping and including of no more than seven IDs at a time. Also, they are not necessary to encode a region list:     they merely allow better compression.

A: This is my attempt to implement that unpacker. Not tested as there is no example data to test it with... (not even compiled, actually)
std::vector<int> regions(std::vector<unsigned char>& data6)
{
    int rp = 0, sz = data6.size();
    std::vector<int> result;
    int current_id = 0;
    while (rp < sz)
    {
        int c = data6[rp++];
        if (c <= 0x3E)
        {
            // 0x00..0x3E : skip forward by this many region IDs
            current_id += c;
        }
        else if (c == 0x3F)
        {
            // 0x3F WORD skip forward by the amount given in the following 16-bit WORD
            if (rp + 2 > sz) throw std::runtime_error("Invalid data");
            int count = data[rp] + (data[rp + 1] << 8); // (NOTE: May be H/L ?)
            rp += 2;
            current_id += count;
        }
        else if (c <= 0x7F)
        {
            // 0x40..0x7F skip forward based on bits 3..5,
            // then include the number of IDs based on bits 0..2
            int keep = (c & 7);
            int skip = (c >> 3) & 7;
            current_id += skip;
            for (int i=0; i<keep; i++)
                result.push_back(current_id++);
        }
        else if (c <= 0xBF)
        {
            // 0x80..0xBF include the number of IDs based on bits 3..5,
            // then skip the number of IDs based on bits 0..2
            int skip = (c & 7);
            int keep = (c >> 3) & 7;
            for (int i=0; i<keep; i++)
                result.push_back(current_id++);
            current_id += skip;
        }
        else if (c <= 0xFE)
        {
            // 0xC0..0xFE subtracting 0xC0, this many region IDs are nearby
            int keep = c - 0xC0;
            for (int i=0; i<keep; i++)
                result.push_back(current_id++);
        }
        else
        {
            // 0xFF WORD the number of region IDs given by the following WORD are nearby
            if (rp + 2 > sz) throw std::runtime_error("Invalid data");
            int count = data[rp] + (data[rp + 1] << 8); // (NOTE: May be H/L ?)
            rp += 2;
            for (int i=0; i<count; i++)
                result.push_back(current_id++);
        }
    }
    return result;
}

I assumed that WORDs are encoded as low/high, but may be it's the opposite...


text:
Q: Draw Graph with upper and lower limit I am attempting to draw a graph with a slope of 200,000 that becomes "saturated" at $y= \pm 10$. Essentially, the graph is of the form $y=200000x$. However, I have been unsuccessful in getting it to level off at the y bounds. I want the graph to become a horizontal straight lines at those values, like this, where my A would be 200000 and my Vcc values would be $\pm 10$:

Thank you!

A: x0 = First[x /. Solve[2 10^5 x == 10]]

1/20000

y[x_] := Piecewise[{{2 10^5 x, -x0 < x < x0}, {10, x >= x0}, {-10, x <= x0}}]

plot = Plot[y[x], {x, -2 x0, 2 x0}, Frame -> True]

Or in another way, using Clip as requested by C. E.:
Plot[Clip[200000 x, {-10, 10}], {x, -2 x0, 2 x0}, Frame -> True]

which gives the same plot as above.


text:
Q: Would Harry still be a Parselmouth at the end of the Deathly Hallows? Near the end of Harry Potter and the Deathly Hallows:

 Voldemort "kills" Harry, destroying the part of his own soul that was in Harry.

Dumbledore tells us before this that:

Part of Lord Voldemort lives inside Harry, and it is that which gives him the power of speech with snakes, and a connection with Lord Voldemort's mind that he has never understood.

Given the above, does that mean that Harry would have lost his ability to speak with snakes at the end of the book? Or would his own mind have learnt Parseltongue from the thing that gave it to him, so that when that thing was gone he would still know how to talk to snakes? I don't think any mention of this is made in the book, but I'm very curious to know. It would be a shame if Harry was no longer a Parselmouth.

A: According to JK Rowling, he lost that ability.
This is mentioned in the following link:
http://www.accio-quote.org/articles/2007/0730-bloomsbury-chat.html

A: YES. Strictly speaking, if we were addressing the title's question

Would Harry still be a Parselmouth at the end of the Deathly Hallows?

The answer is yes, because to be able to speak Parseltongue doesn't imply to be able to say new words - as long as you can say/remember some it is fine - and Ron proved it.
What Harry can't do anymore is say new words he hasn't said/learnt before. But strictly speaking, he can still speak Parseltongue - words he has used many times, like "Open."
So right now, both Harry and Ron can speak Parseltongue :).
Voldemort's soul gave Harry a full vocabulary of Parseltongue. Harry happened to learn some of it. When Voldemort's soul was taken away, the vocabulary goes away, but the words that Harry did learn (using his brain) are obviously kept - they're memories. If you think about it, it is pretty much the same as learning a new language. Therefore, Harry did learn Parseltongue and can speak (some) Parseltongue. Thus the answer to your question is yes.

A: No, Harry loses the ability to speak Parseltongue once Voldemort is dead:

Nigel: Can Harry speak Parseltongue when he is no longer a Horcrux?
J.K. Rowling: No, he loses the ability, and is very glad to do so.

J.K. ROWLING WEBCHAT - 07.30.07 - THE LEAKY CAULDRON
This quote from J.K. Rowling doesn't indicate that Harry retains any knowledge of Parseltongue after Voldemort is dead and, frankly, it sounds like he'd be happy to forget any words he might have retained at one time in his young life. I think it's important to remember that when Harry spoke Parseltongue -- particularly in Chamber of Secrets -- it didn't sound like anything other than English to him. This was true even when he heard other Parselmouths speak Parseltongue. Read the chapter The House of Gaunt in Half-Blood Prince -- it demonstrates how Parseltongue didn't sound any different to Harry than English did. Now when Harry revisited the Gaunt's shack on the day Voldemort (then Tom Riddle Jr) showed up, when viewing Dumbledore's memory, Harry did somehow know it was Parseltongue Tom Riddle and Morphin Gaunt were speaking.


text:
Q: How to remove all special char except $ (dollar sign) using php? How to remove all special char except $ (dollar sign) using php ?
I tried use this
$string = preg_replace("/[^ \w]+/", "", $string);

But all special char include $ (dollar sign) was remove
i tried this too  $string = preg_replace("/$[^ \w]+/", "", $string);
But not work.
I want to store $ (dollar sign) , How can i do that ?

A: You're accepting so few characters that you could just "spell them out": everything that is not A-Z0-9$ -> replace.
<?php
$input= '_~!@#$%^&*()+  babnQWWWEWQEJ';
echo preg_replace('/[^A-Z0-9$]+/', '', $input);


text:
Q: PostProcessing in XNA 4 I am trying to implement a PostProcessing manager in my 3D engine, but I'm failing.  I keep getting the first texture just slapped over the top of everything else.  I'm just creating a new RenderTarget2D using the GraphicsDevice's Viewport in order to set the Width, Height etc. but it just overwrites everything.
Does anyone have any ideas?  My understanding of the RenderTarget2D was that it took a "snapshot" of the screen and then I can redraw that later.

A: Ensure that you aren't setting your RenderTarget2D more than once, also use the GraphicsDevice's viewport to create your RenderTarget2D


text:
Q: How to find de Mean and Variance of a defined distribution I would like to find the Mean and Variance expressions for a Poisson-Lognormal Distribution
$$f(x;\mu,\sigma)=\frac{1}{x!\sigma\sqrt{2\pi}}\int_{0}^{\infty}\lambda^{x-1} e^{-\lambda} e^{\frac{(log(\lambda-\mu)^2}{2\sigma^2} }\text{d}\lambda$$
I have been checking the Expectation[] command to find the expected value of predefined Mathematica pdfs but I do not know how to apply to this expression, and to find the $Var(X)=E[X^2]-E[X]^2$.

A: I suspect that you will need to use numeric techniques.
Clear["Global`*"]

f[x_Integer?NonNegative,
  μ_?(NumericQ[#] && Element[#, Reals] &),
  σ_?(NumericQ[#] && # > 0 &)] := NIntegrate[
   E^-λ λ^(x -
       1) E^(-(Log[λ] - μ)^2/(2 σ^2)),
   {λ, 0, ∞}]/(Sqrt[2 π] σ x!)

mean[μ_?(NumericQ[#] && Element[#, Reals] &),
  σ_?(NumericQ[#] && # > 0 &)] := mean[μ, σ] =
  NSum[x*f[x, μ, σ], {x, 0, ∞}, NSumTerms -> 50,
   WorkingPrecision -> $MachinePrecision]

var[μ_?(NumericQ[#] && Element[#, Reals] &),
  σ_?(NumericQ[#] && # > 0 &)] := var[μ, σ] =
  Module[{m = mean[μ, σ]},
   NSum[(x - m)^2*f[x, μ, σ], {x, 0, ∞}, NSumTerms -> 50,
     WorkingPrecision -> $MachinePrecision]]

mean[0, 1]

(* 1.6487197 *)

var[0, 1]

(* 6.318 *)


text:
Q: Unable to access the array object that contains @ sign I have an array that contains @sign in the object. I can't access that
Actually I'm parsing XML into array
The print_r output is below
[link] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [type] => text/html
                                    [href] => http://www.livingsocial.com/cities/1964-klang-valley-kuala-lumpur/deals/393950-2-pax-steamboat-set-2-iced-lemon-tea
                                    [rel] => alternate
                                )

                        )

$entry->link->@attributes->href
Can't access

A: You have to use the attributes() method to get attributes from a SimpleXMLElement object
 $entry->link->attributes();

If you want to get the href attribute as string you can do the following:
$href = $entry->link->attributes()->href->__toString();


text:
Q: Multiple font-awesome icons sharing a background gradient I've been crawling the web for about 2 hours now, trying to find a solution. So I apologise, my starting code isn't overly helpful.
I've tried using background-clip, multiple.js, fill, and just can't get the effect I'm looking for.
In fact, I currently can't even replicate: https://stackoverflow.com/a/56916981 with Font Awesome 5 and the pesky SVGs.
Here's where I'm currently at:

body{
  font-size:150px;
}
svg {
background: -webkit-linear-gradient(225deg, rgb(251, 175, 21), rgb(251, 21, 242),
rgb(21, 198, 251)) 0% 0% / 300% 300%;
-webkit-text-fill-color: transparent;
animation: 2s ease 0s infinite normal none running fontgradient;
-webkit-animation: fontgradient 2s ease infinite;
-moz-animation: fontgradient 2s ease infinite;
animation: fontgradient 2s ease infinite;
}

@-webkit-keyframes fontgradient {
0%{background-position:0% 92%}
50%{background-position:100% 9%}
100%{background-position:0% 92%}
}
@-moz-keyframes fontgradient {
0%{background-position:0% 92%}
50%{background-position:100% 9%}
100%{background-position:0% 92%}
}
@keyframes fontgradient {
0%{background-position:0% 92%}
50%{background-position:100% 9%}
100%{background-position:0% 92%}
}

Even if the clipping above worked, it still wouldn't quite be the right effect. I want a single background (by that I mean it's positioning) to appear across all 3 icons, not 3 gradients with a position that's reset each time.
And here's all I'm trying to achieve (Animation is simply a bonus):

A: Well with the version that you are using, you will find the icons displayed as svg and the background-clip effect will not work.
You can use the older version where elements are rendered as content inside pseudo elements (:before), and set a parent for the i tags to get a single gradient across the icons:

body {
  font-size: 150px;
}

#parent {
  display: inline;
  background: -webkit-linear-gradient(225deg, rgb(251, 175, 21), rgb(251, 21, 242), rgb(21, 198, 251)) 0% 0% / 300% 300%;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  animation: 2s ease 0s infinite normal none running fontgradient;
}

i {
  font-size: 5rem;
  font-style: normal;
  font-family: fontawesome;
}

@-webkit-keyframes fontgradient {
  0% {
    background-position: 0% 92%
  }
  50% {
    background-position: 100% 9%
  }
  100% {
    background-position: 0% 92%
  }
}

@-moz-keyframes fontgradient {
  0% {
    background-position: 0% 92%
  }
  50% {
    background-position: 100% 9%
  }
  100% {
    background-position: 0% 92%
  }
}

@keyframes fontgradient {
  0% {
    background-position: 0% 92%
  }
  50% {
    background-position: 100% 9%
  }
  100% {
    background-position: 0% 92%
  }
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

A: Don't use the SVG version and use the CSS one then consider background-position to shift the background for each icon to create a continuous one:

body {
  font-size: 100px;
}

i {
  float:left;
  background:
     linear-gradient(225deg, rgb(251, 175, 21), rgb(251, 21, 242), rgb(21, 198, 251))
     0 0 / 3em 100%;
  -webkit-background-clip:text;
  background-clip:text;
  width:1em;
  text-align:center;
  -webkit-text-fill-color: transparent;
  animation: fontgradient 2s ease infinite;
}
.fa-instagram {
  background-position:-1em 0;
}
.fa-facebook-f {
  background-position:-2em 0;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.12.0/css/all.css">

A: Here you go with a solution

body{
  font-size:150px;
}

i.fab {
  font-size: 5rem;
  font-style: normal;
  font-family: fontawesome;
  background: -webkit-linear-gradient(225deg, rgb(251, 175, 21), rgb(251, 21, 242),
  rgb(21, 198, 251)) 0% 0% / 300% 300%;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  animation: 2s ease 0s infinite normal none running fontgradient;
  -webkit-animation: fontgradient 2s ease infinite;
  -moz-animation: fontgradient 2s ease infinite;
  animation: fontgradient 2s ease infinite;
}
@-webkit-keyframes fontgradient {
  0%{background-position:0% 92%}
  50%{background-position:100% 9%}
  100%{background-position:0% 92%}
}
@-moz-keyframes fontgradient {
  0%{background-position:0% 92%}
  50%{background-position:100% 9%}
  100%{background-position:0% 92%}
}
@keyframes fontgradient {
  0%{background-position:0% 92%}
  50%{background-position:100% 9%}
  100%{background-position:0% 92%}
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Are you looking for this?


text:
Q: Convergence of a series with integral inside I'm trying to determine whether the series
$$\sum_{n=0}^{+\infty}\int_0^{\frac{\pi}{2}}\sin^n(x)dx$$
converges, diverges or is indeterminate.
Since $\sin(x)\le 1\;\forall x \in \mathbb{R}$ and thus $\sin^n(x)\le 1^n=1 \; \forall n \in \mathbb{N}$ I tried with the comparison test but with no luck. Does anyone know how to solve this exercise?
Thanks in advance.

A: For first, the hard way. Through the Beta function and the Euler product for the $\Gamma$ function:
$$ \int_{0}^{\pi/2}\sin(x)^n\,dx = \frac{\Gamma\left(\frac{1}{2}\right)\Gamma\left(\frac{n+1}{2}\right)}{2\cdot\Gamma\left(1+\frac{n}{2}\right)}\sim\frac{C}{\sqrt{n}}\tag{1}$$
hence the series is not convergent by the $p$-test. The easy way: by assuming that the series is converging, we are allowed to switch the series and the integral, reaching:
$$ \int_{0}^{\pi/2}\frac{dx}{1-\sin x}=\int_{0}^{1}\frac{dx}{(1-x)\sqrt{1-x^2}}=\int_{0}^{1}\frac{dx}{x\sqrt{x(2-x)}}\tag{2}$$
where the last integral is not converging since the integrand function has a non-integrable singularity in a right neighbourhood of zero. The inequality:
$$ \int_{0}^{\pi/2}\frac{dx}{1-\sin x}=\int_{0}^{\pi/2}\frac{dx}{1-\cos x}=\int_{0}^{\pi/2}\frac{dx}{2\sin^2\frac{x}{2}}\geq \int_{0}^{\pi/2}\frac{2\,dx}{x^2}\tag{3}$$
makes it trivial.

A: By drawing a picture, we note that for $0<x<\pi/2$,
$$ \frac{2}{\pi}x < \sin{x} < x. $$
In particular, therefore, we have
$$ \int_0^{\pi/2} \sin^n{x} \, dx > \int_0^{\pi/2} \left( \frac{2}{\pi} x \right)^n \, dx = \frac{1}{n+1}\frac{2}{\pi} \left( \frac{2}{\pi}\frac{\pi}{2} \right)^{n+1} = \frac{2}{\pi(n+1)}. $$
Hence
$$ \sum_{n=0}^{\infty} \int_0^{\pi/2} \sin^n{x} \, dx > \sum_{n=0}^{\infty} \frac{2}{\pi(n+1)}, $$
which of course diverges, so the original sum diverges.


text:
Q: How to exclude null-value fields when using Flexjson? I am serializing a class like this into JSON using Flexjson:
public class Item {
    private Long id;
    private String name;
    private String description;
    ...

    // Getters and setters
    ...
}

Many of the Item fields can be null (e.g., description). Consequently, when such an Item object is serialized using Flexjson, I get the following JSON:
 {"id":62,"name":"Item A","description":null,...}

Since, as I already mentioned, an Item object may contain many null-value fields, the outcoming JSON is longer than effectively needed. This is in so far a problem, because I would like to send the generated JSON from a web server to a mobile client over a wireless connection via WiFi, 3G, EDGE or GPRS (i.e., more bandwidth is required, which results in less speed).
Therefore, I wanted to ask how it is possible to (efficiently) exclude null-value attributes using Flexjson?
Thanks!

A: You can use the following transformer :
import flexjson.transformer.AbstractTransformer;

public class ExcludeTransformer extends AbstractTransformer {

  @Override
  public Boolean isInline() {
      return true;
  }

  @Override
  public void transform(Object object) {
      // Do nothing, null objects are not serialized.
      return;
  }
}

with the following usage :
new JSONSerializer().transform(new ExcludeTransformer(), void.class).serialize(yourObject)

Note that all null fields will be excluded.
Adding the Transformer by Path (vs by Class) is not supported as FlexJSON forces TypeTransformer for null values :
JSONContext.java : line 95 :
private Transformer getPathTransformer(Object object) {
    if (null == object) return getTypeTransformer(object);
    return pathTransformerMap.get(path);
}

A: I am a newbie,i had same problem and could not find any solution on source forge so i used regular expression to remove all the nulls from JSON String
/**
 * This Function removes all the key:value pairs from the Json String for which the value equals null
 * @param jsonStringWithNullKeys
 * @return jsonStringWithoutNullKeys
 */
public static String getJsonStringWithoutNullKeys(String jsonStringWithNullKeys)
{
    Pattern p = Pattern.compile( "([,]?\"[^\"]*\":null[,]?)+" );
    Matcher m = p.matcher( jsonStringWithNullKeys );
    StringBuffer newString = new StringBuffer( jsonStringWithNullKeys.length() );

    while( m.find() )
    {
        if( m.group().startsWith( "," ) & m.group().endsWith( "," ) ) m.appendReplacement( newString, "," );
        else
            m.appendReplacement( newString, "" );
    }
    m.appendTail( newString );
    return newString.toString();
}

A: I haven't tried out your situation exactly, but I believe the following should solve your problem:
Item item;
// Assign item here
JSONSerializer json = new JSONSerializer();
if ( item.description != null ) {
  json.exclude( field );
}
return json.serialize(item);

Clearly, you'd probably access the description field using a getter. Additionally, you might want to iterate your instance fields using reflection to exclude the null-fields.


text:
Q: How to get online/offline state of the opponent user when there is no internet connection using firebase I am working on chat application using Firebase, i need online, offline and last seen status of the user whom i am chatting with. I will get this status when user is connected to internet, when user doesn't have internet then it won't be updated in Firebase and it still shows online to offline user.
How to update Firebase database instantly when there is no internet connectivity?

A:
How to update firebase database instantly when there is no internet connectivity?

There is no way in which you can update a Firebase database while you are offline. When there is no internet connectivity on user's device it means that the user cannot reach Firebase servers, with other words no changes will be made on Firbease servers but, if you are using the following line of code:
FirebaseDatabase.getInstance().setPersistenceEnabled(true);

It means that you'll be able to query your the database even if you are offline. This is happening because Firebase creates a local copy of your database. Every change that is made while you are offline, will be updated on Firebase servers once you are back online. To be more clear, every client that is using a Firebase database and uses setPersistenceEnabled(true) maintains it's own internal (local) version of the database. When data is updated, it is first written to this local version of the database.
There is also a post on which I have answered a few minutes ago and I think you might be interested.

A: Try to add timestamp of both users to firebase at regular intervals .. if connection is down the last active time is shown .. so at both sides check the timestamp difference . If it is greater than some value then display as one user is offline .. makes sure both sides uses GMT time as standard


text:
Q: iOS 9.0 Xcode 8.3.3 MfiBtPrinterConnection.h streming bluetooth maxLength Zebra ZQ520 I'm using the Zebra printer sdk in particular I have a Zebra ZQ520.
I'm trying to send a string (in the proprietary language called "zpl") to the printer from my project in Xcode (Object-C).
Before this stage, I convert a * .pdf into a * .grf image I take the entire string and firing the printer. So far it has always worked, but if I take a somewhat more complex pdf, I get this error back.

ERROR - /BuildRoot/Library/Caches/com.apple.xbs/Sources/ExternalAccessory/ExternalAccessory-353.50.4/EAOutputStream.m:-[EAOutputStream
  write: maxLength:] - 283 failed to write because stream does not have
  space available

I checked that the connection I create comes from the MfiBtPrinterConnection.h class and with the instance, I create I can only touch two values with these methods setTimeToWaitAfterWriteInMilliseconds and setTimeToWaitAfterReadInMilliseconds. The SDK manual tells you to try to increase the time in case of writing problems. I tried up to 30 seconds but nothing. Unfortunately I do not have access to the sources.

A: I ran into this error today, although my content is different hopefully it will help you. I had to put my .write command on a background thread.
             var error:NSError?
             DispatchQueue.global(qos: .background).async {
                MfiBtPrinterConnection?.write(data, withOffset: 0, andWithLength: data.count - 1, error: &error)
                if error != nil {
                print("Error executing data writing \(String(describing: error))")
             }

Now my data prints like it should.


text:
Q: Reading only the words of a specific speaker and adding those words to a list I have a transcript and in order to perform an analysis of each speaker I need to only add their words to a string. The problem I'm having is that each line does not start with the speakers name.
Here's a snippet of my text file
BOB: blah blah blah blah
blah hello goodbye etc.

JERRY:.............................................
...............

BOB:blah blah blah
blah blah blah
blah.

I want to collect only the words from the chosen speaker(in this case bob) said and add them to a string and exclude words from jerry and other speakers. Any ideas for this?
edit:There are line breaks between paragraphs and before any new speaker starts.

A: Using a regex is the best way to go. As you'll be using it multiple times, you can save on a bit of processing by compiling it before using it to match each line.
import re

speaker_words = {}
speaker_pattern = re.compile(r'^(\w+?):(.*)$')

with open("transcript.txt", "r") as f:
        lines = f.readlines()
        current_speaker = None
        for line in lines:
                line = line.strip()
                match = speaker_pattern.match(line)
                if match is not None:
                        current_speaker = match.group(1)
                        line = match.group(2).strip()
                        if current_speaker not in speaker_words.keys():
                                speaker_words[current_speaker] = []
                if current_speaker:
                        # you may want to do some sort of punctuation filtering too
                        words = [word.strip() for word in line.split(' ') if len(word.strip()) > 0]
                        speaker_words[current_speaker].extend(words)

print speaker_words

This outputs the following:
{
    "BOB": ['blah', 'blah', 'blah', 'blah', 'blah', 'hello', 'goodbye', 'etc.', 'blah', 'blah', 'blah', 'blah', 'blah', 'blah', 'blah.'],
    "JERRY": ['.............................................', '...............']
}

A: Every time a speaker starts to speak, keep the current_speaker and decide what to do according to this speaker. Read the lines until the speaker changes.


text:
Q: Elasticsearch inline string replace seems to do nothing We have some legacy fields in Elastic search index, which cause us some troubles and we would like to perform a  string replace over the whole index.
For instance some old timestamps are stored in format of 2000-01-01T00:00:00.000+0100 but should be stored as 2000-01-01T00:00:00.000+01:00.
I tried to run following query:
POST /my_index/_update_by_query
{
    "script":
    {
        "lang": "painless",
        "inline": "ctx._source.timestamp = ctx._source.timestamp.replace('+0100', '+01:00')"
    }
}

I run the query within Kibana, but I always get a query timeout - I guess that is not necessarily bad considering the database is huge, however I never see the fields updated.
Is there a way to see the status of such query?
I also tried to create a search query for the update, but with no luck:
GET /my_index/_search
{
  "query": {
    "query_string": {
      "query": "*0100",
      "allow_leading_wildcard": true,
      "analyze_wildcard": true,
      "fields": ["timestamp"]
    }
  }
}

Which unfortunately always returns empty set - not sure what might be wrong.
What would be a correct way to achieve such update?

A: I would solve this using an ingest pipeline that you'll use to update your whole index.
First, create the ingest pipeline like below. What it does is detect documents which have a timestamp field ending with +0100 and then updates the timestamp to use the timezone with the correct format.
PUT _ingest/pipeline/fix-tz
{
  "processors": [
    {
      "dissect": {
        "if": "ctx.timestamp.endsWith('+0100')",
        "field": "timestamp",
        "pattern": "%{timestamp}+%{tz}"
      }
    },
    {
      "set": {
        "if": "ctx.tz != null",
        "field": "timestamp",
        "value": "{{timestamp}}+01:00"
      }
    },
    {
      "remove": {
        "if": "ctx.tz!= null",
        "field": "tz"
      }
    }
  ]
}

Then, when the pipeline is created, you just have to update your index with it, like this:
POST my_index/_update_by_query?pipeline=fix-tz&wait_for_completion=false

Once this has run completely, your index should be properly updated.


text:
Q: Asciidoclet for JavaDoc using Maven I'm working on writing documentation for my Java code using JavaDoc. I'm using IntelliJ as my IDE, and executing javadoc -d javadoc src/* -author -version -private as my command to generate HTML documentation from Java classes. So far, this has worked flawlessly.
However, I'm trying to use the AsciiDocs format to write my documentation in the Java classes, which I can do using AsciiDoclet. I'm using Maven, which I have never used before, to add the plugin for asciidoclet. Here's how that file looks:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Documentation</artifactId>
    <version>1.0-SNAPSHOT</version>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <version>2.9</version>
            <configuration>
                <source>1.7</source>
                <doclet>org.asciidoctor.Asciidoclet</doclet>
                <docletArtifact>
                    <groupId>org.asciidoctor</groupId>
                    <artifactId>asciidoclet</artifactId>
                    <!--suppress UnresolvedMavenProperty -->
                    <version>${asciidoclet.version}</version>
                </docletArtifact>
                <overview>src/main/java/overview.adoc</overview>
                <additionalparam>
                    --base-dir ${project.basedir}
                    --attribute "name=${project.name}"
                    --attribute "version=${project.version}"
                    --attribute "title-link=http://example.com[${project.name} ${project.version}]"
                </additionalparam>
            </configuration>
        </plugin>
    </plugins>
</build>

</project>

When I click 'Compile' in the Maven window, i get the following error:
Source option 5 is no longer supported. Use 6 or later.
Target option 1.5 is no longer supported. Use 1.6 or later.

And a warning that might not be a big deal:
File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!

Now, I don't know how to fix this issue, and I have looked for help but there is not that many resources/examples on how to do this. I'm also a bit confused on if I should still run javadoc -d javadoc src/* -author -version -private
once this plugin is working, or if I should run asciidoctor --destination-dir=asciidoc src/*.
Running the asciidoctor command did seem to understand what I was passing in (Java files instead of .adoc files), but the syntax didn't render correctly, probably due to the plugin issue.

A: Add the following to your maven build and see if it makes a difference:
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
    <maven.compiler.release>17</maven.compiler.release>
  </properties>

Use '17' if your java version is 17. Change it accordingly to your own version.
See if this works and let us know.


text:
Q: Problemas al mostrar datos en una plantilla blade Recientemente estoy viendo base de datos en laravel y vistas en blade pero al momento de mostrar la informacion de una tabla en un una extension de la plantilla base de blade se me desordena o no me muestra.
Esta es la plantilla base:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Practica DBt</title>

UNIVERSIDAD TECNICA DEL NORTE

FACULTAD DE INGENERIAS

EJERCICIOS DE BASE DE DATOS

        @yield("parte1")

        yield("parte2")

        yield("parte3")

Y esta es la extension:
@extends("base")
@section("parte1")

DATOS DE FACULTAD

@endsection

@section("parte2")
    @if(count($resultados))

              ID	NOMBRE	DECANO	SECRETARIA	UBICACION	TELEFONO	TELEFONO	CREACION	ACTUALIZACION

            @foreach($resultados as $fila)

                   @foreach($fila as $dato)
                      {{$dato}}
                   @endforeach

            @endforeach

   @endif
@endsection

Al momento de correr en el navegador se me muestra así:

Pero si le quito el @endsection final se muestra así:

La cuestión es que quiero que la tabla se coloque abajo del titulo, miro y miro y no encuentro el error. Necesito ayuda, gracias de antemano.
Nota: Los datos de la tabla son ficticios no se preocupen.


text:
Q: PHP json_encode - Strange behaviour Using json_encode to encode an array of dates, it sometimes does one thing, sometimes does another.
For example, if I'm trying to encode something like:
array(6) {
  [0]=>
  string(6) "Jun-24"
  [1]=>
  string(6) "Jun-25"
  [2]=>
  string(6) "Jun-28"
  [3]=>
  string(11) "Training-24"
  [4]=>
  string(6) "Jun-29"
  [5]=>
  string(6) "Jun-30"
}

It will output
["Jun-24","Jun-25","Jun-28","Training-24","Jun-29","Jun-30"]

However, when I try to encode something like:
array(17) {
  [0]=>
  string(6) "Jun-23"
  [1]=>
  string(6) "Jun-24"
  [2]=>
  string(6) "Jun-28"
  [3]=>
  string(11) "Training-24"
  [4]=>
  string(6) "Jun-29"
  [5]=>
  string(6) "Jun-30"
  [6]=>
  string(6) "Jul-06"
  [7]=>
  string(6) "Jul-07"
  [9]=>
  string(6) "Jul-09"
  [10]=>
  string(6) "Jul-16"
  [11]=>
  string(6) "Jul-17"
  [12]=>
  string(6) "Jul-20"
  [13]=>
  string(6) "Jul-23"
  [14]=>
  string(6) "Jul-24"
  [15]=>
  string(6) "Jul-30"
  [16]=>
  string(6) "Aug-01"
  [17]=>
  string(6) "Aug-05"
}

It will output
{"0":"Jun-23","1":"Jun-24","2":"Jun-28","3":"Training-24","4":"Jun-29","5":"Jun-30","6":"Jul-06","7":"Jul-07","9":"Jul-09","10":"Jul-16","11":"Jul-17","12":"Jul-20","13":"Jul-23","14":"Jul-24","15":"Jul-30","16":"Aug-01","17":"Aug-05"}

(Sorry, couldn't find a smaller example where it fails)
Point being, why does it do this? The options are the same, the array is structured the same, what's the issue?

A: You don't have key [8] set in your second example. According to the documentation a sequential array with an unset key will be encoded as a JSON object and not a JSON array.

A: In your first example the array is numbered sequentially from zero. PHP treats this as a conventional array and encodes it accordingly.
In your second example element 8 is missing. PHP treats this as an associative array and encodes the keys accordingly.

A: Your PHP array is missing entry 8, so is a mapping (object) and not a list (array).

A: It is because of the indexing issue,
when your index is not proper it will behave like this.
the best way to resolve is reindexing.
$array = array_values($array);

Do like this just before converting to JSON.

A: Just when you encode the array, do this which will reindex array values:
$encoded = json_encode(array_values($myArray));


text:
Q: Ext JS 4: Getters and setters in view I've been thinking about this problem for a while, and I can't seem to come up with a reasonable solution. What I would like to do is create getters/setters for a textfield/its value in my view. I realize that the preferred Ext JS way is using a reference within the controller and getting it that way, but that doesn't feel very object-oriented to me. I'd also have to wrap these getters and setters because I want to output a message if the getter returns undefined. What I'd like to do is create my own getters/setters or somehow override the default getters/setters. Here are some ways I was thinking of accomplishing this.
I was thinking I could use the config {}, but that appears to only work for variables I want to define. I then was thinking of using an id somehow, but the community seems split on whether that's a good practice or not. Which leads to my current solution... wrapping. Here's my code:

LoginWindow

Ext.define('MyApp.view.LoginWindow', {
    extend: 'Ext.window.Window',
    alias: 'widget.loginWindow',
    autoShow: true,
    closable: false,
    border: 0,
    plain: true,
    allowBlank: false,
    title: "Enter your username",
    modal: true,
    config: {
        buttons: [{
            text: "Ok"
        }],
        items: [{
            xtype: 'textfield',
            fieldLabel: 'Username',
            id: 'loginUserInput',
            name: 'loginUserInput',
            msgTarget: 'under',
            validator: function(value) {
                if (Ext.isEmpty(value)) {
                    return "You need to enter a username.";
                }
                return true;
            }
        }]
    },

    constructor: function(config) {
        this.callParent(config);
    },

    getButton: function() {
        console.log('here');
    }
});

MyController

Ext.define('MyApp.controller.Chat', {
    extend: 'Ext.app.Controller',

    requires: [
        'Views.ChatModule.view.LoginWindow'
    ],

    refs: [{
        ref: 'loginWindow',
        selector: 'loginWindow',
        xtype: 'loginWindow',
        autoCreate: true
    }, {
        ref: 'loginUserInput',
        selector: '#loginUserInput'
    }],

    init: function() {
        // The events controller oversees
        this.control({
            'loginWindow button[text="Ok"]': {
                'click': this.onSubmitLoginWindow
            }
        });
    },

    getLoginUserInputValue: function() {
        var loginUserInput = this.getLoginUserInput();
        if (loginUserInput) {
            var username = loginUserInput.getValue();
            if (username) {
                console.log(username);
            } else {
                console.warn("username is undefined");
            }
        }
        console.warn("loginUserInput is undefined");
    },

    onSubmitLoginWindow: function(button, event, eOpts) {
        this.getLoginUserInputValue();
    }
});

This works, and I realize it's a very nit-picky thing, but it just doesn't feel right to have the getter in the controller. I feel like it'd be more object-oriented if it was in the Window. However, if I put it in the Window, I believe my only option is to lean on ids or manually create the textfield in the Window's initComponent--which would involve saving off a reference of the textfield in there, but that seems a bit inefficient... as I would have to make a call to doLayout as well.
Just to reiterate, I'd love to have the getters/setters in the Window, and I'm looking for a quick way to reference it, similar to how the controller references objects. I believe the main answer will be to use ids and making a call to Ext.ComponentQuery.query('#loginUserInput') in the Window, but I'd like to know if there were any better approaches out there... like overriding the auto generated getters/setters or adding a simple getter/setter for an input's value.
Cross-post from the Sencha forums.
Edit
I guess I was a bit unclear with what I want.  As a more general statement, instead of jamming all things related to my view in the controller, I'd like to store it all in the view itself, which includes things like getters/setters.  One of these getters/setters just so happens to be the loginUserInput getter.
Using a model is an interesting idea, but I feel like that would be a whole lot of overhead for singleton values.  I'm basically looking for something like Java's setters/getters in the LoginWindow view... and hopefully something as simple as (or close to) Java's.
The idea of including (encapsulating) it in the view makes the controller a bit cleaner, and if I delete the view, I'm deleting its functions as well, so I don't have to go hunting for the functions in the controller... all I have to worry about is removing the references (which should be minimal).

A: I think that the "OO" way that you're looking is to work with a Ext.data.Model for your form. If you look at the Ext.form.Basic you have methods to manipulate a model (called record) and also get the object with the values of your view. So you need:

*

*When you create your form, use loadRecord() to bind your form to a Model.

*At any time you need, use getValues() to retrieve the values of your form fields.

*When submiting your form, use getRecord() and getValues() to sync your record.

Ext.define('MyApp.model.Login',{
  fields : [{
    name: 'username',
    type: 'string'
  },{
    name: 'password',
    type: 'string'
  }]
});

Ext.define('MyApp.controller.Login',{
  ...
  refs : [{
    selector: 'window form',
    ref: 'formPanel'
  }],
  ...
  openForm : function() {
    //load your form and then bind the new record
    var formPanel = this.getFormPanel(), //Ext.form.Panel
        form = formPanel.getForm(); //Ext.form.Basic

    form.loadRecord(Ext.create('MyApp.model.Login'));

  },
  save : function() {
    //get the values in the view
    var form = this.getFormPanel().getForm(),
        vals = form.getValues(),
        record = form.getRecord();

    console.log(vals); //see the object representation of your view here
    record.set(vals); //update your model

    //do whatever you need with your model

  }
  ...
});

This is an good example when you need to save the form data. In the login I think you can work directly with getValues() without binding it to a Ext.data.Model.

A: I am not quite certain what problem you are trying to solve to be honest with you.
If you do not like controllers listening to buttons within your window, you can have button handlers witin your view definition fire custom events that controllers can listen on. Use fireEvent method. And by the way initConfig is a recommended way to setup your views. You can break it up into methods if you wish, 'this' reference is available and is the View component being instantiated.
If you need to find inner components within the View there are many methods available from up /down to nextSibling and query .
For Components:
    • Ext.getCmp(id)
    • Ext.ComponentQuery.query()
    • up()
    • down()
    • nextSibling()
    • previousSibling()
    • child()
    • previousNode()
plus various find.. Methods

EDIT
I think I understood what you mean by getter and setters. Ext forms have the fields finders to make it easy to get and set data to individual fields. See these SO questions: Best way to access adjacent components / fields and EXT.JS getting a list of items from a fieldset
Also like Sergio said there is getRecord getValues and setRecord methods on the form to deal with data binding. Thats it.
EDIT2
The best starting point guide that shows clear and claen MVC patterns as well as form handling. http://docs.sencha.com/extjs/4.1.3/#!/guide/application_architecture

A: My thoughts are something like this:
...
items: [],
constructor: function(config) {
  this.loginUserInput = Ext.create('Ext.form.field.Text', {
    fieldLabel: 'Username',
    id: 'loginUserInput',
    name: 'loginUserInput',
    msgTarget: 'under',
    validator: function(value) {
      if (Ext.isEmpty(value)) {
        return "You need to enter a username.";
      }
      return true;
    }
  });
  this.items.push(this.loginUserInput);
  this.callParent(config);
},

getLoginUserInput: function() {
  var loginUserInput = this.loginUserInput;
  if (!loginUserInput) {
    console.warn("LoginWindow::getLoginUserInput: loginUserInput is undefined");
  }
  return loginUserInput;
}

So instead of letting Ext do its magic, I am now instantiating the object on my own, which then allows me to store away a reference of it, so I can easily access it in my getter.  I just wonder if this is creating any sort of performance hit.  It doesn't seem like it'd be that much worse... it actually seems like it'd be a bit better because I'm not referencing this object by its ID, and I don't have to go searching for it when I need it.


text:
Q: How to grep certain attribute from openldap? I am using openldap and usually I will use command ldapsearch uid=<ldap> + to check certain attribute and by running such command, it will produce full output for example :
SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
lastLoginTime: 20220829012233Z
passwordRetryCount: 0
retryCountResetTime: 20220826111616Z
passwordExpWarned: 0
passwordExpirationTime: 20220905092802Z
pwdUpdateTime: 20220707092802Z
modifyTimestamp: 20220707092802Z

If, for example I would like to grep only "retryCountResetTime", I try to run :
ldapsearch uid=<ldap> + | grep ^retryCountResetTime

But the output will be :
SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
retryCountResetTime: 20220826111616Z

I would like to remove the first 3 line (SASL) by adding tail -1, but it doesn't work.
Any suggestion how can I remove the line 1-3?

A: As @steeldriver mentioned within the comments:

Perhaps the first 3 lines are not going to the standard output stream at all, but to the standard error stream?

To verify that you can redirect the STDERR channel to some other place, for example the null device by adding 2>/dev/null at the end of the command:
command -options arguments 2>/dev/null | grep 'something'

If you want to process it you can redirect it to STDOUT by adding 2>&1:
command -options arguments 2>&1 | grep 'something'

Note if you want to redirect STDERR along with STDOUT to a file the syntax is:
command -options arguments >/path/to/some.log 2>&1


text:
Q: Can we do query in query in prepare statement? I need to check if email activation is true or false in db on regisration form
So got to do second query for that.
I want to know if we can do second query in if statements ?
Here what I have tried, if not possible I will do a second query separetly.
I am getting this error

Warning: mysqli_stmt::close(): Couldn't fetch mysqli_stmt in

        $sql = "INSERT INTO users(username, email, password, type, token) VALUES(?, ?, ?, ?, ?)";
        if($stmt = $mysqli->prepare($sql)){
        $stmt->bind_param("sssis", $param_username, $param_email, $param_password, $param_type, $param_token);
    // Set parameters
        $param_username = $username;
        $param_email = $email;
        $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
        $param_type = 0; // Membership type
        $param_token = $token;
        if($stmt->execute()){
            $stmt = $mysqli->prepare("SELECT emailConfirmation FROM permissons WHERE emailConfirmation = ?");
            $stmt->bind_param("i",$id);
            $stmt->execute();
            $stmt->close();
        if($row['emailConfirmation'] == 1){
                require 'PHPMailer/Exception.php';
                require 'PHPMailer/PHPMailer.php';
                require 'PHPMailer/SMTP.php';
                $mail = new PHPMailer();
                $mail->setFrom('bilgi@444.com');
                $mail->username = "bilgi@444.com";
                $mail->password = "1444";
                $mail->addAddress($email, $username);
                $mail->Subject = "Please verify email!";
                $mail->isHTML(true);
                $mail->Body = "Thanks for signing up!

                            Please click on the link below:

                    Click Here";

                if ($mail->send()){
                    echo "You have been registered! Please verify your email!";
                }else{
                    echo "Something wrong happened mail! Please try again!";
                }
            } else{
                $user = 'login.php';
                header('Location: '.$user);
                 }
            } else{
                echo "Something went wrong. Please try again later.";
            }
        }

        // Close statement
        $stmt->close();
    }

    // Close connection
    $mysqli->close();
}

T hanks for any help or advice.


text:
Q: extjs do some action with window components on it's load I'm trying to disable a button on window when this window pops up but whatever handlers I tried to apply, window in not poped up and just spits out that "undefined" staff to me. For example I tried:
window.onload = Ext.getCmp('buttonId').disable();

and it returns me this in console:
Uncaught TypeError: Cannot call method 'disable' of undefined

Thanks everyone in advance!

A: You probably do not have anid set on the button...
Why don't you disable the button directly?
Ext.create('Ext.Button', {
    text: 'Disabled button',
    disabled:true
});

If you have an id on there, it works:
Ext.create('Ext.Button', {
    text: 'Dynamically disabled Button',
    id:'dynamicBtn',
    renderTo: Ext.getBody(),
    handler: function() {
        alert('You clicked the button!');
    }
});

Ext.application({
    name: 'MyApp',
    launch: function () {
        Ext.getCmp('dynamicBtn').disable();
    },
});

http://jsfiddle.net/4fPSf/


text:
Q: Exact match search in elastic search not working I have Indexed title_o as non indexed field. Query to get exact search is not returning results. I need find documents when the title_o matches this is test1. Please help.
Indexed following documents:
curl -XPUT 'http://localhost:9200/test/test10/1' -d '
{
    "doi":"1234",
    "title":"this is test1",
     "title_o":"this is test1"

}'

curl -XPUT 'http://localhost:9200/test/test10/3' -d '
{
    "doi":"1234",
    "title":"this is test3",
     "title_o":"this is test3"

}'

Search:
curl -XGET 'http://localhost:9200/test/test10/_search?pretty=true' -d '
{
    "query" : {
        "filtered" : {
            "filter" : {
                "term" : {
                    "title_o" : "this is test1"
                }
            }
        }
    }
}'

A: For exact/term matches use not analyzed fields,
Working code:
curl -XGET 'http://localhost:9200/test/test10/_search?pretty=true' -d '
{
    "query" : {
        "filtered" : {
            "filter" : {
                "term" : {
                    "title_o.keyword" : "this is test1"
                }
            }
        }
    }
}'

A: If you have your title field mapped as "index":"no", this tells ElasticSearch to make this field unavailable for search. In your case, make sure you have your field mapped as "index":"not_analyzed" if you plan on using this field for exact string matching.

A: The curl requested you posted in comment:
curl -XGET 'localhost:9200/test/test10/_search?pretty=true' -d ' { "query" : { "filtered" : { "filter" : { "term" : { "title.title_o" : "This is test6" } } } } }'
differs with the one posted in the question.
This should work:
curl -XGET 'http://localhost:9200/test/test10/_search?pretty=true' -d '
{
    "query" : {
        "filtered" : {
            "filter" : {
                "term" : {
                    "title_o" : "this is test1"
                }
            }
        }
    }
}'


text:
Q: how to create a word document with all the content of several others with phpword i have to make one .docx document with all the content of several .docx documents
foo.docx
bar.docx
foobar.docx

all-in-one.docx must be build like this
  foo.docx content
+ page break
+ bar.docx content
+ page break
+ foobar.docx content

PHP 7.0 | laravel 5.5 | PHPWord 0.15

A: A pull request that was accepted June 30 suggests the following.
Loops sections of one document and inserts it in another.
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$section->addText('Lorem ipsum');

// Load another document
$phpWord2 = \PhpOffice\PhpWord\IOFactory::load('lorem.docx');

// Add sections to the first document
foreach ($phpWord2->getSections() as $section) {
    $phpWord->addExistingSection($section);
}

So you would just basically (untested code)
<?php
    $documents = ['doc1.docx', 'doc2.docx', 'doc3.docx', 'doc4.docx'];
    $lastDoc = end($documents);

    $mainDoc = new \PhpOffice\PhpWord\PhpWord();

    foreach($documents as $document) {
        $appendDoc = \PhpOffice\PhpWord\IOFactory::load($document);
        foreach ($appendDoc->getSections() as $section) {
            $mainDoc->addExistingSection($section);
        }

        // Add page break after every appended doc except the last one
        if($document != $lastDoc) {
            $section = $mainDoc->addSection();
            $section->addPageBreak();
        }
    }

Now $mainDoc should be ready to save.
Another possible solution is to use DocxMerge. Not sure it supports adding page breaks etc though.


text:
Q: How to prove universally-quantified formula is true by contraposition?
For all natural numbers $x$ and $y$, if $x+y$ is odd, then $x$ is odd or $y$ is odd.

How do I prove the following statement is true by contraposition without using a truth table and theorems?

A: The contrapositive of "if $x+y$ is odd then either $x$ is odd or $y$ is odd" would be "if $x$ and $y$ are both even or both odd, then $x+y$ is even".
The sum of two even numbers, $2a$ and $2b$, is $2(a+b)$, which is even. The sum of two odd numbers, $2a+1$ and $2b+1$, is $2(a+b+1)$, which is even too. This is sufficient.
In fact, you can prove that the implication goes both ways very similarly.
Edit: as originally stated, one could assume that "or" in "$x$ is odd or $y$ is odd" is not exclusive. In that case the statement only works in one direction, and the proof by contraposition involves proving the statement "$x$ even and $y$ even implies $x+y$ even", which is proved above.


text:
Q: Searching programs in 64 bit and 32 bit registers results in 32 bit I am use method from this: Check if application is installed in registry  to find "Sql Server 2019".
Problem is when i run program with active solution platforms: Any CPU.
string registryKey64 = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
string registryKey32 = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";

RegistryKey key64 = Registry.LocalMachine.OpenSubKey(registryKey64);
RegistryKey key32 = Registry.LocalMachine.OpenSubKey(registryKey32);

In then key64 == key32. Which causes it not to find a 64 bit sql server. Problem dont occurs in the opposite direction.
I dont want run program for platforms 64 bits. How can I get into the 64 bits registers?

A: My solution:
string registryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
RegistryKey key64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
RegistryView.Registry64);
RegistryKey key = key64.OpenSubKey(registryKey);
if (key != null)
{
    var list = key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName).GetValue("DisplayName")).ToList();

    key.Close();
}


text:
Q: Implementing Facebook like content loading I want to implement Facebook like automatic content loading on scrolling in my webpages,how can we easily achieve this?Is there any jquery plugins for this?

A: Use Jquery Waypoints , It will create a event hook when the scroll reaches the bottom of the page , and then ajaxify that according to your usage . Js Fiddle Example
Though its using JqueryMobile in the example but its nothing very related to that. Proper usage of this should do the trick . Best of luck !

A: This is fairly easy. First off, you have to note when the element is scrolled to its end. In case of the FB sidebar ticker, or the page as a whole, you will see that when it is scrolled to its end, a loading GIF image is displayed while data is being fetched by AJAX, after which the data is displayed and the GIF image being pushed out of view. To note the moment when the user has scrolled to the bottom, you can do something like :
$(element).bind('scroll',function() {
   if ($(this).outerHeight() + $(this).scrollTop() >= $(this).get(0).scrollHeight) {
   //unbind the 'scroll' event until the data is fetched and displayed
   $(this).unbind('scroll');
   //ajax call to fetch data, display it, and finally rebind the 'scroll' event as a callback function
   }
  });


text:
Q: SQL Literal/Keywords for DateTime field in Ormlite POCO I'm using servicestack/ormlite 4.0.32 with postgres 9.3.
I have a few timestamp columns in the tables (along with corresponding DateTime fields in their associated POCOs).
How can I use SQL literals like NOW(), CURRENT_TIMESTAMP etc. in ormlite POCO Insert() or Update() methods? By default, the DateTime fields are populated with DateTime.Min.
I don't want to use database triggers, SQL literals such as NOW() are preferrable.

A: The DateTime values that are not Nullable<DateTime> will default to DateTime.Min when you Insert or Update. Therefore you should set them to the desired value.
Set Manually:
You can do this during your Insert or Update statement by specifying the value you want to be DateTime.Now
db.Insert(new Person { Id = 1, FirstName = "John", CreatedDate = DateTime.Now });

Use OrmLite's Insert/Update Filters:
However I suspect that you are looking to avoid having to do this yourself in your Insert or Update statement, and this is typically handled using OrmLite's Insert/Update filter functionality, that can be used to set the record creation and modification time.
From the documentation:
public interface IAudit
{
    DateTime CreatedDate { get; set; }
    DateTime ModifiedDate { get; set; }
    string ModifiedBy { get; set; }
}

OrmLiteConfig.InsertFilter = (dbCmd, row) => {
    var auditRow = row as IAudit;
    if (auditRow != null)
        auditRow.CreatedDate = auditRow.ModifiedDate = DateTime.UtcNow;
};

OrmLiteConfig.UpdateFilter = (dbCmd, row) => {
    var auditRow = row as IAudit;
    if (auditRow != null)
        auditRow.ModifiedDate = DateTime.UtcNow;
};

Then on your database table class:
public class MyTable : IAudit
{
    // Your properties
    ...

    // The audit properties
    DateTime CreatedDate { get; set; }
    DateTime ModifiedDate { get; set; }
    string ModifiedBy { get; set; }
}

When you Insert/Update MyTable then the filters will update the timestamps automatically.


text:
Q: properties toolbar is empty and does not let load up my forms When I open up my project at home the properties bar is completely empty and I can't open up my forms and their coding. I can open up my coding manually by using 'open file' but when I open up the designer it brings up the code for the form and not the form itself. When I open up the project at work it works completely fine and I can open up my forms from the properties toolbar but it doesn't work for me at home.

A: What are you using to view C#? I'm assuming Visual Studio. If so, which version? Do you have any external Form-Tools installed at work but not at home? Something like devexpress?
Generally: Try providing more information, stuff like version numbers, operating systems, used add-ons, etc.


text:
Q: Neo4j : loadByProperty is loading the other objects that doesn't belong to the node my structure is as follows:
a company -> having set of users -> each user is having set of policies -> each policy is for a company.
sample graph structure :
       u1 <- c1 -> u2
       p1 -> c1
       u1 -> p1

company(c1) is having two users (u1, u2) and a policy(p1) belongs lo company(c1). "u1" has taken the policy(p1). "u2" has no policy.
When i'm trying to load the u2 by "loadByProperty" method, expected should be User2 object and the corresponding Company(c1).
But, the policy(p1) is also loading and setting to "u2" object.
Class Structure;
Company{
   Stirng companyName;
   @Relationship(type = "hasUsers", direction = Relationship.OUTGOING)
   List<User> users;
}

User{
   Stirng userName;
   @Relationship(type = "hasPolicy", direction = Relationship.OUTGOING)
   List<Policy> policies;
}

Policy{
   String policyName;
   @Relationship(type = "forCompany", direction = Relationship.OUTGOING)
   Company company;
}

Method for retrieving User:
 public User getUser(String userName) {
    Property<String, Object> properties = new Property<String, Object("userName", userName);
    Set<User> users = (Set<User>) session.loadByProperty(User.class, properties);
    if (users != null && !users.isEmpty())
        for (User user : users)
            return user;
   return null;
 }

Using SDN 4 (mile stone version).
Any suggestions? Thanks is advance.

A: There are a number of ways in which you can load an entity by property value.
Neo4jOperations
Use loadByProperty or loadAllByProperty
Derived finders (repositories only)
@Repository
public interface UserRepository extends GraphRepository<User> {

User findByName(String name);

}

SDN will use the metadata info to translate this into a Cypher query.
@Query (repositories only)
@Repository
public interface UserRepository extends GraphRepository<User> {

   @Query("MATCH (user:User{name:{0}}) RETURN user")
   User findUserByName(String name);

}

Session
Use any of the loadAll methods which accept a Filter.
Example:
session.loadAll(Person.class, new Filter("firstName", "John"))


text:
Q: Authenticate Restful cakePHP 2.3 I have two cakePHP apps on 2 different servers. One app is required to get data from the first one; I have succeeded to put the Restful architecture in place but I failed to implement an authentication procedure to the requests the server sends. I need to authenticate to secure the data. I have looked around on the web but can't seem to get it working. Can anyone point me to a resource / tutorial that explains this in detail.
What I would ultimately need would be a way to authenticate my server every time it sends a request to the other server. Any help would be appreciated.

A: I finally got it to work after some research; indeed one of the solutions is OAuth. In case you are facing the same problem, I can advise you this Plugin made for CakePHP.
In details what I did was put the OAuth Plugin into my API Server and I used it like so for my restful controller:
class RestObjectController extends AppController {
public $components = array('RequestHandler', 'OAuth.OAuth');
public $layout = FALSE;

public function token() {
    $this->autoRender = false;
    try {
        $this->OAuth->grantAccessToken();
    } catch (OAuth2ServerException $e) {
        $e->sendHttpResponse();
    }
}
public function index() {
    $objects = $this->Object->find('all');
    $this->set(array(
        'objects' => $objects,
        '_serialize' => array('objects')
    ));
}

The function RestObject.token() is what I would call to get an Access token which will be used to give me access to the Resources in my controller. (Note that by declaring OAuth in my controller components, all the resources within my controller will need an access token to be accessible).
So on the client Server I would get an access token in the following way:
public function acquireAccessToken(){
    $this->autoRender = FALSE;
    App::uses('HttpSocket', 'Network/Http');
    $link = API_SERVER."rest_objects/token";
    $data = array(
            'grant_type' => 'client_credentials',
            'client_id' => 'xxxx',
            'client_secret' => 'xxxx'
    );
    $response = $httpSocket->post($link, $data);
    if($response->code == 200){
        $data = json_decode($response->body, true);
        return $data['access_token'];
    }
    return FALSE;
}

This assumes that you have clients already set up as explained in the Plugin Doc (replace xxxx by the real values for the client credentials). Once I have my access token, all I have to do is use it as follows:
public function test(){
    $this->layout = FALSE;
    App::uses('HttpSocket', 'Network/Http');
    $httpSocket = new HttpSocket();
    if($access_token = $this->acquireAccessToken()){
            $link = API_SERVER."rest_objects.json"; //For the index as e.g.
            $data = array('access_token' => $access_token);
            $response = $httpSocket->get($link, $data);
    }
}

And here you have it! So start by reading the Oauth Specification  to understand the Protocol (in particular the Obtaining Authorization part), see which protocol (can be different from the one I used) applies and adapt to your case by using the Plugin
Tutorial Here


text:
Q: How to Identify correct URL pattern of SharePoint to get list of items by title from Rest API My goal is to get all items or files names at this URL
https://myOrganization.sharepoint.com/sites/supplierABC/DataSheet/Forms/AllItems.aspx
I have followed this link and I already have client Id and client secret for the SharePoint URL by using them I am able to generate access token successfully. By using generated access token in Authorization (Postman header), I am trying a get request in Postman with URLs:
https://myOrganization.sharepoint.com/_api/web/lists/getbytitle('test')/items
https://myOrganization.sharepoint.com/sites/supplierABC/DataSheet/Forms/AllItem.aspx/_api/web/lists/getbytitle('test')/items
My question here is which URL should be used before _api/web/lists/getbytitle('test')/items either

*

*https://myOrganization.sharepoint.com
or

*https://myOrganization.sharepoint.com/sites/supplierABC/DataSheet/Forms/AllItems.aspx (files are present here)

A: Your REST URL should be:
_spPageContextInfo.webServerRelativeUrl + _api/web/lists/getbytitle('test')/items


text:
Q: Object literal - adding items I have this in my code:-
var chartOptions = {
      series: {
               bars: { show: true }
              }
};

Is there a way I could add another item to the chartOptions object through code so that it was added an item to the series part, like this:-
series: {
    bars: {show: true, fillColor="Red"}
}

How would I go about doing this?  I was expecting something like:-
chartOptions["series"]["bars"]["fillColor"] = "Red"

But that doesn't work.  I'm pretty new to this so any help would be greatly appreciated.
Matt

A: You can add it inline by using : instead of =
series: {
    bars: {show: true, fillColor: "Red"}
}

Or you can add it in code using jQuery.extend() or with JavaScript:
chartOptions.series.bars.fillColor = "Red";

Your code chartOptions["series"]["bars"]["fillColor"] = "Red" should also work but it is the notation when dealing with arrays. The dot notation is usually used when dealing with objects. Both notations are mostly interchangeable though.

A: function extend(destination, source) {
    for (var property in source) {
        destination[property] = source[property];
    }

    return destination;
}

var chartOptions = {
    series: {
        bars: {
            show: true
        }
    }
};

Object.extend(chartOptions.series.bars, {
    fillColor: "Red"
});

console.log(chartOptions);

A: Take a look at this jsfiddle : http://jsfiddle.net/5KMfy/4/
I wrote 2 working examples, with and without jQuery, hope this helps.


text:
Q: Marquee for listview itemtemplate label How to add a marquee control for listview itemtemplate?
i use label as itemtemplate.In listview hvae 12 images and 12 labels.
example:
(If the label text="One" that means
   i don't need marquee
but
   the text="This is the sample for marquee in asp.net" above 40 character means
   i need a marquee)

..It is possible.
advance thanks


text:
Q: WPF WYSIWYG Editor I have created a wysiwyg editor as a standard C# program using the windows form control. I would like to do the same thing except with WPF.
In my old application I did something like this.
using mshtml;
private IHTMLDocument2 doc;

...

HTMLeditor.DocumentText =

"";

doc = HTMLeditor.Document.DomDocument as IHTMLDocument2;

doc.designMode = "On";

Which allowed the the use of Document.ExecCommand on the editor.
How is this accomplished in WPF? It doesn't look like the WebBrowser control in WPF allows for designmode.
Thanks!

A: Try this:
public MyControl()
{
    InitializeComponent();

    editor.Navigated += new NavigatedEventHandler(editor_Navigated);
    editor.NavigateToString("");
}

void editor_Navigated(object sender, NavigationEventArgs e)
{
    var doc = editor.Document as IHTMLDocument2;

    if (doc != null)
        doc.designMode = "On";
}

Edit: where editor is a WebBrowser control.


text:
Q: I want to know the coordinates of a finger touch on a touchscreen (subview) to be displayed on a GUI running on the PC (parent view) I have tried and tried and it has been 2 weeks (long enough?) but I cannot get this to work, the sub-view screen is being observed by 2 cameras at the top corners (right and left) and the GUI on a parent screen is reading output values from the camera and displaying the x and y coordinates.
I am writing this in C#, could someone just provide an inept explanation of what I would need to do to make this work? Thanks, you guys are the best! Here is the Delphi code that does the similar thing.
Procedure MouseLeftClick(beam1:integer; beam2:integer);

var

coordXLocal, coordYLocal : single;

coordXScreen, CoordYScreen :single;

  angle1, angle2 : single;
const
  base:single=1100;
begin
  beep;
  angle1:=(beam1/128) * 90;

angle2:=(beam2/128) * 90;

angle2:=90-angle2;

coordXLocal:=(base*tan(degtorad(angle2)))/(tan(degtorad(angle1))+tan(degtorad(angle2)));

coordYLocal:=coordXLocal*tan(degtorad(angle1));


text:
Q: suspend kubernetes cronjob on job failure to avoid subsequent job runs Whenever a job run fails I want to suspend cronjob so that no further jobs are started. Is their any possible way?
k8s version: 1.10

A: you can configure it simply using suspend: true
apiVersion: batch/v1
kind: Job
metadata:
  name: my-job
spec:
  suspend: true
  parallelism: 2
  completions: 10
  template:
    spec:
      containers:
      - name: my-container
        image: busybox
        command: ["sleep", "5"]
      restartPolicy: Never

Any currently running jobs will complete but future jobs will be suspended.
Read more at : https://kubernetes.io/blog/2021/04/12/introducing-suspended-jobs/
If you are on an older version you can use backoffLimit: 1
apiVersion: batch/v1
kind: Job
metadata:
  name: error
spec:
  backoffLimit: 1
  template:

.spec.backoffLimit can limit the number of time a pod is restarted when running inside a job
If you can't suspend it however we make sure job won't get re-run using

backoffLimit means the number of times it will retry before it is
considered failed. The default is 6.
concurrencyPolicy means it will run 0 or 1 times, but
not more.
restartPolicy: Never means it won't restart on failure.


text:
Q: Can't find jar files in spring framework 4.0.6? Today, i donwloaded Spring Framework 4.0.6 latest version but unable to locate the jar files, and i donwloaded eclipse plugin for spring too, here i find nothing and looking for a way to include these jar files into eclipse, here is a pic.
Some tutorials website refers that it contains into lib folder but i can't see it, please help!

A: It sounds like you have a number of hurdles to overcome:

*

*How to use Eclipse

*How to manage Java dependencies

*How to use Spring

I'm not sure what your level of experience is, but you may wish to consider using Spring Tool Suite as your IDE - it's based on Eclipse with additonal plugins to aid Spring development.
I also urge you to use Maven or Gradle to manage your dependencies. The Spring documentation provides the configuration for adding the dependencies in both. I'd recommend Maven as a starting point as it is easy to use with little knowledge and is well suited to small, standard projects. Gradle is worth a look once you are comfortable with Maven.
Work though the Guides - I'd start with 'Building Java Projects with Maven'.
Edit
Maven is a dependency management and build tool that favours convention over configuration. Dependency management is powerful in that you can declare a dependency on Spring Core, for example, and it will download all the related dependencies for you.
Gradle performs similar functions to Maven but also provides the ability to use scripting. Gradle is seen by many as Maven's predecessor and has been adopted by Spring over Maven.
In my opinion Maven is easier for you at this stage.


text:
Q: I cant use multiple credentials on JMeter Authorization Manager on the same Test Case I am trying to simulate a scenario where two different users(with different credentials) log in simultaneously. This simulation will continue in a controlled number of iterations loop.
I am using the HTTP(S) Test Script Recorder to generate the Transaction controllers when I record my user interactions.
I made two different Thread Groups to resemble each user with their separate Recording Controllers.
I first target one of the Recording Controller in my Test Script Recorder and then record myself logging in as user1. This autogenerates an HTTP Authorization Manager with the credentials.
When I now log in as a different user and record myself this time targeting another thread it does not generate an HTTP Authorization Manager. I then created my own manually and saved it as a txt file. When i try and play the recordings only the auto-generated one works.
What can I do to have two concurrent threads log in as different users or use the same thread group and have it switch between the two login credentials.

A: You can put your credentials in the CSV file
username,password
user1,secret
user2,anothersecret

and add a CSV Data Set Config to read the credentials from the CSV file into JMeter Variables

Then in the HTTP Authorization Manager just use the JMeter Variables from the CSV Data Set Config:

This way each thread (virtual user) will the next line from the CSV file on each iteration and you will be authenticated as a new user.