text:
Q: Subgroups which contain all $p$-Sylowsubgroups for some fixed prime $p$ Is it true that if some subgroup $H \le G$, $H\ne G$ contains all $p$-Sylowsubgroups for some fixed prime $p$, then $H$ contains some non-trivial normal subgroup of $G$?

A: Hint: All the conjugates of $H$ also contain all those Sylow $p$-subgroups. The intersection of the conjugates of $H$ is thus...

A: Yes. $G$ acts by conjugatiopn on the set of $p$-Sylowsubgroups. Hence the smallest subgroup of $G$ that contains all $p$-Sylows is also conjugation-invariant.

A: Consider the subgroup generated by all elements of order $p$. Any automorphism of $G$ permutes these elements. In particular, this means that the subgroup they generated doesn't change, and thus is characteristic. Each of these elements are also contained in some $p$-Sylow. Since $H$ contains all of the $p$-Sylows and is closed under multiplication, this means that the characteristic subgroup is contained in $H$. Since $H$ is not all of $G$, neither is this subgroup.


text:
Q: Defining a listings style and available options When defining a style for a listings environment, I can set the background color by doing:
\lstdefinestyle{highlight}{
  backgroundcolor=\color{orange}
}

Apart from backgroundcolor, which other options are available? In particular, how can I set the font weight to bold?

A:
Apart from backgroundcolor, which other options are available?

Most packages have a documentation. The documentation is available on your computer. You can open the documentation with the command line:
texdoc <packagename>

The command texdoc has same extra options which are documented, too. Run:
texdoc texdoc

to open the documentation. Of course it is also available in the web.
Online version of texdoc
Based on the given information you can open the documentation of listings by
texdoc listings

If you want the online documentation go to CTAN:
listings at CTAN
In section 4.6 Figure out the appearance you find the option basicstyle which is documented as:

is selected at the beginning of each listing. You could use
  \footnotesize, \small, \itshape, \ttfamily, or something like that.
  The last token of basic style must not read any following characters.

The package listings provides an extra development documentation. For this

*

*download the file listings.zip

*extract the file listings.zip

*run make all
The result will be the huge pdf-file listings-devel.pdf

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't delete files from APFS volume -- no space left on device My Late 2012 iMac's APFS Fusion Drive is full (53 KB free) and caused the system to freeze. I've rebooted into Recovery Mode but I cannot remove any files: rm XXX: no space left on device. fsck_apfs reports no problems. I found some suggestion somewhere to remove the APFS Volume named 'VM', but after removing this volume the error remains. After installing macOS on an external disk I tried removing the snapshots, but that resulted in an error. After restarting the snapshots are no longer listed.
The APFS container is the default setup per Catalina on a Fusion drive. There are 2 physical store disks and 5 volumes (Data, Preboot, Recovery, VM & System).
I don't want to reinstall macOS. How can I free up some space such that macOS can boot?

A: APFS is a CoW (Copy on Write) filesystem therefore anything (includes deleting files) requires writable disk space to perform those actions (refer to this post).
In your case, if removing VM doesn't help (because VM is dynamically-sized, and may happen to have a size of 0 when you attempted to remove it, therefore gave you no extra space), try:

*

*Get Recovery volume's (where recoveryOS lives in) identifier with diskutil list.

*Then use diskutil apfs deleteVolume IDENTIFIER
This should give you some space to delete files. Clean up immediately.
This will also ruin your recoveryOS, to restore recoveryOS installation, just:
Download latest macOS update at https://support.apple.com/downloads/macos and install it. Supplemental updates and security updates are all good.
EDIT: If you're on Big Sur (latest at the time of posting), use Mac App Store to download a full image (I know it's big, but you have to) at: itms-apps://apps.apple.com/us/app/macos-big-sur/id1526878132 (this is the URL scheme for Mac App Store, paste it in any browser)


text:
Q: Stationary Background, Moving Foreground Website So I have been working on a website using the .NET framework and would like to make the background style look a little something like it does at bons.me. As you can see when you scroll it background stays in the same position, however as you scroll the part of which you see changes. Anyone know how I would go about doing this? Would it be something in css or ...? I'm rather new to web development, but it would also be just as much of a help if you could just point me in a direction or tell me what this is called so I could google it.

A: This deals with the css property background-position: fixed. David Walsh has a good article describing the technique here.


text:
Q: ubuntu - how to recreate slapd.conf i overwrote initial slapd.conf, then removed slapd with "apt-get purge slapd", and reinstalled it.
initial slapd.conf didn't reappear.
what can i do to get it back?
upd: i need the initial one, not the one with my changes!

A: It depends which filesystem you were deleteing the file from, NTFS you can recover the file using ntfsprogs (apt-get install ntfsprogs) and then look for deleted files (ntfsundelete).
ext3, I am quite certain that you cannot recover files. This is an extract from ext3 FAQS:
Q: How can I recover (undelete) deleted files from my ext3 partition?
Actually, you can't! This is what one of the developers, Andreas Dilger, said about it:
In order to ensure that ext3 can safely resume an unlink after a crash, it actually zeros out the block pointers in the inode, whereas
ext2 just marks these blocks as unused in the block bitmaps and marks the inode as "deleted" and leaves the block pointers alone.
Your only hope is to "grep" for parts of your files that have been deleted and hope for the best.

A: ok, i suspect that there is actually no default slapd.conf in newest 9.10 ubuntu package, that's why it doesn't restore it. must be the one from the old version.

A: try to:
dpkg-reconfigure -plow $package
it should create a new file based on your answer.


text:
Q: Retrieving data from csv file in react js I am using React js to retrieve data.
Data.csv file location: /chart/data.csv
============
Date       | id  | No.
2021-Jan-2 | 1   | 3
2021-Jan-3 | 3   | 1
2021-Jan-4 | 4   | 4
2021-Jan-5 | 2   | 10
2021-Jan-6 | 6   | 7
Practice.js file location: /chart/Practice.js
I have tried to retrieve data from csv file and see in browser.
Here is how I have tried:
import React from 'react';
import * as d3 from 'd3';

const Practice = () => {
  const [data, setData] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    d3.csv("/data.csv").then((d) => {
      setData(d);
      setLoading(false);
    });
    return () => undefined;
  }, []);
  return (

            {loading &&
loading
}
            {!loading &&
data={data}
}

    );
}

export default Practice;

I keep getting an error message saying that TypeError: d3__WEBPACK_IMPORTED_MODULE_5__.csv(...).then is not a function
Am I using d3 correctly?

A: You need to either serve the file as a static asset if you wish to refer to it, or, for testing, use something you can find online....
Below is a sample using dome random csv I found on github.
Also, d3 returns an object which you cannot set as text in react. I have stringified it below...
import React from "react";
import * as d3 from "d3";

const Practice = () => {
  const [data, setData] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    d3.csv("https://raw.githubusercontent.com/curran/data/gh-pages/dbpedia/cities/properties.csv").then((d) => {
      setData(JSON.stringify(d, null, 2));
      setLoading(false);
    });
    return () => undefined;
  }, []);
  return (

        {loading &&
loading
}
        {!loading &&
data={data}
}

  );
};

export default Practice;


text:
Q: Como passar dados lidos em um programa em c++ como momando no cmd Gostaria de saber como ler algo em um programa e passar esta leitura como um comando para o cmd, atraves da biblioteca stdlib ou cstdlib, tanto faz.
A foto mostra o que estou tentando fazer.

A: #include <iostream>
#include <string>

using std::string;
using std::system;

int main()
{
    string line;
    string command = "ping ";
    string param = "www.google.com";

    line = command + param;

    system(line.c_str());
    return 0;
}

Alternativamente, você pode concatenar uma std::string e chamar .c_str() diretamente sem uma terceira variável temporária. Segundo [class.temporary]/4, o tempo de vida do temporário criado pela concatenação vai até o fim da chamada da função, portanto é seguro obter um ponteiro para o primeiro elemento da string com .c_str().
using std::string;

int main()
{
    string arg = "www.google.com";
    system(("ping " + arg).c_str());
    return 0;
}


text:
Q: Why do I not get a good binary image with a grey background using the mahotas python module? I got some problems with image with grey background with mahotas library:
Example:
This is the code:
import mahotas as mh
path ="./imagepath/a.jpg"
fork = mh.imread(path)
bin = fork[:,:,0]
bfork = bin <230

After that i got that:

What have i do for getting a black background and a white sign?
I tried in opencv module and was good, but i prefer mahotas.
import cv2
path ="./imagepath/a.jpg"
ow =  int ((oshape[0]/100 )*7 )
oh =  int ((oshape[0]/100 )*7 )
gray = cv2.imread(path,0)
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(ow,oh))
graydilate = cv2.erode(gray, element)
ret,thresh = cv2.threshold(graydilate,127,255,cv2.THRESH_BINARY_INV)
bin = thresh

A: You are not doing the same as in the opencv version. If you do, you'll get the wanted results:
fork = mh.imread(path)
bin = fork[:,:,0]
bin = mh.erode(bin)
bin = (bin < 127)

The erosion step was missing and the threshold was different.
from matplotlib import pyplot as plt
plt.imshow(bin)
plt.gray()


text:
Q: Do DDD and SOA really play well together? Please let me know, ever so gently, if I am totally mangling the DDD concept, but here is my dilemma.
Let's say I have the following domain model:
Teacher
  IList<Class>

Class
  Teacher
  IList<Student>

Student
  Class

Now, from a DDD perspective, it seems like the Teacher is my root, and indeed, in a simple app, I might carry around my Teacher with her classes and students and act on them as needed.  But in an SOA situation, let's say I've pulled down my Teacher, her classes and students for display purposes (as dtos), and she wants to add a student.  Surely I am not going to send the whole object graph up to the server and retrieve the domain objects from the database just so that I can add a new student, right?
Where is the sweet spot here, or am I totally missing the boat?
Thanks!
Late Upate:  Maybe I'm answering my own question, but I guess one approach is to have my Teacher service have various student management methods (AddStudent, UpdateStudent) such that my root is still managing everything instead of having one service per object.

A: I would say you are both missing the boat, and at the same time on the right track.... let me explain.
DDD is the best way we know as an industry to codify the reality of a business problem into a solution domain that we can map to a computer program. DDD is a methodology to abstract a real domain into something more manageable and relevant for us, these are good things.
The problem you are facing is in the implementation, the prevailing implementation choice for the last 20-30 years has been object orientation (OO), the core mechanism of passing objects around in OO is by passing references to objects in the same memory space as yourself. So the problems you are facing about large object graphs where never a real problem.
Enter Service orientation (SO) which flips things around, you are not longer passing references to objects, but exchanging messages between services. The size of the message now becomes a concern.
If we accept that the paradigm of implementation has changed, we need to accept that some of our OO best practices/patterns either no longer apply or need revision.
If you want to get into the SO way of thinking, you need to,  I believe (my opinion here), let go of the idea of a rich domain slightly.  I term this new concept a Service-Orientated-Domain (SO-Domain).
In a SO-Domain the state of the domain and the behavior of the domain is split between the messages you pass and the services you use.
So the state or the attributes of the teacher are part of the TeacherDTO, but the behavioral is part of the teacher service.
In OO terms this is an anemic domain, but in a SO sense it is not such a bad thing as this gives you some amazing flexibility, as you no longer have one big thing, the state can be used in multiple contexts.
You still have a valid domain, it is just partitioned differentially, messages hold state and services hold behavior.
The rest comes down to service interface design, so to get the class for a teacher you could have things like List RetrieveTeacherClasses(teacherIdentifier). To add a student AddStudentToClass(Student, classId).
There are a million different way to do this you will find the one that works for you, but as a general rule you should follow a state-aware paradigm, this means the message will send any state the service needs to be aware off, this enables the service to be stateless, and stateless service mean scalability.
Pratik mentions performance, true performance gains on a system wide scale are not made by fussing over the size of object graphs, but as the ability of every service in the solution to scale independently.
Here are some links to more on these ideas
Building a SOA
SOA Design Pattern
Achieving integrity in a SOA
Why your SOA should be like a VW Beetle
SOA explained for your boss
WCF Service Performance

A: You are thinking about performance, but you will be surprised. In my SOA web services I use such complete object graphs and performance is well within acceptable limits. I would suggest to use business objects and business web methods like SaveTeacher(Teacher t) unless absolutely required to use DTOs for performance reason and associated CRUD web methods like AddStudent(long teacherId, Student student)
But even if using the later you can apply the DDD concept by loading the teacher from your persistence store given the teacherId, attaching the student and saving the teacher back to persistence store.

A: What Vijay is saying is to add a TeacherService with an AddStudent method
interface ITeacherService
{
  Teacher GetTeacher (name teacher);
  void AddStudent (Teacher teacher, Student student);
}

So then you would end up with something like the following:
Student student = new Student ("Bobby Drop Tables;");
Teacher teacher = teacherService.GetTeacher ("Bob");
teacherService.AddStudent (teacher, student);

A: For SOA, you need Application Services.  Take a look here to figure out where your functionality should go.


text:
Q: Drools - Clone Github Repo I have created a K8 deployment for KIE WB and KIE Server.
For KIE WB I have created a Docker Image that configures the Post Commit hook so my repos are pushed to GitHub.
All of this works great.
My question revolves around restoring a repository upon pod creation. So when my pod starts up I would like to clone my GitHub repos then they're restored without having to manually import them.
I thought I could use the GitHub API and get a tarball and drop them into the .niogit/ path but that's not working (I see the file structure in git is different, it looks like just the java source and not the required files for KIE WB recognize that it's a repo).
I know I have to be doing something that has been done but I am not finding anything to get this going. I don't want to reinvent the wheel either :)
Any ideas?

A: You need to use initContainers with Kubernetes git-sync https://github.com/kubernetes/git-sync/
Please see Answers to Question How to clone a private git repository into a kubernetes pod using ssh keys in secrets?
So the Kubernetes git-sync initContainer will pull a git repository into a local directory which is shared with your Drools Container via emptyDir volume mount.
For More Information on initContainers please read https://kubernetes.io/docs/concepts/workloads/pods/init-containers/


text:
Q: Is Kubernetes + Docker + AWS = Azure + Service Fabric? I see advantages of Kubernetes which include Rolling Deployments, Automatic Health check monitoring, and swinging a new server to action when an existing one fails.  I also do understand that Kubernetes is not just for Docker.
So, that brings a couple of questions!
When Azure, and Service Fabric could provide all that I said (and beyond), why would I need Kubernetes?
Would it make sense for one to use Kubernetes along with Service Fabric for large scale deployments on Azure?

A: Let's look first at the similarities between Kubernetes and Service Fabric.

*

*They are both cloud-agnostic clustering, orchestration, and scheduling software.

*They can both be deployed manually, by you, to any set of VMs, anywhere.

*There are "managed" offerings for both, meaning a cloud provider like Azure or Google Cloud will host a cluster for you, but generally you still own the VMs.

*They both deploy and manage containers.

*They both have rich management operations, such as rolling upgrades, health checks, and self-healing capabilities.

That's a fairly high-level view but should give you an idea of what and where you can run with each.
Now let's look where they're different. There are a ton of small differences, but I want to focus on two of the really big conceptual differences:

*

*Application model:

*

*Service Fabric allows you to orchestrate any arbitrary container or EXE (whether that's a small node.js app or a giant legacy application), and in that sense it is similar to Kubernetes. But overall it is more focused on application development specifically, with  programming models that are integrated with the platform. In this respect, it is more closely comparable to Cloud Foundry than Kubernetes.

*Kubernetes is focused more on orchestrating infrastructure for an application. It doesn't really focus on how you write your application. That's up to you to figure out; Kubernetes just wants a container to run, doesn't matter what's in it.

*State management

*

*Kubernetes allows you to deploy stateful software to it, by providing persistent disk storage volumes to containers and assigning unique identifiers to pods. This lets you deploy things like ZooKeeper or MySQL.

*Service Fabric is stateful software. Service Fabric is designed as a stateful, data-aware platform. It provides HA state and scale-out primitives. So while Kubernetes allows you to deploy stateful things, Service Fabric allows you to build stateful things. This is one of the key differences that's often overlooked. For example:

*

*On Kubernetes, you can deploy ZooKeeper.

*On Service Fabric, you can actually build ZooKeeper yourself using Service Fabric's replication and leader election primitives.

*Kubernetes uses etcd for distributed, reliable storage about the state of the cluster.

*Service Fabric doesn't need etcd, because Service Fabric itself is a distributed, reliable storage platform. The system services in Service Fabric make use of this to reliably store the state of the cluster. This makes Service Fabric entirely self-contained.

The fact that Service Fabric is a stateful platform is key to understanding it and how it differs from other major orchestrators. Everything it does - scheduling, health checking, rolling upgrades, application versioning, failover, self-healing, etc - are all designed around the fact that it is managing replicated and distributed data that needs to be consistent and highly available at all times.

A: Please find below a good comparaison article about the difference between ACS and Azure Service Fabric:
https://blogs.msdn.microsoft.com/maheshkshirsagar/2016/11/21/choosing-between-azure-container-service-azure-service-fabric-and-azure-functions/
Could you please clarify what you refer to when you talk mentionne "AWS" ?
From a "developer level" solution could be statefull in both cases but it have a major difference from an Infrastructure point of view:

*

*Docker + Kuberest is a "IaaS" oriented solution

*Azure Service Fabric (if you are using Azure service) is a PaaS solution.

IaaS is, in general, more costly and have a more significant maintenance cost.
From a support point of view:

*

*Azure Service Fabric is supported by Microsoft

*Docker and Kubernetest are more open source oriented

Hope this help.
Best regards


text:
Q: How to include record after group by and count I have a table that tracks likes for users. Now I get the top 4 by using this line:
Liked_item.group('name').order('count_id desc').count('id').take(4)

This results in an array like this:
=> [["Name1", 10], ["Name 2", 8], ["Name 3", 5], ["Name 4", 3]]

Now instead of just the name and the number I would like to include the full record (The likes are not tied to a model, that's why I have to group by :name). What is the best way to do this?

A: It looks like a candidate for using a scope:
class LikedItem
  scope :by_name, ->(name) { where(name: name) }
end

Usage:
LikeItem.by_name(name)

which will return you an ActiveRecord collection of all likes for given name.
If you indeed want to have a hash with name as key and list of like_items as value, you can use Ruby (which is not recommended):
LikeItem.all.group_by(&:name).each_with_object({}) do |(name, collection), hash|
  hash[name] = { collection: collection, count: collection.size }
end


text:
Q: CSS: Submit button width:auto not wide enough in Safari I am having the most frustrating problem. I am trying to put a text input field and a submit button joined together on the same line.
Everything looks great when I view it in Firefox, but on Safari, the width of the submit button is not as wide as it should be.
Notice the "JOIN NOW" button in this image:

Could anyone help me out in figuring out what's going wrong here?
Here's a link to the Fiddle: https://jsfiddle.net/bf2qaycr/

.form-button-append {
  position: relative;
  display: flex;
  align-items: center;
}
.form-button-append input {
  border-right: 0;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}
.form-button-append button {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}
button, input {
    outline: none;
    box-shadow: none;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    -webkit-border-radius: 0;
    border-radius: 0;
    color: #3b3b3b;
    font-family: inherit;
    font-size: inherit;
    text-decoration: none;
    display: inline-block;
    white-space: nowrap;
    margin: 0;
    padding: 0.2em 0.4em;
    width: 100%;
    -webkit-transition: all 0.3s ease-in-out;
    transition: all 0.3s ease-in-out;
    border-width: 1px;
    border-style: solid;
    border-color: #d4d4d4;
    background: #fff;
    overflow: visible;
}
button {
  width: auto;
  cursor: pointer;
  background: #666;
  color: #fff;
}
<div class="form-button-append">
  <input id="EmailJoin" placeholder="Email Address" type="email">
  <button type="submit">JOIN NOW</button>
</div>


text:
Q: How should I use "will / would" and "tomorrow / today" in reporting yesterday's conversation about an action today? I am talking with my friend, I want to tell him about the meeting with another friend who borrowed some money from me.
what I said him:

"when I met him yesterday, he told me, he will give my money today"

or

"when i met him  yesterday, he told me I will give your money tomorrow"

Which is correct ?

A: Both the sentences you've written are incorrect. You can say it like :
When I met him yesterday, he told me that he would give my money the next day(or today).
When converting to indirect speech "will" will be changed to would (as the reporting verb is in past tense).
For tomorrow, "the next day" should be used but here, since you're mentioning "yesterday" before the indirect speech, you can use "today".

A: If by correct you mean grammatical, then both sentences are correct. The second utterance (When I met him yesterday, he told me: "I will give you your money tomorrow") reports your friend's exact words - indicated here by the speech marks (i.e. direct speech). The use of direct speech in the spoken reporting of what someone told you, however, is very unusual and needs to have the appropriate prosody to be easily interpreted.
The first utterance (When I met him yesterday, he told me, he will give me my money today) uses indirect / reported speech, which is far more common in spoken language than direct speech. When reporting what was said to them, speakers often backshift the tense of the verb, so that the words "I will give you the money" become: He said he would give me the money.
However, backshift is not mandatory. Very often speakers retain the tense of the verb if they believe that what was said to them still holds true. So, for example, if Friend A told me yesterday "I will give you the money tomorrow" and I see Friend B early in the morning of today (firmly believing that A will keep his promise), then I can say:

When I met him yesterday, he told me he will give me my money today.

Of course, if it is the end of the day, and the probability of getting your money back is now low, then you would use would:

When I met him yesterday, he told me he would give me my money today.

Note: if you are learning this grammar for an exam, you are probably better off sticking with the backshifted version, which some consider to be the default usage in such contexts.

A: Both are wrong. What you need is "indirect speech". And the rule is to make each sentence one degree past. Because time has passed between the moment of speaking and the time of the report. To be more explanatory:
I said, 'I'm not very happy at work.' I told her I was not very happy at work.
They said: 'We're going home.' They told us they were going home.
'I've been working,' she said. She said she had been working.
'What happened to make her so angry?' he asked. He asked what had happened to make her so angry.
According to the rule, we need to correct your sentence as follows:
When I met him yesterday, he told me that he would give my money that day.
Will becomes (one degree past tense) would.
Today becomes (one degree past tense)that day.
For more examples of indirect speech please see:
http://dictionary.cambridge.org/grammar/british-grammar/reported-speech-indirect-speech


text:
Q: Very small numbers in Fortran Is it possible to achieve very small numbers in Fortran like 1E-1200? I know how to do it in python, but my code for master's thesis runs too slow. My supervisor recommends me to use Fortran, but I am not sure if this is a problem.

A: The previous answers suggesting use of REAL128 from ISO_FORTRAN_ENV describe a non-portable solution. What you would get here is a real type whose representation is 128 bits, but that says nothing about the range or precision of the type! For example, some IBM systems have a 128-bit real kind that is actually two doubles with an offset exponent. This gets you more precision but not significantly more range.
The proper way to do this is to use the SELECTED_REAL_KIND intrinsic function to determine the implementation's kind that supports the desired range. For example:
integer, parameter :: bigreal = SELECTED_REAL_KIND(R=1200)
real(KIND=bigreal) :: x

If the implementation doesn't have a real kind that can represent a value with a decimal exponent of plus or minus 1200, you'll get an error, otherwise you'll get the smallest appropriate kind.
You could also specify a P= value in the call to indicate what minimum precision (in decimal digits) you need.

A: The short answer is yes.
Modern compilers typically support so-called quad precision, a 128-bit real. A portable way to access this type is using the ISO_FORTRAN_ENV. Here is a sample program to show how big and small these numbers get:
program main
   use ISO_FORTRAN_ENV, only : REAL32, REAL64, REAL128

   ! -- tiny and huge grab the smallest and largest
   ! -- representable number of each type
   write(*,*) 'Range for REAL32:  ',  tiny(1._REAL32),  huge(1._REAL32)
   write(*,*) 'Range for REAL62:  ',  tiny(1._REAL64),  huge(1._REAL64)
   write(*,*) 'Range for REAL128: ', tiny(1._REAL128), huge(1._REAL128)
end program main

The types REAL32, REAL64, and REAL128 are typically known as single, double, and quad precision. Longer types have a larger range of representable numbers and greater precision.
On my machine with gfortran 4.8, I get:
mach5% gfortran types.f90 && ./a.out
 Range for REAL32:     1.17549435E-38   3.40282347E+38
 Range for REAL62:     2.2250738585072014E-308   1.7976931348623157E+308
 Range for REAL128:    3.36210314311209350626E-4932   1.18973149535723176502E+4932

As you can see, quad precision can represent numbers as small as 3.4E-4932.

A: Most Fortran compilers support REAL128 data format which matches IEEE binary128. Some support also REAL80 with similar range, matching C long double.  These don't have performance of REAL64 but should be much faster than python.


text:
Q: how to include a header file in VB I can write program VB 6.0, but I don't know how to include a file in VB 6.0.
In c it was
include "aa.h"

But I really don't know how to include this "aa.h" in my VB program.

A: Comments indicate that you are trying to share a variable between all modules. Just declare a Public variable in a .bas module:
Public foo As String

And, by the way, VB6 is totally different from C.

A: You don't. The purpose of header files in C is to declare (function) prototypes for libraries that you use.

*

*If your C function is available as a COM component (OCX), then you can use the OCX as an external component.

*In classic Visual Basic (up to 6.0) you can declare dependencies to external libraries if those libraries reside inside DLLs. For this you must use the declare feature of Visual Basic. This is basically the Visual Basic variant of the prototype used in the .h file. You must manually convert the C prototypes you want to use from the .h file to VB syntax: e.g. the C prototype BOOL foo(LPCSTR lpString, HWND hWnd) becomes Declare Function foo Lib "a.dll" (ByVal lpString As String, ByVal hwnd As Long) As Long

*If your C functionality is a static libary (.lib), then you cannot use this libary directly. Instead, you must create a DLL or OCX out of it (using C), and use one of the above VB features for external dependencies.

A: Goto

Menu -> Projects -> Components

and choose from the list of Components available
or for adding references

Menu -> Projects -> References

and choose from the list of References available
and call/declare it like
Dim comp as YourComponent

A: The only available solution close to C include headers is to add a module with all your declares and shared variables.
For example:
Public variable1, variable2 as string...
Declare Function X alias Y...


text:
Q: c# Dynamic Where clause in a lambda I have a page that allow the user to search by multiple fields. One can be used or all. The user can set the operator per field to Equals, Contains, Starts With, etc... Looks like this
I am using EntityFrame Work and retrieving the data using a lamba like this one:
listOfPeople = adDB.People.Where(x => x.LastName.StartsWith(lastName) && x.FirstName.StartsWith(firstName)).OrderBy(x => x.LastName)

The question, How do I dynamically create the where clause depending on the data provided by the user?

A: You can use something along the lines of a Func factory to do this since the where clause takes in a Func.
Example:
public class Program
{
    public static void Main(string[] args)
    {
        var people = new[]
        {
            new Person {FirstName = "Hello", LastName = "World"},
            new Person {FirstName = "Foo", LastName = "Bar"},
        };

        Console.WriteLine(people.Where(FuncFactory.GetFilterFunc<Person>(FilterType.Contains, x => x.FirstName, "ello")).Any());
        Console.WriteLine(people.Where(FuncFactory.GetFilterFunc<Person>(FilterType.Equals, x => x.FirstName, "ello")).Any());
        Console.WriteLine(people.Where(FuncFactory.GetFilterFunc<Person>(FilterType.Contains, x => x.LastName, "ar")).Any());
        Console.WriteLine(people.Where(FuncFactory.GetFilterFunc<Person>(FilterType.Equals, x => x.LastName, "ar")).Any());

        Console.ReadKey();
    }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public enum FilterType
{
    Contains,
    Equals
}

public static class FuncFactory
{
    public static Func<T, bool> GetFilterFunc<T>(FilterType filterType, Func<T, IComparable> propFunc, string filter)
    {
        switch (filterType)
        {
            case FilterType.Contains:
                return x => (propFunc(x) as string).Contains(filter);
            case FilterType.Equals:
                return x => (propFunc(x) as string).Equals(filter);
            default:
                throw new ArgumentException("Invalid FilterType");
        }
    }
}

A: You probably want to use the Predicate Builder:
http://www.albahari.com/nutshell/predicatebuilder.aspx


text:
Q: Two seemingly identical sed commands, one works, the other doesn't. Can you tell me why? There's something I'm having trouble understanding concerning sed behavior.
sed -n "/pattern/,$p" < input.inp > output.out

gives the following error
sed: -e expression n°1, caractère 10: `,' inattendue

(my system is in french).
sed -n '/pattern/,$p' < input.inp > output.out

Works fine
I've personnally used commands like
sed -n "/begin/,/end/p" < input.inp > output.out

with both single or double quotes, and they work just fine.
In case it's useful, I have sed version: sed (GNU sed) 4.2.2

A: In double quotes, the shell, not sed, will evaluate $p. Since you probably haven't set a variable named p, sed will only see /pattern/,. To prevent this from happening, you'd need to escape the $ to the shell, by writing \$ instead:
sed -n "/pattern/,\$p" < input.inp > output.out

(You can imagine that using single quotes is a lot easier on the eyes and brain, unless you need shell variables in your expression.)


text:
Q: Rxjs Repeat Until items to process is zero I have an endpoint which receives an array of ids to do some processing.
The backend dev, asked me to send only 10 ids during rushhour, and 50 outside them.
The user enters in a field, all the ids they want to process (top 100).
What I need to do is, first, know how much ids send to the back, regarding the current time.
I haven't chunked the ids before hand, because I wanted to take a number of ids related to the condition mentioned before, so I was trying to repeat the whole obs until there are none ids to process.
There is another challenged, which is that it must have a delay of 1 min between each.
    concatMap(() =>
      of(null).pipe(
        map(() => this.isRushHour()),
        map(isRushHour => this.storeListToProccess.splice(0, isRushHour ? 10 : 50)),
        switchMap(p => this.createZones(p)),
        delayWhen(() => this.storeListToProccess.length ? interval(this.delayMs) : interval(0)),
        repeatWhen(()=> !!this.storeListToProccess.length)
      )
    )

Is there any way to achieve this or is prechunking the ids the only way to do it?

A: I would resolve you task in this way:
from(this.storeListToProccess).pipe(
  bufferCount(this.isRushHour() ? 10 : 50), // here we chunkify the whole array into groups of 10 or 50 elements
  concatMap((p) => merge(this.createZones(p), timer(this.delayMs)))
  // concatMap () => timer will make sure that no new request will be send, untill timer is complete
)

and that is basically it, if you don't need handle request results. If you do need to handle it, more information on the question is required.

A: I found a solution, (two, in fact). I will post the one using RXjs:
interval(1000)
  .pipe(
    takeWhile(()=> storeListToProccess.length>0),
    map(()=>storeListToProccess.splice(0, isRushHour() ? 1 : 2)),
    tap((IdsToSend)=> console.log(IdsToSend)),
    finalize(()=>console.log("Finished"))
  )
  .subscribe()


text:
Q: Python time.sleep every regular time intervals and function I need to start the execution of a function foo() every 10 seconds, and the foo() function takes a random time between 1 and 3 seconds to be executed.
import time
import datetime

def foo():
    # ... code which takes a random time between 1 and 3 seconds to be executed

while True:
    foo()
    time.sleep(10)

of course in the above example the function foo() is not executed every 10 seconds but every 10 + random seconds.
Is there a way to start executing foo() each exactly 10 seconds? I'm sure it's something related with threading but can't find a proper example.

A: Yes, it is related to threading as you want to spawn a different thread to execute your function asynchronously - the parent process will wait 10 seconds irrespective of how long the thread takes to execute.
This is a standard way to do this in python:
import threading

def print_some():
  threading.Timer(10.0, print_some).start()
  print "Hello!"

print_some()

See more here:
http://www.bogotobogo.com/python/Multithread/python_multithreading_subclassing_Timer_Object.php
So in your case it would be:
import threading
import time

def foo():
    threading.Timer(10.0, foo).start()
    print("hello")

if __name__ == '__main__':
    foo()

A: If you want threading here you go!
import threading

def foo():
   # does stuff

while True:
   t = threading.Thread(target=foo)
   t.start()
   time.sleep(10)

A: Sample code.
import time
import datetime

def foo():
    # ... code which takes a random time between 1 and 3 seconds to be executed

while True:
    start = time.time()
    foo(random number)
    end = time.time()  - start
    time.sleep(10 - end)


text:
Q: Count alternating up / down sequences Description of the problem :
Compute the number of all the sequences which go up down from some input n.
So the user input n; with that n then I create an array of numbers 1..n and then number the sequences with that property
Example: n = 4
1 3 2 4
1 4 2 3
2 3 1 4
2 4 1 3
3 4 1 2

Answer: 5
My program works but for some reason I sometimes get 0 instead of the answer.
#include <stdio.h>
#include <stdlib.h>

void *safeMalloc(int n) {
    void *p = malloc(n);
    if (p == NULL) {
        printf("Error: malloc(%d) failed. Out of memory?\n", n);
        exit(EXIT_FAILURE);
    }
    return p;
}

void swap(int *fir, int *sec) {
    int temp = *fir;
    *fir = *sec;
    *sec = temp;
}

void permute(int *array, int i, int length, int *count) {
    if (length == 2) {
        *count = 1;
        return;
    }
    if (length == i) {
        int v = 0, flag = 1;
        while (v < length) {
            if (v % 2 == 0) {
                if (array[v] < array[v + 1]) {
                    v++;
                } else {
                    flag = 0;
                    return;
                }
            }

            if (v % 2 != 0) {
                if (array[v] > array[v + 1]) {
                    v++;
                } else {
                    flag = 0;
                    return;
                }
            }
        }
        if (flag == 1) {
            /*
            int a;
            for (a = 0; a < length; a++)
                printf("%d", array[a]);
            printf("\n");
            */
            *count = *count + 1;
        }
    }
    int j = i;
    for (j = i; j < length; j++) {
        swap(array + i, array + j);
        permute(array, i + 1, length, count);
        swap(array + i, array + j);
    }
    return;
}

int main(int argc, char **argv) {
    int n;
    scanf("%d", &n);
    int *arr = safeMalloc(n * sizeof(int));
    int i;
    for (i = 0; i < n; i++) {
        arr[i] = i + 1;
    }
    int count = 0;
    permute(arr, 0, n, &count);
    printf("%d\n", count);
    return 0;
}

A: if you call tab(n,k) the number of updown sequence of length n with k being the last number in your sequence, you can write a recursive formula and implement it like that:
int N = 5+1;
int** tab = new int*[N];
for (int n = 0; n < N; n++) {
    tab[n] = new int[N];
    for (int k = 0; k < N; k++) {
        tab[n][k] = 0;
    }
}
tab[1][1] = 1;
for (int n = 2; n < N; n++) {
    for (int k = 1; k <= n; k++) {
        if (n % 2 == 0) {
            for (int j = 0; j < k; j++) {
                tab[n][k] += tab[n-1][j];
            }
        }
        else {
            for (int j = k; j < n; j++) {
                tab[n][k] += tab[n-1][j];
            }
        }
    }
}
int res = 0;

for (int j = 0; j < N; j++) {
    res += tab[N - 1][j];
}

A: You basically generate all permutations of the array elements and count the valid ones.
Your code has a minor flaw:

*

*the loop while (v < length) { goes one step too far: you access tab[v + 1] so the loop should stop at v < length - 1. As currently coded, it has undefined behavior.

You can further simply the code:

*

*there should be no need to special case length == 2.

*flag useless as you always return when you clear it.

*if (v % 2 != 0) is redundant: else would suffice.

Here is a fixed and simplified version:
#include <stdio.h>
#include <stdlib.h>

void *safeMalloc(int n) {
    void *p = malloc(n);
    if (p == NULL) {
        printf("Error: malloc(%d) failed. Out of memory?\n", n);
        exit(EXIT_FAILURE);
    }
    return p;
}

void swap(int *fir, int *sec) {
    int temp = *fir;
    *fir = *sec;
    *sec = temp;
}

void permutate(int *array, int i, int length, int *count) {
    if (i == length) {
        for (int v = 0; v < length - 1; v++) {
            if (v % 2 == 0) {
                if (array[v] >= array[v + 1]) {
                    return;
                }
            } else {
                if (array[v] <= array[v + 1]) {
                    return;
                }
            }
        }
        *count = *count + 1;
    } else {
        for (int j = i; j < length; j++) {
            swap(array + i, array + j);
            permutate(array, i + 1, length, count);
            swap(array + i, array + j);
        }
    }
}

int main(int argc, char **argv) {
    int n;
    if (scanf("%d", &n) == 1 && n > 0) {
        int *arr = safeMalloc(n * sizeof(int));
        for (int i = 0; i < n; i++) {
            arr[i] = i + 1;
        }
        int count = 0;
        permutate(arr, 0, n, &count);
        printf("%d\n", count);
    }
    return 0;
}

A: You can solve this without iterating through the permutations. Say you're trying to calculate f(n). Where can the new, high number go? It has to go in an 'up' position, which is an even position. You can have any valid sequence of odd length preceding it, and any valid sequence following it.
Let's say we're calculating f(n,k) where the highest val is in position k, zero indexed. This is zero for k even. For odd k we get:
f(n,k) = choose(n-1, k) * f(k) * f(n - k - 1)
To get f(n), sum f(n,k) over odd k < n.
We have to calculate the first few by hand.
f(0) = 1
f(1) = 1
f(2) = 1
f(3) = f(3,1) = choose(2,1) * f(1) * f(1) = 2 * 1 *1 = 2
f(4) = f(4,1) + f(4,3) = choose(3,1) * f(1) * f(2) + choose(3,3) * f(3) * f(0) = 3*1*1 + 1*2*1 = 5
f(5) = f(5,1) + f(5,3) = choose(4,1) * f(1) * f(3) + choose(4,3) * f(3) * f(1) = 4*1*2 + 4*2*1 = 16


text:
Q: Angular6 Default ContextMenu I am working on a project in Angular 6, where I have used (click)="actionNavigateAway()" to direct page to a new Url. This works perfectly fine on the left click. But on the right click, it shows up a context menu having options like Back, Reload, etc (as shown in the 1st photo).

Instead, what I want to show is the default context menu that we usually find on right clicking a link (figure 2). I have searched the web and found ways to make a custom contextmenu, but nothing for the default. Can you please help me with that? Thanks.

A: Take a look at this

If the a element has an href attribute, then it represents a hyperlink
  (a hypertext anchor) labeled by its contents.
If the a element has no href attribute, then the element represents a
  placeholder for where a link might otherwise have been placed, if it
  had been relevant, consisting of just the element's contents.

So it's not considered as a hyperlink.
Just add an empty href attribute. Like this,

  Not Working

 Working

A: If you need to use JS to route your link, but want the href context menu -you can use both. You can add a blank href or any href, and then pass the event to  prevent default on a function. like so
This link has both

Now the page won't try to route you to "/somepath" when you click that href link. You can either add more code to the function, or use a JS SPA router to handle the routing. You now have javascript handling your links, and a normal context menu. Since the context menu has an actual route -it will actually open if and only if you select to open in new tab. not an actual click

A: The default context menu is normally working on link, it's normal that nobody tried to reproduce it ^^
In your case, the only possible problem is that you're not aiming correctly the link
But you can also create a custom contextmenu like this : Angular 2: Implement a custom context menu

A: The context menu should work when right clicking a link with a href attribute.

This is a A tag without attributes

This A tag has a href attribute

This A tag has a onclick attribute

So that means that you should use the href attribute instead of a click handler.
Try and run the snippet and right click on the different 'links' to see what I mean.


text:
Q: Using mutable objects as a constant Adding final to a primitive type variable makes it immutable.
Adding final to an object prevents you from changing its reference, but is still mutable.
I'm trying to use ImageIcon as a final constant, but at the same time, I don't want the image to be changeable.  Is it okay to just use mutable objects as a constant, or are there any alternatives?
Example Constants:
public static final ImageIcon bit0 = new ImageIcon("bit0.png");
public static final ImageIcon bit1 = new ImageIcon("bit1.png");

Using the Constants:
JButton button = new JButton(ClassName.bit0);
JLabel label = new JLabel(ClassName.bit1);

A:
I'm trying to use ImageIcon as a final constant, but at the same time, I don't want the image to be changeable. Is it okay to just use mutable objects as a constant, or are there any alternatives?

Whether it's okay is up to you. :-) Exposing a public reference to a mutable object leaves it open to mutation, as you said, so probably not ideal.
In terms of alternatives: Since the JButton constructor you're using accepts Icon, and Icon is quite a simple interface with no mutation methods, you might want to create yourself an ImmutableIcon wrapper class and expose that.
E.g.:
class ImmutableIcon implements Icon {
    private Icon icon;

    public ImmutableIcon(Icon i) {
        this.icon = i;
    }

    public int getIconHeight() {
        return this.icon.getIconHeight();
    }

    public int getIconWidth() {
        return this.icon.getIconWidth();
    }

    public void paintIcon(Component c, Graphics g, int x, int y) {
        this.icon.paintIcon(c, g, x, y);
    }
}

then
public static final Icon bit0 = new ImmutableIcon(new ImageIcon("bit0.png"));

A: Because ImageIcon is a reference type (instead of primitive), final here only means that the reference will always point to the same object. It says nothing about the state of that object.
If you're concerned about someone changing the object's state, you can wrap it in another object whose interface you have control over, or simply upcast to Icon if your other uses of the icon allow for that, e.g.
public static final Icon bit0 = new ImageIcon("bit0.png");

I'd also reconsider whether you need to expose the icon variable as a class constant. If you only ever make one instance of the containing class, then there are no savings from reuse.
As for whether or not mutable class constants are okay in general, I don't think there's any convention discouraging it, it just isn't always that useful. And since they're not garbage collected, you must be careful not to leak memory.


text:
Q: 502 bad gateway error with upstream prematurely closed connection? I am trying to run an machine learning inference server on docker container with AWS sagemaker , Flask, Nginx and Gunicorn. I have tried running with  a c5.xlarge instance and c5.4xlarge instance on AWS sagemaker and it always breaks when run on a c5.xlarge instance.
When the request comes to check health of the application by loading the ML model which is around 300 mb. When inference endpoint is called, it checks if the model is up and running in the worker and if not get the ML model up and then run the prediction with data. I usually call the model with <=5MB data .
Nginx Config:
worker_processes auto;
daemon off; # Prevent forking

pid /tmp/nginx.pid;
error_log /var/log/nginx/error.log;

events {
  # defaults
}

http {
  include /etc/nginx/mime.types;
  default_type application/octet-stream;
  access_log /var/log/nginx/access.log combined;

  upstream gunicorn {
    server unix:/tmp/gunicorn.sock;
  }

  server {
    listen 8080 deferred;
    client_max_body_size 5m;

    keepalive_timeout 10000;

    location ~ ^/(ping|invocations) {
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;
      proxy_pass http://gunicorn;
    }

    location / {
      return 404 "{}";
    }
  }
}

gunicorn :
subprocess.Popen(['gunicorn',
                             '--timeout', str(model_server_timeout),
                             '-k', 'gevent',
                             '-b', 'unix:/tmp/gunicorn.sock',
                             '-w', str(model_server_workers),
                             '--error-logfile', '-',
                             '--access-logfile', '-',
                             '--preload',
                             'wsgi:app'])

I have looked at the timeout (it is already set at 60 secs for gunicorn), tried preloading the app, and the logs thrown to stdout have only upstream prematurely closed connection while reading response in the error.

A: How long does your container usually respond to requests? If you use the container in a hosted Endpoint, the container has to respond to requests within 60 seconds. It might be helpful to set the gunicorn timeout to be a little lower than 60 seconds.
https://docs.aws.amazon.com/sagemaker/latest/dg/API_runtime_InvokeEndpoint.html
It looks like the response time depends on the instance type. If this is the case, and you do want to use c5.xlarge instance type for example, you can try to create a batch transform job instead of using a real time inference endpoint. Batch transform job does allow >60 seconds response time for each request.
https://docs.aws.amazon.com/sagemaker/latest/dg/API_CreateTransformJob.html
Hope this helps!
-Han


text:
Q: PHP imagettftext always drawing black Basically when I draw text it's ending up black like this: http://i.stack.imgur.com/z675F.png
Instead of the color I'm allocated in PHP and the function.
Code:
    $finalImage = imagecreatefrompng($imageFile);
    $logo = imagecreatefrompng($logoImage);
    imagecopy($finalImage, $logo, $logoPosition['x'], $logoPosition['y'], 0, 0, imagesx($logo), imagesy($logo));
    $font = "arial.ttf";
    $fontSize = 10;
    $yOffSet = 15;
    $white = imagecolorallocate($finalImage, 255, 255, 255);
    foreach($pixelArray as $key => $x) {
        foreach($valueArray[$key] as $valueText) {

            imagettftext($finalImage, $fontSize, 0, $x, $yOffSet, $white, $font, $valueText);
            $yOffSet += 15;
        }
        $yOffSet = 15;
    }
    if($miscText != null) {
        foreach($miscText as $key => $text) {
            imagettftext($finalImage, $fontSize, 0, $text['x'], $text['y'], $white, $font, $text['text']);
        }
    }
    imagepng($finalImage,$saveFileName.".png");
    imagedestroy($finalImage);

It was working before, but then it just stopped and I have no clue why. It was after I changed the source image (Was generating fine) and I hadn't touched the code. I've tried all sorts of things with changing the colors, but I can't get it to display in anything other then black.

A: Fixed it by changing imagecolorallocate to imagecolorclosest since I already some white text on a logo I copy in:
//       imagecolorallocate....
$white = imagecolorclosest($im, 255, 255, 255);

A: Have you checked if the imagecolorallocate() function is returning boolean false, as it will if the allocation fails? If the $finalImage .png is 8bit, and your pure white color isn't in the source image's palette, this call will fail. You do say you changed the source image, so this is most likely why it's broken now.
$white = imagecolorallocate($finalImage, 255, 255, 255);
if ($white === FALSE) { // note the === -> strict type comparison
    die("Failed to allocate color 255/255/255")
}

The function will also simply return a number representing the color triplets, in this case it would 0xFFFFFF. You can try passing that into the imagegetttftext() call directly, see if that helps.

A: Use imagecreatetruecolor() to allocate the color:
$width = 500; //whatever width you need
$height = 200; //whatever height you need
$white = imagecolorallocate(imagecreatetruecolor($width, $height), 255, 255, 255);

That worked for me.


text:
Q: Theoretical Justification Behind the Mean of a Probability Distribution? In school, we always learned that:

*

*If $X$ is a random variable with a probability distribution of $f_X(x)$, then the mean of $x$ (i.e. expected value) is the integral $\int x f_X(x)\, dx$
This works out such that the average value of $X$ will correspond to this integral.
I have always accepted this fact at face value and never really tried to understand it beyond this point. This brings me to my question:
Is there a proof that shows why the average value of a random variable "x" is given by this integral? Or is this simply by definition?
Thanks!

A: It's simply by definition.
If you have studied some mechanics, you might notice that it is similar to finding the centre of mass of some object when given a density function.

A: Here's some intuition that works well when the random variable is discrete. Let's assume that $X$ is a random variable that takes values in $1,2,3,\dots, n$ with respective probabilities $p_1,p_2,\dots,p_n$.
What does it mean when we say $P(X=1) = p_1$? The frequentist notion of probability simply states that if we have a sequence of i.i.d. random variables $X_1,X_2,\dots,X_N$ equal in distribution to $X$ where $N$ is very large, then
$$f^N_1:=\frac{1}{N}\sum_{i=1}^N \mathbb{I}_{X_i=1} \approx P(X_1=1)=P(X=1).$$
That is, $p_k$ tells us (with high probability) the approximate proportion of random variables in $X_1,\dots,X_N$ that will be equal to $k$, which we denote by $f^N_k$.
So, the expected value of $X$ then tells us,
$$E[X] = \sum_{k=1}^n kp_k \approx \sum_{k=1}^n kf^N_k = \sum_{k=1}^n \frac{k}{N}\sum_{i=1}^N \mathbb{I}_{X_i=k} = \frac{1}{N}\sum_{i=1}^N \sum_{k=1}^n k\mathbb{I}_{X_i=k} = \frac{1}{N}\sum_{i=1}^N X_i.$$
The argument above isn't quite rigorous, and it's even a little circular (we use the law of large numbers for indicator functions to imply the law of large numbers for discrete random variables), but I think it gives a good sense of why the expectation operator is defined the way it is.
If $X$ is discrete but infinite state, the argument is almost exactly the same. In the continuous case, we can now suppose $X$ has pdf $f$. Then we can approximate $X$ by the discrete random variable,
$$X^n := \frac{\lfloor nX\rfloor}{n}.$$
Then the expected value of $X^n$ is,
$$E[X^n] = \sum_{z \in \mathbb{Z}} \frac{z}{n}\int_{\frac{z}{n}}^{\frac{z+1}{n}} f(y)\,dy.$$
This is essentially a Riemann sum that converges to $$\int_{\mathbb{R}} yf(y)\,dy$$
as desired.
Edit: Had a typo in my definition of $X^n$.
Edit 2: My argument above is non-rigorous. However, if you want a rigorous proof, the law of large numbers states exactly that the standard definition of expected value is equivalent to the notion of a long-term average. You can look up any proof of the law of large numbers.

A:
This works out such that the average value of $X$ will correspond to this integral.

Not exactly. There two different things here. One is the mean (or expected value) of a random variable. This can be computed as an integral, if the random variable is continuous (and well behaved), so that its probability law can be described by a density function $f_X(x)$
$$\mu = E[X]= \int f_X(x) dx $$
(If instead the random variable is discrete, the mean is computed as $E[X]= \sum_x x p(x)$ )
Secondly, there is the average (arithmetic mean, or sample mean) of a set of $n$ results of a experiment, which are regarded as "realizations" of a random variable $X$ (or, equivalently, as $n$ random variables, independent and identically distributed).
$$\bar X = \frac{\sum X_i}{n}$$
Notice a crucial difference: $\mu$ is a fixed number, while $\bar X$ is itself a random variable (takes different values in different experiments).
Your quoted assertion, actually says that in some sense $\bar X$ tends to $\mu$: if $n$ is large, almost always (under certain restrictions) the values will be be similar.
This is not always true, though. To learn about the restrictions, the precise meaning and the proof of this property, you need to read about the law of large numbers.
To get a general feeling of why this might be true, see forgottenarrow's answer.


text:
Q: Google Maps API for Business can be used for localhost URL? I'm working on a new project using geocoding, but now im testing my website locally. How can I register a local URL (ex: [http://localhost/myWebApp])? Or will I see the changes only if my web is on a webhosting service?

A: By using the javascript V3 api, you can just enter the api key in the script declaration. Example:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=enteryourapikeyhere&sensor=false"></script>

You can follow the required steps right here to implement it in your page:
Google Maps JavaScript API v3


text:
Q: jacobian of a dot product of 2 functions take the function $f: \mathbb R^3 \rightarrow \mathbb R^2$ an a function $g: \mathbb R^2 \rightarrow \mathbb R^2 $ defined via $$ f
\begin{pmatrix}
 x\\
y\\
z
\end{pmatrix} =
\begin{pmatrix}
 x+z^3\\
xyz
\end{pmatrix}
$$
and $$ g
\begin{pmatrix}
 s\\
t
\end{pmatrix} =
\begin{pmatrix}
 s^2 + t\\
s+t
\end{pmatrix}
$$
compute the vector  $$ J(g \circ f) \begin{pmatrix} 1\\ 2\\ 3 \end{pmatrix}$$ , that is the jacobian of the dot product

A: I can see that you have no trouble bar silly mistakes in computing the Jacobian. More precisely, we have :
$$
Df(x,y,z) = \begin{pmatrix}
1 & 0 & 3z^2 \\
zy&xz&xy
\end{pmatrix} ;
Dg(s,t) = \begin{pmatrix}
2s & 1 \\
1&1
\end{pmatrix}
$$
Now, the chain rule is the following : (with variables $a,b,c$ to avoid confusion)
$$
D(g \circ f)(a,b,c) = Dg(f(a,b,c)) \times Df(a,b,c)
$$
So, in steps , given a point $(a,b,c)$ :

*

*Find $f(a,b,c)$.

*Find $Df$ evaluated at $(a,b,c)$, and $Dg$ evaluated at $\color{green}{f(a,b,c)}$ , and not $\color{red}{(a,b,c)}$.

*Multiply them as matrices, in the order specified in the formula.
For example, you have $(a,b,c) = (1,2,3)$. We find that $f(1,2,3) = (28,6)$.
Now, we have $Df(1,2,3) = \begin{pmatrix}
1 & 0 & 27 \\
6 & 3 & 2
\end{pmatrix}$.
We also have $Dg(28,6) = \begin{pmatrix}
56&1\\1&1
\end{pmatrix}$
And therefore, multiplying them in that order gives
$$
\begin{pmatrix}
56&1\\1&1
\end{pmatrix} \times \begin{pmatrix}
1 & 0 & 27 \\
6 & 3 & 2
\end{pmatrix} = \begin{pmatrix}
62 & 3 & 1514\\
7 & 3 & 29
\end{pmatrix}
$$
Which is the answer.


text:
Q: Which store should I use: Document storage or SQLite? I'm pulling a list of text posts from an API. Each post has a title and description. I need to persist all of them in my iPhone app.
Which storage should I use ? Should I use Document storage or should I use CoreData SQLite store?

A: If you want to perform query on them, it is better to use core data or sqlite. Otherwise, I think document file is ok.

A: CoreData is a good and efficient way to persist data in your app. But consider that in such case is up to you to clean up too old data to avoid using too much storage space in your device. Besides consider that CoreData is very good to persist object relationships, while in your case probably you don't need to persist an object graph but just a list of post data and so you will not take benefit of the querying feature of CoreData.
But if you're using a network based API you may also take benefit of the data caching provide by the API and use the iOS network caching mechanism. To simplify things, you can take advantage of opensourced network frameworks such as MKNetworkKit which will persist the cached data in the file system and will get rid of them as soon as they expire or after a customizable time (days, weeks, months). Or if you don't want to use a 3rd party tool, you can still use the NSURLCache object provided by Apple with iOS. This approach is much more simpler than core data one: in such case you will still fetch data from the network and if it has been cached yet no network path will be followed and data will be directly taken from the file system.

A: With iCloud, documents make more sense but @yibuyiqu is right that if you want to query against your data a DB is best.
You can put your searchable and initially displayable data in the DB and have it point to the file that holds the full data (use a GUID for the filename).  This way if you use iCloud your data is ready to export because it's already in a document, which it expects.
Another benefit is search performance goes up the less data there is in the DB.  So if you're storing images or other heavy data, having that external to the DB is best.

A: You can use UIManagedDocument to get the benefits of both.  You'll also be in a position to add iCloud syncing later.


text:
Q: How do I parse a currency value as *big.Int in Go? I want to parse a string like "12.49" into a *big.Int in Go. The resulting *big.Int should represent the amount of cents in the given value, in this case 1249. Here are some more examples of inputs and their expected outputs:

*

*"3": 300

*"3.1": 310

*".19": 19

I already tried working with *big.Float and its Int function, but realized, that *big.Float does not provide arbitrary precision.
Right now I'm using this algorithm, but it seems fragile (Go Playground link):
func eurToCents(in string) *big.Int {
    missingZerosUntilCents := 2
    i := strings.Index(in, ".")
    if i > -1 {
        missingZerosUntilCents -= len(in) - i - 1
        if missingZerosUntilCents < 0 {
            panic("too many decimal places")
        }
    }
    in = strings.Replace(in, ".", "", 1)
    in += strings.Repeat("0", missingZerosUntilCents)
    out, ok := big.NewInt(0).SetString(in, 10)
    if !ok {
        panic(fmt.Sprintf("could not parse '%s' as an interger", in))
    }
    return out
}

Is there a standard library function or other common way to parse currencies in Go? An external library is not an option.
PS: I'm parsing Nano cryptocurrency values, which have 30 decimal places and a maximum value of 133,248,297.0. That's why I'm asking for *big.Int and not uint64.

A: Update: Seems like this solution is still buggy, because an inaccurate result is reported after multiplication: https://play.golang.org/p/RS-DC6SeRwz

After revisiting the solution with *big.Float, I realized, that it does work perfectly fine. I think I forgot to use SetPrec on rawPerNano previously. I'm going to provide an example for the Nano cryptocurrency, because it requires many decimal places.
This works as expected (Go Playground link):
func nanoToRaw(in string) *big.Int {
    f, _ := big.NewFloat(0).SetPrec(128).SetString(in)
    rawPerNano, _ := big.NewFloat(0).SetPrec(128).SetString("1000000000000000000000000000000")
    f.Mul(f, rawPerNano)
    i, _ := f.Int(big.NewInt(0))
    return i
}

Thanks @hymns-for-disco for nudging me in the right direction!


text:
Q: javax.persistence.Entitymanager: remove() method Does remove(Object entity) method of EntityManager work only on those objects got from find() method?
I have following code snippet:
public void deletePerson() {
    EntityManager em = getEntityManager();
    Person p = new Person("x", "y", 200);
    em.remove(p);
}

But it is not removing the particular entry from database.
When I tried something like below:
public void deletePerson() {
    EntityManager em = getEntityManager();
    Person p = em.find(Person.class, 200);
    em.remove(p);
}

It's working fine.

A: Yes in case of merge or remove operation you have to use a find() operation and then use the remove method on the retrieved entity.

A: Quoting from ObjectDB's manual on deleting JPA entity objects:

In order to delete an object from the database it has to first be
  retrieved (no matter which way) and then in an active transaction, it
  can be deleted using the remove method.
An IllegalArgumentException is thrown by remove if the argument is not
  a an instance of an entity class or if it is a detached entity.

When creating object with new operator, it becomes a detached entity, you need to persist it if you want to remove it.
When retrieving entity, you are retrieving persistent entity.

A: With JPA, you can remove an entity without retrieving it by simply executing a delete statement:
javax.persistence.Query q= entityManager.createQuery("delete from A where id = :id");
q.setParameter("id", "value of id to delete");
int deletedRows = q.executeUpdate();

A: Something to that direction. EntityManager.remove works only for managed entities. How you obtained these managed entities does not matter, it can be for example:

*

*via JPQL query

*via Criteria API query

*find method in EntityManager

*by following relationship from some other entity.

*created new entity and persisted it

But simply creating new object and trying to remove it does not work, because this new object is not managed entity. Also entity should not be yet detached.
Life of entity is quite much as follows, all in same transaction (entities outside their transaction are not managed):
Entity ent = new Entity(1); //entity is in new state, EntityManager never know
                            //anything about it
em.persist(ent); //entity is managed as long as not disconnected
                 //from EntityManager
em.clear(); // all previously managed entities, including ent, are now detached

Entity same = em.find(1); //managed same
em.remove(same); // entity is removed


text:
Q: Embedded Linux device blocking RS485 bus during startup I'm having trouble with an industrial Linux computer I'm working with to achieve communication over an RS485 bus with multiple connected devices. What I've encountered is that the IO pins used by the RS485 USART driver are set to different levels at startup instead of going to the RS485 idle/tri-state. As a result, the other devices on the bus are blocked for more than 30 seconds while the device boots up, triggering all sorts of external problems. The course of events can be viewed in the attached image, where I've measured the output voltages with an oscilloscope during startup.
My guess is that the actual driver is not started until the voltage levels reach their tri-state levels (e.g. ~2.2V for this device). After that everything works as expected.
I've tried to find any config-files to set the default IO level of the pins at boot (thinking this may be set by the bootloader) to no avail.
Also, I've tried to apply a startup-script to run "early enough" to set DATA- high, but the device in question does not provide any interface to control these pins as regular GPIOs as far as I can tell.
Any help, tips or insights would be much appreciated!
EDIT: I am not an experienced Linux developer, so please highlight if I've left out any important details.
Some specs:

*

*ARM920T rev 0 (v41) CPU

*Proprietary distribution of Linux 2.6

*Uses Busybox

*Atmel USART drivers

Extract from boot log:
Linux version 2.6.28.10 (root@) (gcc version 4.1.2) #94 PREEMPT Tue Oct 29 10:22:19 CET 2013
CPU: ARM920T [41129200] revision 0 (ARMv4T), cr=c0003177
/...
.../
RS485 mode for port /dev/ttyS3 enabled
/...
... (I'm guessing the ~30 secs elapse here)
.../
atmel_usart.3: ttyS3 at MMIO 0xfffcc000 (irq = 9) is a ATMEL_SERIAL
atmel_serial.3: Putting the RS485 RTS pin down
/...
...
.../
Full boot log: https://drive.google.com/file/d/0B2XYl1mNCa8jNUZ5V0Nic1hkU0U/view
Similar issue:
Possibly a similar issue is discussed here: UART initialisation: Prevent UART to pull RTS high
But I'm not sure how to proceed with the suggested solution.

A: This is little more than wild speculation, but it might be worth adding a start-up script that echoes a NULL character to the device (e.g. /dev/ttyS1 or whatever) as early as possible during start-up. This might be enough to kick the driver into initialising the hardware.
You could also try to locate the driver in the Linux source to look at how it starts up.

A: Probably you have access to the source code, so you can investigate who and when mess with the that GPIO. Just grep the kernel source for the atmel gpio controller port addresses to figure out what happen. If you are lucky may be there will be kernel command line option that you can pass from the bootloader to set the line to what you need in advance.

A:
this answer may work if you can find required things mentioned below
  of your board!

Once I also had a same issue on PWM. There I found that my bootloader was responsible for the same, I changed in bootloader configuration and it started working fine.
Check your BSP provided by board vendor or third party (If you have the source), If your bootloader is U-boot you can find it inside U-boot-(source)/include/configs/(your-board).h there you can find configuration for RS484. As per your datasheet for the board you can check for other things which are muxed on the same pin and disable those if not required for boot time and enable RS485.
enabling/disabling can be done by changing the values 0, 1 or 2 as per your configuration and also you can simply disable anything just by commenting // out the line.


text:
Q: Does regular sky clouds stops the sun's ultraviolet rays? I have an argue with an ex-Doctor of Medicine about the amount of ultraviolet light reaching us under the clear day sun and under the 100% cloudy sky.
To what extent we can say that the sky clouds stops ultraviolet light from the sun?

A: Clouds don't absorb light (much), they reflect and refract it, and this applies to uv light in the same way as visible light. So a 100% cloudy sky will block uv light in the same way it blocks visible light. A quick Google suggests that heavy cloud cover will remove 80-90% of uv light. Anyone disputing this should try sunbathing on a cloudy day :-)
I've heard occasional claims that broken cloud cover can actually enhance uv levels in the unshaded areas by reflecting uv light into the breaks. However I've never come across any studies that prove this happens. While it seems vaguely plausible I'd be surprised if the effect was very big.


text:
Q: Looping through all available autofilter criteria one at a time in vba I was wondering if there was a way to get all the different autofilter criteria in a list in order to iterate through each criteria, to in the end copy and paste each different table that would appear to a separate sheet as it iterates through.
Ideally this would be run n times:
ActiveSheet.Range(AllRows).AutoFilter Field:=10, Criteria1:=CritVariable

Where n is the number of different CritVariables there are.
I'd like to stress that I know how to copy and paste in the macro itself, but I was curious how to iterate through all the different criteria because the criteria could be different depending on the day. If a list of it isn't available how would I best go about iterating through the criteria?

A: You can study and adapt the following. Here is an outline of what is going on.

*

*I have a staff-table starting at cell A5, with a list of Offices in
column G;

*I'm copying from G5 downwards (assuming there are no blanks in this column's data) to W1;

*From range W1 downwards I am removing duplicates;

*Then I'm looping through this data, using Advanced Filter to copy the data for each office to an area starting at cell Z1;

*This filtered data is then moved (Cut) to a new worksheet, which is named from the current Office name (the criteria);

*After each Advanced Filter the cell W2 is deleted, making the value in W3 move up, so that it can be used for the next filter operation.

This does mean that when you press Ctrl-End to go to the last-used cell it goes further than it needs to. You can find a way to resolve this if necessary ;).
Sub SheetsFromFilter()
    Dim wsCurrent As Worksheet
    Dim wsNew As Worksheet
    Dim iLeft As Integer

    Set wsCurrent = ActiveSheet
    Application.ScreenUpdating = False
    Range("G5", Range("G5").End(xlDown)).Copy Range("W1")
    Range("W1").CurrentRegion.RemoveDuplicates Columns:=1, Header:=xlYes
    iLeft = Range("W1").CurrentRegion.Rows.Count - 1
    Do While iLeft > 0
        wsCurrent.Range("A5").CurrentRegion.AdvancedFilter xlFilterCopy, _
            wsCurrent.Range("W1:W2"), wsCurrent.Range("Z1")
        Set wsNew = Worksheets.Add
        wsCurrent.Range("Z1").CurrentRegion.Cut wsNew.Range("A1")
        wsNew.Name = wsCurrent.Range("W2").Value
        wsCurrent.Range("W2").Delete xlShiftUp
        iLeft = iLeft - 1
    Loop
    wsCurrent.Range("W1").Clear
    Application.ScreenUpdating = True
End Sub

BTW I don't intend to modify this for your specific file; this is something that you should do (or pay someone to do ;) ).
BTW It could be done using the normal (rather than Advanced) Filter. You would still copy the column and remove duplicates. This would have the benefit of not increasing the apparent size of the worksheet too much. But I decided to do it this way ;).
Added: Well, I felt inspired to achieve this with AutoFilter as well:
Sub SheetsFromAutoFilter()
    Dim wsCurrent As Worksheet
    Dim wsNew As Worksheet
    Dim iLeft As Integer

    Set wsCurrent = ActiveSheet
    Application.ScreenUpdating = False
    Range("G5", Range("G5").End(xlDown)).Copy Range("W1")
    Range("W1").CurrentRegion.RemoveDuplicates Columns:=1, Header:=xlYes
    iLeft = Range("W1").CurrentRegion.Rows.Count - 1
    Do While iLeft > 0
        Set wsNew = Worksheets.Add
        With wsCurrent.Range("A5").CurrentRegion
            .AutoFilter field:=7, _
                Criteria1:=wsCurrent.Range("W1").Offset(iLeft).Value
            .Copy wsNew.Range("A1")
            .AutoFilter
        End With
        wsNew.Name = wsCurrent.Range("W1").Offset(iLeft).Value
        iLeft = iLeft - 1
    Loop
    wsCurrent.Range("W1").CurrentRegion.Clear
    Application.ScreenUpdating = True
End Sub

[Both procedures could be improved using Defined Names and some error handling/checking.]

A: if you want you can build a new collection which will have an array of only unique values and then loop over them. you will know that each

A: I know it's late and you've already selected an answer, but I'm working on a similar project involving a pivot table and decided to do it this way:
'Here I'm Filtering a column of Week numbers to get rid of non-numbers
'From a pivot table

'I select sheet where my underlying pivot data is located and establish the range
'My data is in column 2 and it ends after "DSLastRow" Rows starting at Row 2

Sheets("DataSheet").Select
DSLastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

'I create and redim an array that is large enough to hold all of the data in the range
Dim FilterCriteria(): RedimFilterCriteria(1 To DSLastRow)

For r = 2 To DSLastRow 'r for row / my data has a header in row 1
    If Cells(r, 2).Value <> "" Then 'again, starting in column B (2)
        'Check if it's already in the FilterCriteria Array
        For CheckFCA = 1 To r
            'Jumps to next row if it finds a match
            If FilterCriteria(CheckFCA) = Cells(r, 2).Value Then GoTo Nextr
            'Saves the value and jumps to next row if it reaches an empty value in the array
            If IsEmpty(FilterCriteria(CheckFCA)) Then
                FilterCriteria(CheckFCA) = Cells(r, 2)
                GoTo Nextr
            End If
        Next CheckFCA
    End if
Nextr:
Next r
'At this point FilterCriteria() is filled with all of the unique values

'I'm filtering a pivot table which is why I created the unique array from
'the source data, but you should be able to just loop through the table
Sheets("Pivot").Select
ActiveSheet.PivotTables("ReportPivot").PivotFields("Week").ClearAllFilters
With ActiveSheet.PivotTables("ReportPivot").PivotFields("Week")
    For FilterPivot = 1 To DSLastRow
        'I'm filtering out all non-numeric items
        If IsEmpty(FilterCriteria(FilterPivot)) Then Exit For
        If Not IsNumeric(FilterCriteria(FilterPivot)) Then
            .PivotItems(FilterCriteria(FilterPivot)).Visible = False
        End If
    Next FilterPivot
End With


text:
Q: How do I get all timestamps associated with an ID and aggregate it them into total time elapsed? I have a sample table:
id   timestamp
1    2020-02-03T19:25:41.961Z
1    2020-02-03T19:25:42.000Z
1    2020-02-03T19:26:33.147Z
2    2020-02-03T20:21:29.684Z
2    2020-02-03T20:21:29.705Z

In BigQuery, I want to group all of the columns with the same ID together, and then get the total elapsed time between all of the timestamp cols for that ID.

A: You can use timestamp_diff():
select id, timestamp_diff(max(timestamp), min(timestamp), second) as diff_seconds
from t
group by id;


text:
Q: SSL Certificates doesn't work My problem is that I have an application on .net is mvc
The application make "Facturas Electronicas" for the company that I work.
If I run the application on my computer from the visual studio, the application works fine.
But if I publish the app to another server the application doesn't make the "Factura Electronica", but before this erros the application works fine on other servers.
All started when I publish another app with the same code, and needs the same certificates but it is to other product and i need the two applications.
After checking all the code I realize that the problem was the certificate a pfx file,
when the app try to execute this
X509Certificate2 cert = new X509Certificate2(certificadoDemo, claveCertificadoDemo);

the navigator return this

This webpage is not available

the expiration of the pfx file is until july 2014
Do anyone knows what is going on?
adding this
X509KeyStorageFlags.MachineKeySet

to that line of code i resolved the problem
this is the new line of code
X509Certificate2 cert = new X509Certificate2(certificadoDemo, claveCertificadoDemo, X509KeyStorageFlags.MachineKeySet);

thanks

A: Your question cannot be answered without a detailed exception. Either turn off customErrors in the web.config file (in which case, the entire exception will be sent to the browser) or catch errors in Global.asax Application_Error event handler and log the errors to a file somehow (using System.Diagnostics preferably). Without more sample code, we can't even know which constructor you're calling because X509Certificate2 has 5 constructors which take two parameters. See http://sscce.org/ on how to ask questions.


text:
Q: Does Far Cry 4 need any bandwidth? I'm looking to get Far Cry 4 for my computer. I do believe the game is thirty gigabytes, and my internet is capped. If I were to get the game on a disk, would it still use bandwidth, or would it install directly to my hard drive?

A: Though the majority of the game will be installed, forum posts such as this (from 2016) suggest that:

the version that comes on the DVD's is outdated by almost 2 years

and that

and many of those 8 patches were several gig in size anyway

This post is, in itself, probabably outdated by now.

A: Once installed, Far Cry 4 can be played in offline mode, which uses very little, if any, bandwidth.

A: http://forums.nexusmods.com/index.php?/topic/452910-installing-skyrim-from-the-dvd/
This post details how to force Steam to install a game from the disk instead of download. There will most likely be an update or 2 after install, but it probably won't even reach a half gig.


text:
Q: Не работает модальное окно с версией Jquery? Всем привет с версией Jquery-1.4.3.min.js модальное окно работает нормально. Но мне на сайте нужна более новая версия jquery-1.10.1.min.js. Подключаю ее и вуаля ничего не работает. Выдает ошибку в коде.
$('a[data-reveal-id]').live('click', function(e) {
undefined is not a function

Что можно сделать?
A: Сразу же нашел решение. Убрали метод live. Теперь используем On.


text:
Q: Why am I getting a file_put_contents error even after clearing the cache and modifying storage, vendor and bootstrap permissions CentOS? I have read many similar posts with a similar error, but after doing the recommended solutions for each of them, I still have not had any success sending a POST API request to my Laravel API instance hosted locally on my vagrant CentOS server.
The error message:
ErrorException: file_put_contents(/vagrant/html/test/storage/framework/cache/data/a2/76/a2767fcc897a34fbe4b83d0a6ad5f44445bd07a5):
 failed to open stream: No such file or directory in file
/vagrant/html/test/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php on line 135

What I have tried:
Running the following commands both on the local Laravel instance and on Vagrant:
chmod -R 777 storage/ bootstrap/ vendor/

rm bootstrap/cache/config.php

sudo chown -R root: storage/ vendor/

Thanks in advance for any help! Cheers!


text:
Q: QList filled in constructor but accessed in other function I'm not very sure about this C++ code.
#include <QList>
#include <QString>

using namespace std;

class MyClass {
    public:
            QList<QString> m_List;

    MyClass() {
            QString text1("foo1");
            m_List << text1;

            QString text2("foo2");
            m_List << text2;
    }

};

int main() {
    MyClass myClass;
    for (int i = 0; i < myClass.m_List.size(); ++i) {
            cout << myClass.m_List.at(i).toStdString()  << endl;
    }
}

I don't understand why it's work because I create and add QString in my QList in the constructor.
So, my instance text1 shouldn't exist anymore at the end of constructor and when I access to QList element in the loop this shouldn't work, but the output look nice :
foo1
foo2

cppcheck don't say anything about this code.
This code is it correct ?

A: Your code is correct.
Yes, the local instances do not exist anymore. But that does not matter. QList stores data by value. What ever you pass to a QList is copied and the copy is stored in the list. So even if your local QString objects where discarded when leaving the constructor, the copies in QList still exist.

A: It seems that for a QString it stores the value in the array
http://qt-project.org/doc/qt-5/qlist.html#details

Internally, QList is represented as an array of pointers to items
  of type T. If T is itself a pointer type or a basic type that is no
  larger than a pointer, or if T is one of Qt's shared classes, then
  QList stores the items directly in the pointer array.

Also take a look at: http://qt-project.org/doc/qt-5/implicit-sharing.html#list-of-classes


text:
Q: I should have tried to write some more details erlier.
I need a kind of questionnaire with questions with only one of several answers you can choose.
The questionnare is grouped into <fieldset>elements which are made visible after the last groups question answered.
Due to design reasons, I have a written the with several button elements which are set to type "button".
I cannot let the page reload inbetween answering the questionnaire.

Now I want to pass their value, if clicked to PHP to save them to a database.

jQuery(document).ready(function($) {
      var current = 1,
        current_step, next_step, steps;
      var buttonname = '';
      var buttonvalue = '';
      var btnarray = [];
      steps = $(".fieldset").length;
      $(".next").click(function() {
        buttonname = $(this).attr('name');
        buttonvalue = $(this).val();
        btnarray.push(buttonname + ":" + buttonvalue);
        current_step = $(this).parents("fieldset");
        next_step = $("fieldset").eq(current);
        buttonvalue = $(this).val();
        current_step.hide();
        next_step.show();
        //setProgressBar(++current);

      });

      });
.parallelogram {
  background: #fff;
  width: 100%;
  height: auto;
  position: relative;
  border: solid 5px #0793EB;
  margin-left: -10px;
  transform: skew(-15deg);
  font-size: 24pt;
  color: #0793EB;
}

<form id="reg_form" novalidate action="action.php" method="POST">
  <fieldset>
  <button type="button" class="parallelogram next" name="topic[]" value="1">Button 1-1</button>

  <button type="button" class="parallelogram next" name="topic[]" value="2">Button 1-2</button>
 </fieldset>

   <fieldset hidden>
  <button type="button" class="parallelogram next" name="secondtopic[]" value="1">Button 2-1</button>

  <button type="button" class="parallelogram next" name="secondtopic[]" value="2">Button 2-2</button>
 </fieldset>
 </form>

In Firebug, I can see the parameters and also the array in the preview, but var_dump($_POST); does not give me anything.
Does anybody has an idea?
Thanks in advance.
Regards.

A: give buttons as array and you can access that in php.
  <button type="submit" class="parallelogram next" name="topic[]" value="1">Button 1</button>

      <button type="submit" class="parallelogram next" name="topic[]" value="2">Button 2</button>

   <?php

       $buttonData = $_POST['topic'];

  // do database operations
    ?>


text:
Q: outputting full sequential range of values i have a sql query:
  SELECT
  TAT,
  SUM(CASE WHEN [Month Entered] = 1 THEN 1 ELSE 0 END) JAN,
   SUM(CASE WHEN [Month Entered] = 2 THEN 1 ELSE 0 END) FEB,
   SUM(CASE WHEN [Month Entered] = 3 THEN 1 ELSE 0 END) MAR,
   SUM(CASE WHEN [Month Entered] = 4 THEN 1 ELSE 0 END) APR,
   SUM(CASE WHEN [Month Entered] = 5 THEN 1 ELSE 0 END) MAY,
   SUM(CASE WHEN [Month Entered] = 6 THEN 1 ELSE 0 END) JUN,
   SUM(CASE WHEN [Month Entered] = 7 THEN 1 ELSE 0 END) JUL,
   SUM(CASE WHEN [Month Entered] = 8 THEN 1 ELSE 0 END) AUG,
   SUM(CASE WHEN [Month Entered] = 9 THEN 1 ELSE 0 END) SEP,
   SUM(CASE WHEN [Month Entered] = 10 THEN 1 ELSE 0 END) OCT,
   SUM(CASE WHEN [Month Entered] = 11 THEN 1 ELSE 0 END) NOV,
   SUM(CASE WHEN [Month Entered] = 12 THEN 1 ELSE 0 END) [DEC]

  FROM
  [SalesDWH].[dbo].[TurnAround]
  where DATEPART(yyyy,[datetime entered])=2010
  GROUP BY TAT
  ORDER BY 1;

here's what it returns:
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| TAT | JAN | FEB | MAR | APR | MAY | JUN | JUL | AUG | SEP | OCT | NOV | DEC |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
|   0 |   0 |   0 |   0 |   3 |   0 |   0 |   0 |   0 |   0 |   0 |   0 |   0 |
|   1 |   1 |   0 |   0 |   0 |   0 |   0 |   0 |   0 |   0 |   0 |   0 |   0 |
|   7 |   0 |   0 |   0 |   0 |   1 |   0 |   0 |   0 |   0 |   0 |   0 |   0 |
|  18 |  28 |   0 |   0 |   0 |   0 |   0 |   0 |   0 |   0 |   0 |   0 |   0 |
|  19 |  39 |   0 |   0 |   0 |   0 |   1 |   0 |   0 |   0 |  53 |   0 |   0 |
|  20 | 106 |   0 |   0 |   0 |   0 |   0 |   2 |  17 |   0 |   1 |   2 |   0 |
|  21 | 113 |  12 |   0 |   0 |   0 |  22 |   1 |  81 | 137 |  27 |   1 | 110 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+

i would like the output to be:
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| TAT | JAN | FEB | MAR | APR | MAY | JUN | JUL | AUG | SEP | OCT | NOV | DEC |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
|   0 |     |     |     |   3 |     |     |     |     |     |     |     |     |
|   1 |   1 |     |     |     |     |     |     |     |     |     |     |     |
|   2 |     |     |     |     |     |     |     |     |     |     |     |     |
|   3 |     |     |     |     |     |     |     |     |     |     |     |     |
|   4 |     |     |     |     |     |     |     |     |     |     |     |     |
|   5 |     |     |     |     |     |     |     |     |     |     |     |     |
|   6 |     |     |     |     |     |     |     |     |     |     |     |     |
|   7 |     |     |     |     |   1 |     |     |     |     |     |     |     |
|   8 |     |     |     |     |     |     |     |     |     |     |     |     |
|   9 |     |     |     |     |     |     |     |     |     |     |     |     |
|  10 |     |     |     |     |     |     |     |     |     |     |     |     |
|  11 |     |     |     |     |     |     |     |     |     |     |     |     |
|  12 |     |     |     |     |     |     |     |     |     |     |     |     |
|  13 |     |     |     |     |     |     |     |     |     |     |     |     |
|  14 |     |     |     |     |     |     |     |     |     |     |     |     |
|  15 |     |     |     |     |     |     |     |     |     |     |     |     |
|  16 |     |     |     |     |     |     |     |     |     |     |     |     |
|  17 |     |     |     |     |     |     |     |     |     |     |     |     |
|  18 |  28 |     |     |     |     |     |     |     |     |     |     |     |
|  19 |  39 |     |     |     |     |   1 |     |     |     |  53 |     |     |
|  20 | 106 |     |     |     |     |     |   2 |  17 |     |   1 |   2 |     |
|  21 | 113 |  12 |     |     |     |  22 |   1 |  81 | 137 |  27 |   1 | 110 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+

please notice that all 0's have been removed and that the TAT column is sequential 0,1,2,3,4,......
how do i force these two conditions?
i need this for values of TAT between 0 and 191.
for values 192 and greater, i would like the TAT at 192 to be a sum of all values of 192 and greater

A: EDIT for new info
;WITH d AS ( SELECT TAT = CASE WHEN TAT > 191 THEN 192 ELSE TAT END,
   SUM(CASE WHEN [Month Entered] = 1  THEN 1 ELSE 0 END) AS JAN,
   SUM(CASE WHEN [Month Entered] = 2  THEN 1 ELSE 0 END) AS FEB,
   SUM(CASE WHEN [Month Entered] = 3  THEN 1 ELSE 0 END) AS MAR,
   SUM(CASE WHEN [Month Entered] = 4  THEN 1 ELSE 0 END) AS APR,
   SUM(CASE WHEN [Month Entered] = 5  THEN 1 ELSE 0 END) AS MAY,
   SUM(CASE WHEN [Month Entered] = 6  THEN 1 ELSE 0 END) AS JUN,
   SUM(CASE WHEN [Month Entered] = 7  THEN 1 ELSE 0 END) AS JUL,
   SUM(CASE WHEN [Month Entered] = 8  THEN 1 ELSE 0 END) AS AUG,
   SUM(CASE WHEN [Month Entered] = 9  THEN 1 ELSE 0 END) AS SEP,
   SUM(CASE WHEN [Month Entered] = 10 THEN 1 ELSE 0 END) AS OCT,
   SUM(CASE WHEN [Month Entered] = 11 THEN 1 ELSE 0 END) AS NOV,
   SUM(CASE WHEN [Month Entered] = 12 THEN 1 ELSE 0 END) AS DEC
  FROM [SalesDWH].[dbo].[TurnAround]
  WHERE [datetime entered] >= '20100101'
    AND [datetime entered] <  '20110101'
  GROUP BY CASE WHEN TAT > 191 THEN 192 ELSE TAT END
),
n AS ( SELECT TOP (193) n = ROW_NUMBER() OVER (ORDER BY [object_id]) - 1
  FROM sys.all_columns ORDER BY [object_id]
)
SELECT TAT = n.n,
  JAN = COALESCE(RTRIM(NULLIF(JAN, 0)), ''),
  FEB = COALESCE(RTRIM(NULLIF(FEB, 0)), ''),
  MAR = COALESCE(RTRIM(NULLIF(MAR, 0)), ''),
  APR = COALESCE(RTRIM(NULLIF(APR, 0)), ''),
  MAY = COALESCE(RTRIM(NULLIF(MAY, 0)), ''),
  JUN = COALESCE(RTRIM(NULLIF(JUN, 0)), ''),
  JUL = COALESCE(RTRIM(NULLIF(JUL, 0)), ''),
  AUG = COALESCE(RTRIM(NULLIF(AUG, 0)), ''),
  SEP = COALESCE(RTRIM(NULLIF(SEP, 0)), ''),
  OCT = COALESCE(RTRIM(NULLIF(OCT, 0)), ''),
  NOV = COALESCE(RTRIM(NULLIF(NOV, 0)), ''),
  DEC = COALESCE(RTRIM(NULLIF(DEC, 0)), '')
FROM n LEFT OUTER JOIN d ON n.n = d.TAT
ORDER BY n.n; -- do not use ordinal numbers for ORDER BY!

A: first, you need create a table with all values for your first column and join data table with it
then you do another query on top of this one ( so this one is subquery) and each month column will be
 case jan when 0 then '' else cast(jan as nvarchar) end jan


text:
Q: feature extraction for machine learning Looking for some advice. I am playing around with an accelerometer, combined with the machine learning app in matlab. Clearly there are many ways to extract features from the received data, both in time and frequency domains. However, I have recently come across time-frequency analysis, specifically using wavelets.
Has anyone got any advice on using wavelet analysis for classifying accelerometer (or similar) data and the benefits of using it ? Or if indeed this would be a valid way of extracting features ? I'm not too sure what sort of data I should be extracting using this method ?
Thanks in advance.

A: Few points to note,
1)You can transform a number of samples (should be a dyadic number and depends on your sampling frequency) into wavelet domain and classify that data. (eg. if you transform 64 accelerometer samples then you also have 64 points in wavelet domain).
2) Apart from time-frequency information from wavelet transformation, wavelet transformation has sparsity property
(https://en.wikipedia.org/wiki/Sparse_approximation) that would be useful for your classification model.
3) Also, you can try different wavelet basis functions (mother wavelets),
and try to figure out which basis is most suitable for your data. Maybe you can start with Haar basis function as it is more suitable to capture the singular behaviour of your data.


text:
Q: Having trouble with match wildcards in array I've a master text file and exceptions file and I want to match all the words in exception file with master file and increase counter, but the trick is with wildcards.
I'm able to do without wildcards with this:
words = %w(aaa aab acc ccc AAA)
stop = %q(/aa./)

words.each do |x|
    if x.match(/aa./)
     puts "yes for #{x}"
    else
     puts "no for #{x}"
    end
end

=>
yes for aaa
yes for aab
no for acc
no for ccc
yes for AAA

Also which would be the best way to go about this, using arrays or some other way.
Edit: Sorry for the confusion. Yes stop has multiple wildcards and I want to match all words based on those wildcards.
words = %w(aaa aab acc ccc AAA)
stop = %q(aa* ac* ab*)

Thanks

A: The description of your requirements is really vague.  But either the partition or select methods will work for you:
words = %w(aaa aab acc ccc AAA)
re = %r(aa.)i
p words.partition {|word| word.match(re)}  # => [["aaa", "aab", "AAA"], ["acc", "ccc"]]
p words.select {|word| word.match(re)}     # => ["aaa", "aab", "AAA"]

UPDATE
Based on your last comment:
stops= %q(aa* ac* ab*)
stops.split.collect do |wildcard|
  re = Regexp.new(wildcard, Regexp::IGNORECASE)
  words.select {|word| word.match(re)}
end
# => [["aaa", "aab", "acc", "AAA"], ["aaa", "aab", "acc", "AAA"], ["aaa", "aab", "acc", "AAA"]]

If those results surprise you, you may want to learn more about regular expressions, which are much different and more powerful than glob-style patterns. Ruby doesn't do glob matching on strings.


text:
Q: SQL For Standardizing Postal Codes I have a table in SQL Server that has a PostalCode column.  The data in here is not standardized - Sometimes the postal code appears is H0H 0H0 and othertimes it is H0H0H0.  Using SQL only, how can I ensure each of these postal codes is standardized as H0H 0H0 ?

A: Well, for starters, it really depends on how it's entered into the database (i.e. you should be controlling how this is entered and managed pre-insertion). But for updating your table, you could do this to put them in the right format, with the space in between:
Update MyTable Set PostalCode=SubStr(LTrim(PostalCode),0,3) || ' ' || SubStr(RTrim(PostalCode),-3,3);

This might vary depending on the actual database engine. At the time of writing, OP had not specified which.

A: If you can be sure that those are the only two formats:
select left(replace(post_code,' ',''),3) + right(replace(post_code,' ',''),3)

If the case can vary wrap the result in UPPER()


text:
Q: How do I inflate an Android options menu and set an item to Enabled=false? My XML menu definition sets the item R.id.menu_refresh's enabled state to false. When the app runs the menu item is greyed and disabled. Why is this code in the app not enabling the item?
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    MenuItem refresh = menu.getItem(R.id.menu_refresh);
    refresh.setEnabled(true);
    return true;
}

What am I missing?

A: Try menu.findItem() instead of getItem(). getItem() takes an index from [0, size) while findItem() takes an id.

A: this is what I do in my activity for the menu handling ...
//Android Activity Lifecycle Method
// This is only called once, the first time the options menu is displayed.
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);
    return true;
}

//Android Activity Lifecycle Method
// Called when a panel's menu is opened by the user.
@Override
public boolean onMenuOpened(int featureId, Menu menu)
{
    MenuItem mnuLogOut = menu.findItem(R.id.main_menu_log_out_id);
    MenuItem mnuLogIn = menu.findItem(R.id.main_menu_log_in_id);
    MenuItem mnuOptions = menu.findItem(R.id.main_menu_options_id);
    MenuItem mnuProfile = menu.findItem(R.id.main_menu_profile_id);

    //set the menu options depending on login status
    if (mBoolLoggedIn == true)
    {
        //show the log out option
        mnuLogOut.setVisible(true);
        mnuLogIn.setVisible(false);

        //show the options selection
        mnuOptions.setVisible(true);

        //show the edit profile selection
        mnuProfile.setVisible(true);
    }
    else
    {
        //show the log in option
        mnuLogOut.setVisible(false);
        mnuLogIn.setVisible(true);

        //hide the options selection
        mnuOptions.setVisible(false);

        //hide the edit profile selection
        mnuProfile.setVisible(false);
    }

    return true;
}

//Android Activity Lifecycle Method
// called whenever an item in your options menu is selected
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle item selection
    switch (item.getItemId())
    {

    case R.id.main_menu_log_in_id:
    {
        ShowLoginUI();
        return true;
    }

    case R.id.main_menu_log_out_id:
    {
        ShowGoodbyeUI();
        return true;
    }

    case R.id.main_menu_options_id:
    {
        ShowOptionsUI();
        return true;
    }

    case R.id.main_menu_profile_id:
    {
        ShowProfileUI();
        return true;
    }

    default:
        return super.onOptionsItemSelected(item);
    }
}

I like this approach because it makes the code nice and modular

A: Use menu.findItem() instead of getItem().
because findItem is used to find item by id.