text:
Q: synonyms for "conceive of" I am not a native speaker of English and It's become very confusing to understand the meaning of "conceive of" . To conceive means to conceptualize; but why we mostly use preposition of with conceive?
Consider this sentence :

I conceived of a machine that would help the mechanical engineers.

replacing it with conceptualize it becomes :

I conceptualized a machine that would help the mechanical engineers.

It looks perfectly accurate without the preposition for. Can somebody please explain its exact meaning?

A: You can use "conceive" as a transitive verb with a direct object, or as an intransitive verb, with "of".
American Heritage Dictionary "conceive"
transitive

*To form or develop in the mind: conceive a plan to increase profits; conceive a passion for a new acquaintance.

*To apprehend mentally; understand: couldn't conceive the meaning of that sentence.
intransitive

*

*To form or hold an idea: Ancient peoples conceived of the earth as flat.

To me, "conceive" sounds more concrete. "Conceive of" sounds more vague. I don't think there's much difference.


text:
Q: Alternative proof for not attained norm Consider a mapping
$$T_\lambda: \ell^1 \rightarrow \ell^1\quad T_\lambda f:=\{\lambda_1 f_1,\,\lambda_2 f_2,\lambda_3 f_3,\,\cdots\},$$
where $\lambda_n = 1 - \frac{1}{n}$, $\lambda \in \ell^\infty$.
The operator norm is not attained, which can be shown by Hölder inequality.
But I am looking for an alternative proof that is more elementary and avoids from using 'advanced' theories such as Hölder inequality.
Any suggestions?
Thanks.

A: $$
\|T_\lambda f\|_1=\sum_n|\lambda_nf_n|=\sum_n\left(1-\frac1n\right)\,|f_n|.
$$
It is easy to see that $\|T_\lambda\|=1$.
If $\|T_\lambda f\|_1=\|f\|_1$ for some nonzero $f\in\ell^1$, then
$$
\sum_n\left(1-\frac1n\right)\,|f_n|=\sum_j|f_n|.
$$
As both series converge (absolutely, being of positive terms), we get
$$
\sum_n\frac1n\,|f_n|=0.
$$
But since $f\ne0$, $\sum_n\frac1n|f_n|>0$, a contradiction.

redpajama_set_name: RedPajamaStackExchange


text:
Q: macOS, exfat 3.5 hdd recognizes in one external enclosure, says not recognized and to initialize in other (no thanks), what could be the cause? I have a single bay enclosure that I initialized an 8tb drive in as exfat in, then I got a 5 bay enclosure, when I stick it in the 5 bay it's not recognized and says to initialize.
I put it back in the single bay and it works perfectly fine, same computer, same OS
I misplaced the oem usb type b cable that came with the 5 bay, but I have many others, and the proper ac, and other drives connect and are recognized with various cables.
Another possibility is that maybe it doesn't like mix and match drive formats, as I have some ntfs and that one is exfat (I'm going to convert them all to ntfs eventually).
Any ideas? It's not a huge issue but would prefer to be able to ditch the single bay.


text:
Q: Scala. How to take the count of array of first array using scala I have a file with words separated by * and lines separated by ~, I would like to count the specific word how many times it is appeared in the file.
For eg.
Input File:
AB*xyz*1234~
CD*mny*769~
MN*bvd*2345~
AB*zar*987~

Code:
for (line <- bufferedSource.getLines()) {
      array = line.split("\\~")

for (row <- array ){
      val splittedRow=row.split("\\*")
      val cnt = splittedRow(0).contains("AB").count()

Here i am facing the issue in, how many times the word AB is present. Can you please help me how to get the count of specific words from an array. I am not able to use the keyword .count.
Kindly help me.

A: I made a small function for your case:
def count(term:String,file:File): Int = {
    Source.fromFile(file, "UTF-8").getLines().foldRight(0)((line, count) => {
        count + line.split("\\*").filter(_.contentEquals(term)).length
    })
}

println(count("AB",PATH_TO_INPUT)) // result is 2

all lines will check if there is your delimitter, filter the list of words  to the term and add the length of remaining words to the current count value.
this helps me to understand fold methods
I hope that answer your question

A: arr.map(_.split("\\*")).count(i => i.headOption.exists(_.contains("AB")))

count by contains function with first element and use Option to handle None.

A:
the issue in, how many times the word AB is present. Can you please help me how to get the count of specific words from an array

You can read the file using Source api and then store the separated words in a list.
val resultArray = Source.fromFile(filename).getLines().flatMap(line => line.replace("~", "").split("\\*")).toList

You can count the number of repeatition of each words by call count function as
println(resultArray.count(_ == "AB"))   //will print 2
println(resultArray.count(_ == "CD"))   //will print 1
println(resultArray.count(_ == "xyz"))  //will print 1

I hope the answer is helpful


text:
Q: OS Command Injection from Process.Start My application is using Process.Start for opening another application to run. VeraCode [a security software scanning tool] reported this command as OS Command Injection Vulnerable. I would like to get some comment. I have found a lot of information on the web regarding to filter the input or to constraint the program name; however, I am curious to see if there's any other alternatives of using Process.Start?
Edit:
Thanks for the comment, here is one of the sample, and yes, it is getting input from users:
public static void Run(string fileName, string arguments, bool waitForExit)
{
    Process p = Process.Start(fileName, arguments);

    if (waitForExit)
        p.WaitForExit();
}

Thanks!

A: This is a command injection vulnerability because you have not filtered out the users input from the function and directly appended to the process.start()
Due to this, the tool has marked it as a vulnerability.
To avoid this issue you should use regex method to filter out the bad characters and depending on what that function is going to do when it gets run.
for eg. you function is created only to check from this path c:/users/docs.txt
then that function should not get executed for c:/admin/docs.txt.
This is how you need to validate before sending the user data directly into the process.
For more information refer this awesome link : https://dotnet-security-guard.github.io/SG0001.htm
or
https://www.veracode.com/security/dotnet/cwe-78

A: The Process class is nothing else then a Managed wrapper class the the Native Create Process and its Variations like Create Process As User .

*

*Process MSDN

*Process
SourceCode
I don't think that there is another way to start a process than this, because every other solution would also call the WinAPI function. ( because this function (or its overloads and Variations) is  the only way to start a process in Windows).
Personally, I have not heard anything about a problem with Process.Start please clarify the problem
regards

A: I ran into this as well. You need to set the UseShellExecute property to false. Then Veracode will not consider it a vulnerability.
using (WinProcess myProcess = new WinProcess())
{
    myProcess.StartInfo.FileName = "notepad.exe";
    myProcess.StartInfo.Arguments = Path.GetFileName(fullPath);
    myProcess.StartInfo.UseShellExecute = false;
    myProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(fullPath);
    myProcess.StartInfo.RedirectStandardOutput = false;
    myProcess.Start();
}


text:
Q: Can I increase the amount of Dedicated Memory for my NVIDIA graphics card? I have an old laptop that has an NVIDIA GeForce 9600M GT,
it's got 2046mb of Total Available Graphics Memory, and 512mb of Dedicated Video Memory(VRAM).
It's running on Windows 10 64-bit.
I was wondering if it was possible to increase the amount of VRAM for that graphics card.
Here's a screenshot

A: No.
Dedicated memory is the amount of memory in dedicated memory chips soldered somewhere on GPU's circuit board. There's exactly 512 MB of memory soldered there, no more, no less.


text:
Q: Event Delegation: can someone explain me this JavaScript code? I'm studying the event delegation on a book and I'm not sure I understood very well the concept. I know that it is used to "attach" an event to a parent element instead of attaching it to all the children. But I think I would not be able to use it on my own without a good explanation.

function getTarget(e) {
  if(!e) {
    e = window.event;
  }
  return e.target || e.srcEvent;
}

function itemDone(e) {
  var item, elParent, elGrandparent;
  item = getTarget(e);
  elParent = item.parentNode;
  elGrandparent = item.parentNode.parentNode;
  elGrandparent.removeChild(elParent);

  if (e.preventDefault) {
    e.preventDefault();
  } else {
    e.returnValue = false;
  }
}

var el = document.getElementById("shoppingList");
if (el.addEventListener) {
  el.addEventListener("click", function(e) {
    itemDone(e);
  }, false);
} else {
  el.attachEvent("onclick", function(e) {
    itemDone(e);
  });
}

fresh figs

pine nuts

honey

balsamic vine

A: If you attach an event to a parent element, and click a child element, if the child element has a click event attached to it that will fire, javaScript will also go down a chain of sorts and fire events attached to parent elements unless you prevent that from happening.
html

child 1

child 2

child 3

javascript
document.getElementById('parent').addEventListener('click', function(e){

    console.log(e.target.innerHTML);

});

jsfiddle
In my example the innerHTML of the child element that is click is logged to the console.


text:
Q: Time/Space-Complexity method I got a question to answer with the best complexity we can think about.
We got one sorted array (int) and X value. All we need to do is to find how many places in the array equals the X value.
This is my solution to this situation, as i don't know much about complexity.
All i know is that better methods are without for loops :X
class Question
{
    public static int mount (int [] a, int x)
    {
        int first=0, last=a.length-1, count=0, pointer=0;
        boolean found=false, finish=false;
        if (x < a[0] || x > a[a.length-1])
                return 0;
        while (! found) **//Searching any place in the array that equals to x value;**
        {
            if ( a[(first+last)/2] > x)
                last = (first+last)/2;
            else if ( a[(first+last)/2] < x)
                first = (first+last)/2;
            else
            {
                pointer = (first+last)/2;
                count = 1;
                found = true; break;
            }
            if (Math.abs(last-first) == 1)
            {
                if (a[first] == x)
                {
                    pointer = first;
                    count = 1;
                    found = true;
                }
                else if (a[last] == x)
                {
                    pointer = last;
                    count = 1;
                    found = true;
                }
                else
                    return 0;
            }
            if (first == last)
            {
                if (a[first] == x)
                {
                    pointer = first;
                    count = 1;
                    found = true;
                }
                else
                    return 0;
            }
        }
        int backPointer=pointer, forwardPointer=pointer;
        boolean stop1=false, stop2= false;
        while (!finish) **//Counting the number of places the X value is near our pointer.**
        {
            if (backPointer-1 >= 0)
                if (a[backPointer-1] == x)
                {
                    count++;
                    backPointer--;
                }
                else
                    stop1 = true;
            if (forwardPointer+1 <= a.length-1)
                if (a[forwardPointer+1] == x)
                {
                    count++;
                    forwardPointer++;
                }
                else
                    stop2 = true;
            if (stop1 && stop2)
                finish=true;
        }
        return count;
    }
    public static void main (String [] args)
    {
        int [] a = {-25,0,5,11,11,99};
        System.out.println(mount(a, 11));
    }
}

The print command count it right and prints "2".
I just want to know if anyone can think about better complexity for this method.
Moreover, how can i know what is the time/space-complexity of the method?
All i know about time/space-complexity is that for loop is O(n). I don't know how to calculate my method complexity.
Thank a lot!
Editing:
This is the second while loop after changing:
        while (!stop1 || !stop2) //Counting the number of places the X value is near our pointer.
    {
        if (!stop1)
        {
            if ( a[last] == x )
            {
                stop1 = true;
                count += (last-pointer);
            }
            else if ( a[(last+forwardPointer)/2] == x )
            {
                if (last-forwardPointer == 1)
                {
                    stop1 = true;
                    count += (forwardPointer-pointer);
                }
                else
                    forwardPointer = (last + forwardPointer) / 2;
            }
            else
                last = ((last + forwardPointer) / 2) - 1;
        }
        if (!stop2)
        {
            if (a[first] == x)
            {
                stop2 = true;
                count += (pointer - first);
            }
            else if ( a[(first+backPointer)/2] == x )
            {
                if (backPointer - first == 1)
                {
                    stop2 = true;
                    count += (pointer-backPointer);
                }
                else
                    backPointer = (first + backPointer) / 2;
            }
            else
                first = ((first + backPointer) / 2) + 1;
        }
    }

What do you think about the changing? I think it would change the time complexity to O(long(n)).

A: First let's examine your code:
The code could be heavily refactored and cleaned (which would also result in more efficient implementation, yet without improving time or space complexity), but the algorithm itself is pretty good.
What it does is use standard binary search to find an item with the required value, then scans to the back and to the front to find all other occurrences of the value.
In terms of time complexity, the algorithm is O(N). The worst case is when the entire array is the same value and you end up iterating all of it in the 2nd phase (the binary search will only take 1 iteration). Space complexity is O(1). The memory usage (space) is unaffected by growth in input size.
You could improve the worst case time complexity if you keep using binary search on the 2 sub-arrays (back & front) and increase the "match range" logarithmically this way. The time complexity will become O(log(N)). Space complexity will remain O(1) for the same reason as before.
However, the average complexity for a real-world scenario (where the array contains various values) would be very close and might even lean towards your own version.


text:
Q: RTRIM inside LISTAGG? Good day. I am writing a query that uses LISTAGG and returns results. This is the code I have so far.
   select
    listagg(rtrim(shop_cde, 1), ', ') within group (order by shop_cde) col1,
    business_cde
    from mytable
    group by business_cde

I expect that this returns results, aggregates them, and trims off 1 character from the right on shop_cde. However, it appears no trimming occurs. Shop_cde still shows in full. Does anyone know how to TRIM inside a LISTAGG function?

A: The trim() functions are generally used to remove leading and trailing spaces (although you can remove other characters as well).
If you want to discard the last character, use substr():
select listagg(substr(shop_cde, 1, length(shop_cde) - 1), ', ') within group (order by shop_cde) col1,
       business_cde
from mytable
group by business_cde

A: Use substr if you want to remove a given number of charcaters from the right, use rtrim if you want an unspecified number of a given character eliminated. Removing on the left would use substr(..., 2) and ltrim, resp.
   select
    listagg(substr(shop_cde, -1), ', ') within group (order by shop_cde) col1,
    business_cde
    from mytable
    group by business_cde

A: you should use rtrim(listagg(....) )
select
rtrim(listagg(shop_cde, ', ') within group (order by shop_cde) ) col1,
business_cde
from mytable
group by business_cde


text:
Q: Import Error: No module named snappy I am trying the software SNAP in Python. I have installed SNAP and the module Snappy. But when I try to import snappy through python GUI I am getting this error:

Import Error: No module named snappy

My python version is 2.7.10. I have checked the bit compatibility of SNAP and Python it's ok.
snap installed in cmd, here's the Python GUI error:

How can I solve it?

A: The path that you append should not have the last component ('\snappy'). A path is the name of the folder where Python will search for your modules, not the name of the module folder. This solved it @DYZ

A: I tried doing both the changes. I removed the last component and got the following error.error 1
I changed the name of the folder containing snap and still got an errorerror2


text:
Q: IntelliJ IDEA: Auto code update on tomcat7:run On eclipse, when you execute a Maven RUN with: tomcat7:run on your project, if you change some classes, you don't need to re-run your application in order to check the changes. I think is "hot-code swap" or something like that.
Is it possible to do that on IntelliJ?

A: yeah you have 4 options:
First press Ctrl + F10
you will see:

*

*Update Classes

*Update Resources and Clases

*Redeploy

*Restart Server

The second is the answer. More info here:
http://www.jetbrains.com/idea/webhelp/updating-applications-running-on-application-servers.html
EDIT 2018: IntelliJ IDEA 2017.3.3

A: Here's what I found to work with the Maven tomcat7:run plugin in IntelliJ IDEA 2017.3 using a Run/Debug Configuration.
After you create the Run/Debug Configuration and configure Java Hot Swap in your IntelliJ Settings, you MUST run this configuration in DEBUG mode.
While the Tomcat server is running, you can make code changes and recompile them with ctrl+shift+F9 and IntelliJ IDEA will pop-up a message telling you that "some classes have changed" and asking "would you like to deploy the updates/changes?" (due to Settings > Ask).  Answer Yes and IntelliJ will display a status telling you if it succeeded, in which case you can send your POST/GET request again to test your changes, OR, if it failed to deploy the changes, in which case you'll need to Stop Tomcat and Start it again.
Success or failure to deploy your changes depends on whether or not your changes are allowed by Java's Hot Swap feature.  Refer to your JDK docs.
Here are the images for my IntelliJ IDEA Settings and my Run/Debug Configuration:
Java Hot Swap Settings
Run/Debug Configuration
NOTE: You can add options to the Before Launch section to do additional steps you might need such as copying additional "resource" files to your "target/classes" folder.  For example, you can call a script, with an External Tool option, that you've written to copy additional "resource" files to your "target/classes" folder.  IntelliJ's docs explain how to use the Before Launch feature.


text:
Q: error: can't find crate I'm trying to use this library.
But, cargo build says this:
   Compiling test v0.1.0 (file:///C:/path/to/project/test)
src\main.rs:1:1: 1:28 error: can't find crate for `jvm_assembler` [E0463]
src\main.rs:1 extern crate jvm_assembler;
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `test`.

To learn more, run the command again with --verbose.

My Cargo.toml is this:
[package]
name = "test"
version = "0.1.0"
authors = ["yomizu_rai"]

[dependencies]
jvm-assembler = "*"

src/main.rs is this, and there are no other sourcefiles.
extern crate jvm_assembler;
use jvm_assembler::*;
fn main() {}

I think my Cargo.toml is not wrong, and src/main.rs has no room for mistake.
Why can not rustc find jvm-assembler?
How do I resolve?

A: Cargo can only find crates by name if they are on crates.io. In your case you need to specify the git URL, see the section on dependencies in the Cargo documentation.


text:
Q: mac find -name *.png does not work I am trying to recursively search for a filename ending in .png
My find command works fine for *.js, but not for *.png.
~ >find dev -name *.png
~ >find dev -name bluerightarrow.png
dev/sandbox/ScheduleEditorTS/ScheduleEditorTS/img/bluerightarrow.png
~ >find dev -name *.js
dev/backup/ScheduleEditorTS/packages/jQuery.2.1.3/Content/Scripts/jquery-2.1.3-vsdoc.js
dev/backup/ScheduleEditorTS/packages/jQuery.2.1.3/Content/Scripts/jquery-2.1.3.js
... etc

A: You probably have a .png file in your current directory and the * is expanded by your shell.
Here's a practical explanation. Create a directory called test, then another one called sub inside it and finally a file called myfile.txt in sub. Then cd into test. Here are commands to do that:
~ >mkdir -p test/sub
~ >touch test/sub/myfile.txt
~ >cd test

You can run find and you'll get expected results:
~/test >find sub -name *.txt
sub/myfile.txt

Now create a file called cause.txt in test and run find again:
~/test >touch cause.txt
~/test >find sub -name *.txt

This time nothing is found because shell expands the * and your find command becomes:
~/test >find sub -name cause.txt

There's no cause.txt file in sub, so there are no results.
To avoid this problem you have to escape the asterisk with a backslash:
~/test >find sub -name \*.txt
sub/myfile.txt


text:
Q: Docker build dockerfile I am trying to build a docker image from  dockerfile which I have written.
docker build -f ~/www/node-beta.dockerfile

This however results in the error:
docker: "build" requires 1 argument. See 'docker build --help'.

A: sudo docker build -t yee/haw -f ~/www/node-beta.dockerfile ~/www/

A: The docker build command always requires a location argument. In this case you should use ~/www/ as the for the location argument, and the file name, "node-beta.dockerfile" for the -f (filename) argument.
docker build -f node-beta.dockerfile ~/www


text:
Q: Unread email notifier, most practical approach I'm in the process of writing a small php-cli script that will loop over my  personal inbox and then send me an SMS via a gateway.
The question I have is:
As will have the script launch via cron every 10 minutes, if there is an email sitting in my inbox that is not read before the next script launch then I will receive 2 sms.
Does any one (pseudocode will do) have any idea what the best practice would be in php5 to ensure only 1 SMS is sent?
What I am currently learning towards is storing the message ID in a sqlite DB and flagging a field whether an SMS has been sent or not - but wondering if there is an easier way?

A: You shouldn't need to store anything.  If I understand you correctly, you simply want your program to send you a message if a new, unread email has arrived within the last 10 minutes.  In that case, could you not do the following?
foreach($inbox[] as $message){
    if(($message.isUnread) && ($message.receiveTime > NOW() - 10 minutes)){
        $sendMessage = TRUE;
    }
}

if($sendMessage){
    sendMessage();
}

I don't know how you're able to access the data, so the above is unlikely to be usable as-is.  Assuming you can filter your inbox's contents by read status and date arrived, however, shouldn't that work in principle?

A:
What I am currently learning towards is storing the message ID in a sqlite DB and flagging a field whether an SMS has been sent or not

This is one of the most simple and straightforward ways to do this.  Regardless of storage method, you'll have to keep the list of seen-but-unread message IDs somewhere.  May as well be in a simple, self-contained SQLite file.  I suppose you could just keep them in a list in a flat file.  That is by definition more simple, but is it really easier?

A: I don't see you getting away without persisting something somewhere.
That something should be of ever-incrementing nature - message ID maybe, timestamp for sure. As long as you can look at it and determine if new messages have arrived since.
If all you wish to communicate with the SMS is that there are unread messages, I don't see the need to persist more then a single ID or a timestamp.

A: After a few hours sleep (up since 4am watching Australia vs Germany, World Cup) I've come up with an even better method, a bit more complex then just using a sqlite DB but has some extra benefits.
I'm using imap_mail to send the SMS to the gateway, and storing the message_id that the SMS is notifying to as a custom "X-Relationship:" header in the outgoing email and then copying the message to my Sent Items.
Then the notifier simply scans my Sent Items for the presence of the X-Relationship header within my Sent Items.
This what I have a record (Sent Item) of the email sent to the SMS Gateway - seems to be working well.


text:
Q: Unity 2020 project building asm.js files instead of wasm I upgraded a project from unity 2018 to unity 2020. the webGL build for unity 2020 should default to wasm (Web assembly) but instead it is building the project with asm.js. I can't figure out how to fix this.

A: All I needed to do was edit ProjectSettings/projectsettings.asset and set   webGLLinkerTarget: 1

A: You find it in your explorer: Go to your project location, there should be a folder named "ProjectSettings", in there you find the "ProjectSettings.asset".  In the file you can now edit parameters by simply writing and saving.


text:
Q: How to efficiently select certain items from two lists using LINQ I have these 3 classes:

*

*Employee

*Student

*Person

Code:
public class Employee
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
    public long TimeStamp { get; set; }
}

public class Student
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public long TimeStamp { get; set; }
}

public class Person<br>
{
    public string Name { get; set; }
    public int Age { get; set; }
}

I create 4 Lists :
var studentList = new List<Student>();// fill the List with a lot of Stundents
var employeeList = new List<Student>(); // fill the List with a lot of employees
var personList1 = new List<Person>();
var personList2 = new List<Person>();

Select all students and employees
var allStudents = studentList.Select(a => a); // does not make a lot of sence but for testing
var allEmployee = employeeList.Select(b => b);

I want to map allStudents to
personList1.AddRange(allStudents.Select(a => new Person()
            {
               Age = a.Age,
               Name = a.Name
            } ));

I want to get all Employees where the value of TimeStape is not mentioned in the allStundent List
var allEmployeesWithDifferentTimeStampThanStundent =
    allEmployee.Where(a => !allStudents.Select(b =>b.TimeStamp).Contains(a.TimeStamp));

mapping again
personList2.AddRange(allEmployeesWithDifferentTimeStampThanStundent.Select
(a => new Person()
    {
    Age = a.Age,
    Name = a.Name
    } ));

merge both lists
personList1.AddRange(personList2);

Is there a better and more efficient way to do this?

A: The personList2 variable appears only to be there as an intermediate for projecting to the Person type -- if that's the case, you could skip its creation and use query syntax like so:
var personsFromNonMatchingEmployees =
    from employee in allEmployee
    join student in allStudents
    on employee.TimeStamp equals student.TimeStamp into studentsWithMatchingTimeStamp
    where !studentsWithMatchingTimeStamp.Any()
    select new Person { Age = employee.Age, Name = employee.Name };

personList1.AddRange(personsFromNonMatchingEmployees);

This is similar to the other GroupJoin approach since the compiler translates the above into a GroupJoin call. The use of join/group-join necessarily performs better than the Where..Contains approach since it makes use of hashing - in other words, it's an algorithmic Big-O improvement that should be quite noticeable for any more than a few Student or Employee instances.
By selecting the new Person object in the query, I'm able to bypass the personList2 list altogether. I find that I'm almost always able to eliminate temporary lists by doing selects like this that project to the type that I'm really interested in. I also left out the () on the new Person { .. } since the compiler doesn't require it.
Shy of changing up the inheritance and making Employee : Person & Student : Person, I don't think there's much more to improve.

A: You can use GroupJoin to find all employees without a matching Student record with the same timestamp:
var employeesDiffTS = allEmployee
    .GroupJoin(allStudents, e => e.TimeStamp, s => s.TimeStamp, (e, students) => new { Emp = e, HasMatch = students.Any() })
    .Where(em => !em.HasMatch)
    .Select(em => em.Emp)

personList2.AddRange(employeeDiffTS.Select(a => new Person { Age = a.Age, Name = a.Name }));

personList1.AddRange(personList2);


text:
Q: Prove $\frac{1}{\sqrt{b+\frac{1}{a}+\frac{1}{2}}} + \frac{1}{\sqrt{c+\frac{1}{b}+\frac{1}{2}}} $ For postive integer $a, b, c $ prove the following inequality  $$\frac{1}{\sqrt{b+\frac{1}{a}+\frac{1}{2}}} + \frac{1}{\sqrt{c+\frac{1}{b}+\frac{1}{2}}} + \frac{1}{\sqrt{a+\frac{1}{c}+\frac{1}{2}}} > \sqrt{2}$$
How we can prove this inequality?

A: $$\frac{1}{\sqrt{b+\frac{1}{a}+\frac{1}{2}}} + \frac{1}{\sqrt{c+\frac{1}{b}+\frac{1}{2}}} + \frac{1}{\sqrt{a+\frac{1}{c}+\frac{1}{2}}} > \sqrt{2}$$
By$ AM-GM$ $$\sum_{cyc}\frac{1}{\sqrt{b+\frac{1}{a}+\frac{1}{2}}}=\sum_{cyc}\frac{\sqrt2}{2\cdot\frac{1}{\sqrt2}\sqrt{b+\frac{1}{a}+\frac{1}{2}}}\geq\sum_{cyc}\frac{\sqrt2}{b+\frac{1}{a}+1}=\sqrt2$$


text:
Q: Civilization 5 view - show resources on map I see a view on the web where in Civilization 5 you can see the resources on the map by default.  How do I enable that?  For example, in my view, I just see the map and don't see the resources at all.
Here is a site with that view.
http://www.nohighscores.com/2011/08/30/civilization-5-game-diary-ode-to-oda-nobunaga-part-5-turns-401-466/


text:
Q: SQL Query with ON DUPLICATE KEY UPDATE does not work I have a table with profiles. If there is a profile for user #:userId, I want to UPDATE it. If there is no profile for that user, I want to INSERT it. I tried this SQL query, but it did not work:

    INSERT INTO profiles
    SET name = :name,
        website = :website,
        bio = :bio
    WHERE user = :userId
    ON DUPLICATE KEY UPDATE
        name = :name,
        website = :website,
        bio = :bio

'user' is primary key
EDIT: I found a mistake in my SQL, when it looks like this, it works just fine:

    INSERT INTO profiles
    SET user = :userId,  -- <-- mistake was here
        name = :name,
        website = :website,
        bio = :bio
    ON DUPLICATE KEY UPDATE
        name = :name,
        website = :website,
        bio = :bio

Thanks, everyone!

A: Your INSERT syntax is incorrect (it looks like a modified UPDATE statement). Try something like:
INSERT INTO profiles (name, website, bio)
       VALUES (:name, :website, :bio)
  ON DUPLICATE KEY UPDATE website = :website, bio = :bio;

See the documentation for INSERT ... ON DUPLICATE KEY UPDATE for further information and examples.


text:
Q: Use mustache templates with PostgreSQL and JSONb inputs Is time to use JSONb datatype as input in a template, and PostgreSQL queries as template system... Mustache will be perfect, if there are some Mustache implementation for PLpgSQL (or adapted for C)... Seems there are no one.
But there are a good source-code for Javascript-mustache: how to use/adapt it for PLv8?
What the best way (performance) to call mustache many times in a context like  SELECT tplEngine_plv8(input_jsonb,tpl_mustashe) as text_result FROM t ?

NOTES for test and discuss
Test with: http://jsfiddle.net/47x341wu/
CREATE TABLE story (
  id int NOT NULL PRIMARY KEY,
  title text NOT NULL,
  UNIQUE(title)
);
CREATE TABLE story_character (
  id_story int REFERENCES story(id) NOT NULL,
  name text NOT NULL,
  UNIQUE(id_story,name)
);
INSERT INTO story (id,title) VALUES (1,'African jungle story'),
  (2,'Story of India jungle');
INSERT INTO story_character(id_story,name) VALUES
  (1,'Tarzan'), (1,'Jane'), (2,'Mowgli'), (2,'Baloo');

CREATE VIEW t AS
  select id_story, jsonb_build_object('title',title,
      'names', jsonb_agg( jsonb_build_object('name', name) )
   ) AS j
  from story s INNER JOIN story_character c ON s.id=c.id_story
  group by id_story,title;

So with VIEW t we have names and titles for a mustache template,
SELECT tplEngine_plv8(
  j,
  '
* {{title}} with: {{#names}} {{name}}; {{/names}}'
 ) as result
FROM t;

and compare it with the JSFiddle result.

Performance tests
Using EXPLAIN ANALYZE ... Perhaps adding a few hundreds of random values at the testing tables. And, testing also calling strategies: one at a time or by array.
CREATE FUNCTION mustache_engine(
  p_input JSONB,
  p_template TEXT
) RETURNS TEXT language plv8 as $$
   // copy https://rawgit.com/janl/mustache.js/master/mustache.js
   // and somethings more
$$;

or
CREATE FUNCTION mustache_engine(
  p_inputs JSONB[],  -- many inputs
  p_templates TEXT   -- one template
) RETURNS TEXT[]     -- many resuts
language plv8 as $$ ... $$;

CREATE FUNCTION mustache_engine(  -- many input-template pairs
  p_inputs JSONB[],
  p_templates TEXT[]
) RETURNS TEXT[]     -- many resuts
language plv8 as $$ ... $$;

A: create or replace function mustache(template text, view json, partials   json) returns text
language plv8 as
 << copy https://rawgit.com/janl/mustache.js/master/mustache.js >>
 var mustache=this.Mustache;
return mustache.render(template, view, partials)
 $$

;


text:
Q: Getting result from array of Ids in Laravel I've a following attendance table:
id | grade_id | subject_id |    date    |        students
 1 |     2    |      6     | 2020-05-05 | [3,6,8,11,17,21,20,19]

I want to fetch all rows with name of all students from array of Ids.
What I've tried is:
$result[] = Attendance::where('date', '=', $day)
                ->with('grades', 'subjects')
                ->join('students', function($join) {
                      $join->on('students.id', '=', 'attendances.id')
                           ->where('students.id', '=', 'attendances.students');
                      })->get();

But couldn't get result. Please help me!

A: It is not a proper table structure.Will be better if you make another table like
id | attendance_id | student_id
1  | 1             | 3
1  | 1             | 6

And make its relation in model with attendance and student table.This way table will be normalized and will be easy to handle relationship.


text:
Q: Amazon Web Services - EC2: How do I stop my WordPress site showing the ip address as the domain? I am close to tearing my hair out on this issue as I just cannot seem to get my Wordpress site to not read the Amaazon Public IP address.
I have a domain name in GoDaddy and have changed a host record so that my domain name "http://example.com" redirects to "http://0.0.0.0".
However once this page loads, the url quickly changes back to the Public IP address.
I have tried changing the Site URL in the Wordpress Settings but this just breaks the site and does not allow me to log in.
What is it I am doing wrong? I just cant figure it out. I just want the domain name from goDaddy to appear as the URL.
Thanks.

A: First of all attach the Elastic IP to your EC2 Instance so it wont change public IP after you shutdown and restart your machine. Make A Record in your Godaddy DNS Record File that points to the elastic IP.
You have not changed the base URL of your wordpress thats why it is still redirecting to the old Base URL. Connect to your EC2 instance and edit wp-config.php add the following line of code
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');


text:
Q: ¿Cómo utilizar `count` para contabilizar la cantidad de registros para distintos valores de un campo en mysql? Resulta que tengo un campo llamado ESTADO en mi tabla.
En este campo hay varias estados de pedido que son: LOGÍSTICA, PACKING, PICKING, CARTERA, FACTURACIÓN Y FACTURADO.
Quiero saber si hay una forma de utilizar Count para contar cuantas veces se repite cada uno de los valores de mi campo ESTADO. Es decir, cuanto registros tengo en cada uno de los estados que mencioné.
Ayuda, por favor.
Este es el código que tengo hoy día.
$rs= mysqli_query($mysqli,"SELECT id, nombre_vendedor, codigo_vendedor, estado, DATE_FORMAT(fecha_pedido, '%Y-%m-%d'), COUNT(nombre_vendedor) FROM `pedidos` WHERE (estado IN('Logistica','Picking','Facturado','Packing','Cartera') OR ESTADO LIKE 'Facturacion Tarjeta%') AND DATE_FORMAT(fecha_pedido, '%Y-%m-%d') BETWEEN '$fecha_desde' AND '&fecha_hasta' AND codigo_vendedor LIKE '$row1[0]' GROUP BY nombre_vendedor");
        while ($row = mysqli_fetch_row($rs)){

            $row[2] == $row1[0];
            if ($row[3] == 'Logistica') {
                $row[3] = $log;
          substr_count($log);
            }elseif ($row[3] == 'Picking') {
                $row[3] = $pic;
          strlen($pic);
            }elseif ($row[3] == 'Facturado') {
                $row[3] = $fac;
          substr_count($fac);
            }elseif ($row[3] == 'Packing') {
                $row[3] = $pac;
          substr_count($pac);
            }elseif ($row[3] == 'Cartera') {
                $row[3] = $car;
          substr_count($car);
            }elseif(strpos($row[4], 'Facturacion') !== false){
      $row[3] = $fact;
          substr_count($fact);
        }
       }

A: Lo que deseas es contar la cantidad de elementos en cada estado de la base de datos que tienes (asumiendo que la columna se llama 'estado' y la tabla 'pedidos') puedes realizar lo siguiente:
SELECT estado,COUNT(*) as total FROM pedidos GROUP BY estado;

Lo que hará dicha consulta es seleccionar el campo 'estado' y mostrar cuántos hay con aquél mismo nombre (debido a que hacemos un 'GROUP BY estado' al final).
Puedes esperar que tu resultado sea algo así:
estado        total
-----         ------
'Logistica'   100
'Picking'     102
...

Hay un pequeño artículo que da un ejemplo de lo que quieres hacer en la siguiente dirección si es que te ayuda:
http://blog.aulaformativa.com/consultorio-desarrollo-web/


text:
Q: how to populated a combobox in wince I tried to populated a combo box on a DIALOG  with following code:
TCHAR szTmp[64];
for (i = 0; i < 10; i++)
{
  wsprintf(szTmp, TEXT("Item %d"), i);
  SendDlgItemMessage(hwnd, IDC_COMBO,CB_INSERTSTRING, (WPARAM)i, (LPARAM)szTmp);
}
  SendDlgItemMessage(hBaudRate, IDC_COMBO, CB_SETCURSEL, (WPARAM)0, (LPARAM)0);

That did not work. Please let know what I am missing.

A: If both calls to SendDlgItemMessage() are operating on the same ComboBox, then hwnd should be changed to hBaudRate, or vice versa.
Also, the WPARAM of the CB_INSERTSTRING message should be changed to -1, or else use CB_ADDSTRING instead.


text:
Q: std::string constants in a class - inline vs define in cpp file I've come across this stack overflow answer which suggests two ways of handling static string class members: https://stackoverflow.com/a/1563906
Defining in cpp file
// a.h
class A {
private:
  static const string RECTANGLE;
};

// a.cpp
const string A::RECTANGLE = "rectangle";

Inlining
// a.h
class A {
private:
  inline static const string RECTANGLE = "rectangle";
};

I've tried the inline approach and noticed the string is duplicated in every translation unit which imported the header file, and the executable has multiple duplicates.
So, why would anyone prefer the inlining approach if it increases the executable size?
Test setup I've used:
// a.h
#pragma once
class A {
    public:
        void f();
};

// a.cpp
#include <iostream>
#include "a.h"
#include "b.h" // for no reason

void A::f() {
    std::cout << "A" << std::endl;
}

// b.h
#pragma once
#include <string>
class B {
    public:
        void f();
    private:
        inline static const std::string STR = "JOHNWICK";
};

// b.cpp
#include <iostream>
#include "b.h"

void B::f() {
    std::cout << "B" << std::endl;
}

// main.cpp
#include <iostream>
#include "a.h"
#include "b.h"

int main() {
    A a;
    B b;
    a.f();
    b.f();
    return 0;
}

Compile: g++ main.cpp a.cpp b.cpp
strings a.out | grep "JOHNWICK"

prints JOHNWICK <3 times>


text:
Q: How to use pagenumbering in the document? In my Master thesis, I would like to have the title page without any page number and an acknowledgments section and the table of contents with roman numbers. The rest of the document should be numbered arabic.
I have tried this, to have roman numbers for the Table of contents and normal numbers for the rest.
\documentclass[12pt,ngerman,openany]{report}
\usepackage{titlesec}
\usepackage{titletoc}
\usepackage{cite}
\usepackage[a4paper]{geometry}
%\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[ngerman]{babel}
%\usepackage{ngerman}{babel}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{float}
\selectlanguage{ngerman}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{url}
\usepackage{epstopdf}
\usepackage{scrhack}
\usepackage{listings}
\usepackage{caption}
\titleformat{\chapter}{\rmfamily\huge}{\textbf\thechapter.}{25pt}{\huge\textbf}
\defcaptionname{ngerman}{\lstlistingname}{Code}
\defcaptionname{ngerman}{\lstlistlistingname
}{Codeverzeichnis}

\lstloadlanguages{R}
\lstset{% general command to set parameter(s)
  basicstyle=\sffamily\footnotesize, % print whole listing small
  keywordstyle=\sffamily\footnotesize\bfseries, % ubold black keywords
  identifierstyle=, % nothing happens
  commentstyle=\sffamily\footnotesize\slshape, % green comments
  stringstyle=\sffamily\footnotesize, % typewriter type for strings
  showstringspaces=false, % no special string spaces
  numbers=left,
  numberstyle=\sffamily\footnotesize,
  stepnumber=1,
  numbersep=10pt,
  showspaces=false,
  showtabs=false,
  frame=lines,
  morecomment=[l]{\%},
  float=htbp,
  numberbychapter=true
}

\begin{document}
\let\cleardoublepage\clearpage

\pagenumbering{roman}
\tableofcontents
\clearpage
\vspace*{75mm}
\chapter{Einleitung}
\section{Motivation}
bla bla bla
\section{Ziel}

bla bla
\chapter{Stand der Technik zur Mustererkennung}
\section{Die Zeitreihen}
bla bla
\subsection{Beschreibung}
bla bla
\subsection{Erklärung}

bla bla

\subsection{Vorhersage}
bla bla
\subsection{Kontrolle}
bla bla
\section{Feature Extraktion}
bla bla
\subsection{Autokorrelation}
\subsection{Was ist Autokorrelation?}
bla bla

\subsection{Autokorrelation und Zeitreihen}
bla bla

\subsubsection{Zeitreihe-Diagramm}

bla bla
\subsubsection{Lagged Streudiagramm}
bla bla

\subsubsection{Autocorrelation-Function (Korrelogramm)}
bla bla
\subsection{Spektralanalyse}
\subsection{Was ist Spektral-Analyse}
bla bla
\end{document}

A: \pagenumbering{style} changes the appearance of \thepage to match style and
resets the page count to one (\@one). This change in the page
number can be noticed with the shipout of the next page, which is
in fact the page currently typeset.
Now, where to put the \pagenumbering command? A good idea is to
place this immediately after a chapter command.
\documentclass{report}
\usepackage{blindtext}
\usepackage{showframe}
\begin{document}
\chapter{standard counting}
\blindtext[8]
\chapter{roman counting}
\pagenumbering{roman}
\blindtext[5]
\end{document}

All works perfectly fine. But now, what does happen if we take
the same example, but use twoside? Package showframe helps us
determine what left and right pages are. The marginparcolumn is
always on the outer side.
\documentclass[twoside]{report}
\usepackage{blindtext}
\usepackage{showframe}
\begin{document}
\chapter{standard counting}
\blindtext[8]
\chapter{roman counting}
\pagenumbering{roman}
\blindtext[5]
\end{document}

As you may notice, two odd (right) pages follow each other,
making it very hard to bind the final output. The chapter
command issues a clearpage by default (cleardoublepage if
option openright is used) which isn't enough in this case. But
now, we can't issue the needed cleardoublepage after chapter
has been issued. That would make no sense. But we can use
cleardoublepage before chapter. If the pagenumbering
command is issued before or after chapter doesn't make a
difference now.
\documentclass[twoside]{report}
\usepackage{blindtext}
\usepackage{showframe}
\begin{document}
\chapter{standard counting}
\blindtext[8]
\cleardoublepage
\chapter{roman counting}
\pagenumbering{roman}
\blindtext[5]
\end{document}

Is there anything to say about titlepages?
Yep, the standard classes and the KOMA-classes differ in their
behaviour.
\documentclass{report}
%\documentclass{scrreprt}
\usepackage{showframe}
\title{How does pagenumbering work?}
\author{\TeX.SX}
\begin{document}
\maketitle
\chapter*{What pagenumber do we get here?}
pagenumber: \thepage
\end{document}

As we can see by running this example with the standard report,
the titlepage is not counted, the next page has page number 1.
The KOMA-class differs, the titlepage is counted, the next page
gets number 2.
Changing the example to twoside both classes number the pages
in the same way. There is a simple reason for that, odd pages are
always right-hand pages.
Why are all examples using report and its KOMA counterpart?
The behaviour described is defined in the titlepage
environment. article doesn't use a titlepage per default, books
use titlepage, but are printed twoside by default.
The same are working for memoir as well. But it should be
mentioned, that the title of a standard memoir class uses the
pagestyle title which is an alias for plain. So the titlepage
gets (visibally) numbered by default.
What about pagenumbering in articles and books? If you want to change the pagenumbering in an article, you should consider switching to a class with chapters. book provides the frontmatter, mainmatter and backmatter mechanism, taking care of pagenumbering and some other stuff.


text:
Q: How to convert String to Binary using StringBuilder with Array and reverse it? I want to input some text by Scanner, like "John has a dog".
Then i want to convert it (by ASCII table for example) to binary values, so it'll be: 01001010011011110110100001101110 011010000110000101110011 01100001 011001000110111101100111.
And I want to put those binary values in Array or ArrayList (to be able to change some bits).
Then I want to reconvert it, so show it again as a String but with changed some bits, so that sentence should be changed from original "John has a dog".
I have such code, which doesn't seem to work, because char cannot be converted to String.
Scanner skaner = new Scanner (System.in);
String s = skaner.nextLine();
byte[] bytes = s.getBytes();

StringBuilder binary = new StringBuilder();

//  for(int i=0;i<length;i++){
//      hemisphere [i]=new StringBuilder();
//  }
    ArrayList<Byte> bajt = new ArrayList<>();
//  byte[] bin = new byte[seqLenght];

for (byte b : bytes)
{
    int val = b;
    for (int i = 0; i < 8; i++)
    {

        bajt.add(binary.toString().split(' '));
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
    }
    //binary.append(' ');
}
System.out.println("tab"+bytes[1]);

A: I don't understand why you need to have the ArrayList of binary to manipulate the bits.  Once you have the byte array you have everything you need to do bit manipulation.
public static void main(String[] args) throws Exception {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a message: ");
    String message = input.nextLine();

    byte[] messageBytes = message.getBytes();
    // Using OR operation (use 1 - 127)
    for (int i = 0; i < messageBytes.length; i++) {
        messageBytes[i] |= 1;
    }

    System.out.println("Before: " + message);
    System.out.println("After : " + new String(messageBytes));
}

Results:
Enter a message: John has a dog
Before: John has a dog
After : Koio!ias!a!eog

Update to include binary output
public static void main(String[] args) throws Exception {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a message: ");
    String message = input.nextLine();
    byte[] messageBytes = message.getBytes();

    System.out.println("Before: " + message);
    // Display message in binary
    for (int i = 0; i < messageBytes.length; i++) {
        System.out.print(Integer.toBinaryString(messageBytes[i]) + " ");
    }
    System.out.println();

    // OR each byte by 1 as an example of bit manipulation
    for (int i = 0; i < messageBytes.length; i++) {
        messageBytes[i] |= 1;
    }

    System.out.println("After : " + new String(messageBytes));
    // Display message in binary
    for (int i = 0; i < messageBytes.length; i++) {
        System.out.print(Integer.toBinaryString(messageBytes[i]) + " ");
    }
    System.out.println();
}

Results:
Enter a message: John has a dog
Before: John has a dog
1001010 1101111 1101000 1101110 100000 1101000 1100001 1110011 100000 1100001 100000 1100100 1101111 1100111
After : Koio!ias!a!eog
1001011 1101111 1101001 1101111 100001 1101001 1100001 1110011 100001 1100001 100001 1100101 1101111 1100111


text:
Q: Dynamic JSON to model where data with common prefix should go to dictionary I have JSON like that:
{
    "id": "913678a9-63d6-4261-9a4c-d710755c8141",
    "A": null,
    "B": null,
    "C": null,

    "extension_A": "COKOLWIEK",
    "extension_B": "36402User"
}

id, A, B, and C are always in model.
and class:
string a {get;set;}
string b {get;set;}
string c {get;set;}

@JsonIgnore
IDictionary<string,string> extensions {get;set;} = new Dictionary<string,string>();

I'd like to convert Json to object of this class, where all extension_{x} goes into dictionary as KeyValue pair, where key is name of property.
I think about using
JsonConvert.DeserializeObject
and iterate over all properties and add it to dictionary if property name is extension_ ,
but maybe there is better way to do this.


text:
Q: The roots of the equation $(a^4+b^4)x^2+4abcd x + (c^4+d^4)$will be? The discriminant shall be
$$16(abcd)^2-4a^4c^4-4a^4d^4-4b^4c^4-4b^4d^4$$
$$-4(b^2d^2+a^2c^2)^2-4(a^2d^2+b^2d^2)^2$$ which is clearly a negative value. So the roots should be imaginary. But the answer given is real and equal. How is that possible?

A: It will be $$-4(a^2b^2-c^2d^2)^2-4(a^2d^2-b^2c^2)^2\le0$$

A: Your discriminant is written slightly wrong it should be
$$-4(b^2d^2 - a^2c^2)^2 -4(a^2d^2 - b^2c^2)^2.$$
Further as per the equation you have written you are surely   correct that it will have imaginary roots. May be the answer given is wrong or some more information may be provided. Hope this helps.

A: The discriminant is given by $$-a^4c^4-a^4d^4+4a^2b^2c^2d^2-b^4c^4-b^4a^4$$ and now completing the squares.


text:
Q: Error with Parse: PFObject does not have a member named 'createdAt' I am stuck on that issue. I've read the Parse documentation (https://parse.com/docs/ios/guide#queries-query-constraints) but it doesn't helps me that much.
The error
When I try to get "createdAt" or "updatedAt" from a PFObject, I got the following error:

['PFObject'] does not have a member named 'createdAt'

The Code
Here is the (shortened) function:
func loadCheckInData() {

    var query = PFQuery(className: "CheckIn")
    query.orderByDescending("createdAt")
    query.selectKeys(["firstName","lastName","updatedAt","createdAt"])

    query.findObjectsInBackgroundWithBlock({
        (objects: [AnyObject]?, error: NSError?) -> Void in

        if error == nil {

            println(objects)
            // Do something
            if let object = objects as? [PFObject] {
                println("\(object.createdAt)")                  <---- Error here
                self.CheckedPatients = Array(object.generate())
            }
        } else {
            // Log details of the failure
            println("Error: \(error!) \(error!.userInfo!)")
        }
    })
}

Then I retrieve "firstName", "lastName" (and try to retrieve "createdAt") that are in my "CheckIn" Parse's class with the following code
func collectionView(cellView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    // Add parse data
    if let value = CheckedPatients[indexPath.row]["lastName"] as? String {
        cell.cellLabelTwo.text = value
    }
    if let value = CheckedPatients[indexPath.row]["firstName"] as? String {
        cell.cellLabel.text = value
    }
    if let value = CheckedPatients[indexPath.row]["createdAt"] as? String {
        cell.cellDay.text = value
    }
    return cell
}

And I call the function
override func viewDidAppear(animated: Bool) {
    loadCheckInData()
}

In fact I tried differents method to get that "createdAt" value, and I can't make it works. Does anyone have an idea (and a quick explanation if possible) it could be nice.
Thank you !

A: It's simply because updatedAt/createdAt is a property on all PFObjects, no need to retrieve it using a key, just treat it as property.

A: I figured out how to get the property, thanks to @SanitLee answer. I post my code with the solution so that everybody could see it.
Solution
In my function named loadCheckInData() I added for object in objects { to the findObjectsInBackgroundWithBlock method. See below:
func loadCheckInData() {

    var query = PFQuery(className: "CheckIn")
    query.orderByDescending("createdAt")
    query.findObjectsInBackgroundWithBlock({
        (objects: [AnyObject]?, error: NSError?) -> Void in
        if error == nil {

            // Do something
            if let objects = objects as? [PFObject] {
                for object in objects {                 // <---  Added
                    // data stored in the var named "CheckedPatient"
                    self.CheckedPatients = Array(objects.generate())
                }
            }
        } else {
            // ...
        }
    })
}

Then to retrieve the createdAt property inside the cellForItemAtIndexPath function, I changed:
if let value = CheckedPatients[indexPath.row]["createdAt"] as? String {
    cell.cellDay.text = value
}

into:
    var DateVar : PFObject = CheckedPatients[indexPath.row]
    var dateFormatter:NSDateFormatter = NSDateFormatter()      // Formating
    dateFormatter.dateFormat = "EEEE dd MMM HH:mm"
    cell.cellDay.text = dateFormatter.stringFromDate(DateVar.createdAt!)

Now it works as I want. If you have any advice, thorough explanations or improvement about the code, feel free to modify and explain it.
Thanks


text:
Q: Boost Fusion: Nesting flatten_view and zip_view

Hi!
I'm desperately trying to nest different views using Boost Fusion. I'm still in the process of learning Fusion, so apologies if this is a silly question.
My actual scenario is much more complex, but I'll try to simplify it as much as possible for the sake of illustration. I have two Fusion vectors v1 and v2 which are themselves contained in another Fusion vector vv:
typedef fusion::vector<int, int, int> IntVector;
IntVector v1(1,2,3);
IntVector v2(4,5,6);
typedef fusion::vector<IntVector&, IntVector&> VVector;
VVector vv(v1,v2);

What I would like to achieve now is an interleaving of the vectors contained in vv, i.e. a lazy view which traverses vv in the following order:
1,4,2,5,3,6

In order to achieve that, I was thinking about nesting zip and flatten as follows:
typedef fusion::zip_view<VecVector> ZipView;
auto zv = ZipView(vv);
typedef fusion::flatten_view<ZipView> FlattenView;
auto fv = FlattenView(zv);

This compiles, however, as soon as I start dereferencing elements in fv, problems arise. For example:
auto first = fusion::begin(fv);

This produces the following output:
iteration01.cpp:486:27:   instantiated from here
boost/fusion/view/flatten_view/flatten_view_iterator.hpp:80:36: error: no matching function for call to 'boost::fusion::detail::make_descent_cons<boost::fusion::vector_iterator<boost::fusion::vector2<int&, int&>, 0>, void>::apply(const type)'
boost/fusion/view/flatten_view/flatten_view_iterator.hpp:80:36: note: candidate is:
boost/fusion/view/flatten_view/flatten_view_iterator.hpp:54:28: note: static boost::fusion::detail::make_descent_cons<Iterator, <template-parameter-1-2> >::type boost::fusion::detail::make_descent_cons<Iterator, <template-parameter-1-2> >::apply(const Iterator&) [with Iterator = boost::fusion::vector_iterator<boost::fusion::vector2<int&, int&>, 0>, <template-parameter-1-2> = void, boost::fusion::detail::make_descent_cons<Iterator, <template-parameter-1-2> >::type = boost::fusion::cons<boost::fusion::vector_iterator<boost::fusion::vector2<int&, int&>, 0>, boost::fusion::nil_>]
boost/fusion/view/flatten_view/flatten_view_iterator.hpp:54:28: note:   no known conversion for argument 1 from 'const type {aka const boost::fusion::vector_iterator<const boost::fusion::vector2<int&, int&>, 0>}' to 'const boost::fusion::vector_iterator<boost::fusion::vector2<int&, int&>, 0>&'

I've been playing around with this example for ages, but I cannot wrap my head around what's going on. I would be very grateful if anyone could point me into the right direction. Sorry again if this is a stupid question.
Many thanks!

A: Most likely, the views return references to the underlying sequence, but somewhere down the line it gets too complicated (I haven't actually dug down the error chain).
What usually helps is to interpose a simpler sequence.
Using as_vector:
Live On Coliru
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/zip_view.hpp>
#include <boost/fusion/include/view.hpp>

using namespace boost;

int main()
{
    typedef fusion::vector<int, int, int> Tuple3;
    Tuple3 v1(1,2,3);
    Tuple3 v2(4,5,6);

    typedef fusion::vector<Tuple3&, Tuple3&> VVector;
    VVector vv(v1,v2);

    typedef fusion::zip_view<VVector> ZipView;
    auto zv = fusion::as_vector(ZipView(vv));
    typedef fusion::flatten_view<decltype(zv)> FlattenView;
    auto fv = FlattenView(zv);

    // proof of the pudding:
    auto first = fusion::begin(fv);
}

You will think "if I can afford to copy the values" but from the looks of it, the compiler might still generate identical object code anyways, so be sure to check your needs before optimizing.


text:
Q: Автоматическое обновление страницы при изменениях БД Я написал бек-часть веб приложения "Список дел" на spring boot, но сейчас хочу добавить простенький веб-интерфейс с помощью html и js. Список дел подгружается на главной странице из БД через html:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>To Do List</title>

    <link rel="stylesheet" type="text/css" href="/css/styles.css">

    <form>

Добавление дела

        Дело:
        <input type="text" name="name" value="">

        <button id="save-task">Сохранить</button>
    </form>

Список дел

   <button id="show-add-task-form">Добавить дело</button>

В чем проблема: нужно, чтобы на странице сразу появлялось дело при добавление через форму. Находил инфу про куки, проверку на изменения, но не знаю, как и где это применить для себя..
Я очень плохо знаком с js, поэтому прошу не хейтить за, возможно, очевидный вопрос. Буду рад любой помощи, спасибо!
JS:

$(function(){

    const appendTask = function(data){
        var taskCode = '' + data.name + '
';
        $('#task-list')
            .append('
' + taskCode + '
');
    };

    //Show adding task form
    $('#show-add-task-form').click(function(){
        $('#task-form').css('display', 'flex');
    });

    //Closing adding task form
    $('#task-form').click(function(event){
        if(event.target === this) {
            $(this).css('display', 'none');
        }
    });

    //Add task
    $('#save-task').click(function()
    {
        var data = $('#task-form form').serialize();
        $.ajax({
            method: "POST",
            url: '/tasks/',
            data: data,
            success: function(response)
            {
                $('#task-form').css('display', 'none');
                var task = {};
                task.id = response;
                var dataArray = $('#task-form form').serializeArray();
                for(i in dataArray) {
                    task[dataArray[i]['name']] = dataArray[i]['value'];
                }
                appendTask(task);
            }
        });
        return false;
    });

});

A: Перепробовал кучу всего и нашёл простое и изящное решение:

//Add task
    $('#save-task').click(function()
    {
        var data = $('#task-form form').serialize();
        $.ajax({
            method: "POST",
            url: '/tasks/',
            data: data,
            success: function(response)
            {
                $('#task-form').css('display', 'none');
                var task = {};
                task.id = response;
                var dataArray = $('#task-form form').serializeArray();
                for(i in dataArray) {
                    task[dataArray[i]['name']] = dataArray[i]['value'];
                }
                appendTask(task);
                $('#divSettings').html(response); //просто добавил этот кусок кода
            }
        });
        return false;
    });


text:
Q: PostgreSQL: Select entre datas + hora Bom dia. Na tabela movimento, tenho, além de outros, os campos data e hora. Preciso fazer um select entre a data escolhida e seu dia posterior (Ex.: entre 11/09/2020 e 12/09/2020). Preciso que o select filtre entre as '07:00' do dia 11/09/2020 e as '07:00' do dia 12/09/2020, informando os movimentos de 24 horas.
Entre as datas, informando manualmente, ok:
select * from movimento
WHERE '[2020-09-11, 2020-09-12]'::daterange @> data
order by data,hora

Contudo queria, tbm, pegar automaticamente o dia posterior ao primeiro dia informado. Além dos filtros de hora. À saber: No sistema, a hora é informada manualmente durante o registro pois pode ser realizado fora do horário atual.

A: Olá,
Pelo que entendi, você informa uma data a partira da qual você quer o intervalo de 24h (ou 1) dia após a hora escolhida.
Tente usar o interval:
select *
from movimentos
where true
-- obeservar que o valor da data '2020-09-11 07:00:00' deve vir de alguma variável que é utilizada duas vezes
and (data + hora)::timestamp between '2020-09-11 07:00:00' and ('2020-09-11 07:00:00'::timestamp + interval '1 day')
order by
data,
hora

Dê uma olhada aqui também. Exemplo
Aqui tem tudo o que o postgresql oferece em relação a isso Documentação
PS: Não esqueça de dizer se te atende ou não.


text:
Q: Transfer functions How do I find the magnitude of the following:
$G(jw) = \frac{jw}{(10^4 + jw)}$
I have tried to take multiply the numerator and denominator by $-jw$ to ultimately come up with $w/(\sqrt{w^2 + 10^8})$ as my final answer, but that doesn't seem like the right approach.

A: For a complex number $z$ we have
$$
|z| = \sqrt{z\cdot \bar z}
$$
then
$$
|G(j\omega)| = \sqrt{\left(\frac{j\omega}{10^4+j\omega}\right)\left(\frac{-j\omega}{10^4-j\omega}\right)} = \frac{\omega}{\sqrt{10^8+\omega^2}}
$$


text:
Q: AspectJ - Is is possible to extend an enum's value? Say I have an enum
public enum E {A,B,C}

Is it possible to add another value, say D, by AspectJ?
After googling around, it seems that there used to be a way to hack the private static field $VALUES, then call the constructor(String, int) by reflection, but seems not working with 1.7 anymore.
Here are several links:
http://www.javaspecialists.eu/archive/Issue161.html (provided by @WimDeblauwe )
and this: http://www.jroller.com/VelkaVrana/entry/modify_enum_with_reflection

A: Actually, I recommend you to refactor the source code, maybe adding a collection of valid region IDs to each enumeration value. This should be straightforward enough for subsequent merging if you use Git and not some old-school SCM tool like SVN.
Maybe it would even make sense to use a dynamic data structure altogether instead of an enum if it is clear that in the future the list of commands is dynamic. But that should go into the upstream code base. I am sure the devs will accept a good patch or pull request if prepared cleanly.
Remember: Trying to avoid refactoring is usually a bad smell, a symptom of an illness, not a solution. I prefer solutions to symptomatic workarounds. Clean code rules and software craftsmanship attitude demand that.

Having said the above, now here is what you can do. It should work under JDK 7/8 and I found it on Jérôme Kehrli's blog (please be sure to add the bugfix mentioned in one of the comments below the article).
Enum extender utility:
package de.scrum_master.util;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import sun.reflect.ConstructorAccessor;
import sun.reflect.FieldAccessor;
import sun.reflect.ReflectionFactory;

public class DynamicEnumExtender {

    private static ReflectionFactory reflectionFactory =
        ReflectionFactory.getReflectionFactory();

    private static void setFailsafeFieldValue(Field field, Object target, Object value)
        throws NoSuchFieldException, IllegalAccessException
    {
        // let's make the field accessible
        field.setAccessible(true);

        // next we change the modifier in the Field instance to
        // not be final anymore, thus tricking reflection into
        // letting us modify the static final field
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        int modifiers = modifiersField.getInt(field);

        // blank out the final bit in the modifiers int
        modifiers &= ~Modifier.FINAL;
        modifiersField.setInt(field, modifiers);

        FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false);
        fa.set(target, value);
    }

    private static void blankField(Class<?> enumClass, String fieldName)
        throws NoSuchFieldException, IllegalAccessException
    {
        for (Field field : Class.class.getDeclaredFields()) {
            if (field.getName().contains(fieldName)) {
                AccessibleObject.setAccessible(new Field[] { field }, true);
                setFailsafeFieldValue(field, enumClass, null);
                break;
            }
        }
    }

    private static void cleanEnumCache(Class<?> enumClass)
        throws NoSuchFieldException, IllegalAccessException
    {
        blankField(enumClass, "enumConstantDirectory"); // Sun (Oracle?!?) JDK 1.5/6
        blankField(enumClass, "enumConstants"); // IBM JDK
    }

    private static ConstructorAccessor getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes)
        throws NoSuchMethodException
    {
        Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
        parameterTypes[0] = String.class;
        parameterTypes[1] = int.class;
        System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
        return reflectionFactory.newConstructorAccessor(enumClass .getDeclaredConstructor(parameterTypes));
    }

    private static Object makeEnum(Class<?> enumClass, String value, int ordinal, Class<?>[] additionalTypes, Object[] additionalValues)
        throws Exception
    {
        Object[] parms = new Object[additionalValues.length + 2];
        parms[0] = value;
        parms[1] = Integer.valueOf(ordinal);
        System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length);
        return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms));
    }

    /**
     * Add an enum instance to the enum class given as argument
     *
     * @param <T> the type of the enum (implicit)
     * @param enumType the class of the enum to be modified
     * @param enumName the name of the new enum instance to be added to the class
     */
    @SuppressWarnings("unchecked")
    public static <T extends Enum<?>> void addEnum(Class<T> enumType, String enumName) {
        // 0. Sanity checks
        if (!Enum.class.isAssignableFrom(enumType))
            throw new RuntimeException("class " + enumType + " is not an instance of Enum");

        // 1. Lookup "$VALUES" holder in enum class and get previous enum
        // instances
        Field valuesField = null;
        Field[] fields = enumType.getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().contains("$VALUES")) {
                valuesField = field;
                break;
            }
        }
        AccessibleObject.setAccessible(new Field[] { valuesField }, true);

        try {

            // 2. Copy it
            T[] previousValues = (T[]) valuesField.get(enumType);
            List<T> values = new ArrayList<T>(Arrays.asList(previousValues));

            // 3. build new enum
            T newValue = (T) makeEnum(
                enumType,                         // The target enum class
                enumName,                         // THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED
                values.size(), new Class<?>[] {}, // could be used to pass values to the enum constuctor if needed
                new Object[] {}                   // could be used to pass values to the enum constuctor if needed
            );

            // 4. add new value
            values.add(newValue);

            // 5. Set new values field
            setFailsafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0)));

            // 6. Clean enum cache
            cleanEnumCache(enumType);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

Sample application & enum:
package de.scrum_master.app;

/** In honour of "The Secret of Monkey Island"... ;-) */
public enum Command {
    OPEN, CLOSE, PUSH, PULL, WALK_TO, PICK_UP, TALK_TO, GIVE, USE, LOOK_AT, TURN_ON, TURN_OFF
}

package de.scrum_master.app;

public class Server {
    public void executeCommand(Command command) {
        System.out.println("Executing command " + command);
    }
}

package de.scrum_master.app;

public class Client {
    private Server server;

    public Client(Server server) {
        this.server = server;
    }

    public void issueCommand(String command) {
        server.executeCommand(
            Command.valueOf(
                command.toUpperCase().replace(' ', '_')
            )
        );
    }

    public static void main(String[] args) {
        Client client = new Client(new Server());
        client.issueCommand("use");
        client.issueCommand("walk to");
        client.issueCommand("undress");
        client.issueCommand("sleep");
    }
}

Console output with original enum:
Executing command USE
Executing command WALK_TO
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant de.scrum_master.app.Command.UNDRESS
    at java.lang.Enum.valueOf(Enum.java:236)
    at de.scrum_master.app.Command.valueOf(Command.java:1)
    at de.scrum_master.app.Client.issueCommand(Client.java:12)
    at de.scrum_master.app.Client.main(Client.java:22)

Now you can either add an aspect with an advice executed after the enum class was loaded or just call this manually in your application before extended enum values are to be used for the first time. Here I am showing how it can be done in an aspect.
Enum extender aspect:
package de.scrum_master.aspect;

import de.scrum_master.app.Command;
import de.scrum_master.util.DynamicEnumExtender;

public aspect CommandExtender {
    after() : staticinitialization(Command) {
        System.out.println(thisJoinPoint);
        DynamicEnumExtender.addEnum(Command.class, "UNDRESS");
        DynamicEnumExtender.addEnum(Command.class, "SLEEP");
        DynamicEnumExtender.addEnum(Command.class, "WAKE_UP");
        DynamicEnumExtender.addEnum(Command.class, "DRESS");
    }
}

Console output with extended enum:
staticinitialization(de.scrum_master.app.Command.<clinit>)
Executing command USE
Executing command WALK_TO
Executing command UNDRESS
Executing command SLEEP

Et voilà! ;-)


text:
Q: Function with input not working I have written a function for placeholder functionality of an input field. It works if I write the on/off functions separately, but it's not working when keeping an input variable and if construct. Please help regarding what's wrong in syntax or logic.
function placeholder(x) {
    if (x=="1") {
        if (document.getElementById("search_field").value=="") {
            document.getElementById("placeholder").style.display="inline";
        }
    }
    else {
        document.getElementById("placeholder").style.display="none";
        document.getElementById("search_field").focus();
    }
}

<input id="search_field" type="text" value="" onfocus="placeholder(0);" onblur="placeholder(1);">

Search

A: Try without the quotes on 1 when evaluating x:
 function placeholder(x){
if(x==1){
    if(document.getElementById("search_field").value==""){
    document.getElementById("placeholder").style.display="inline";
    }
}
else{
    document.getElementById("placeholder").style.display="none";
    document.getElementById("search_field").focus();
    }
}

Also, remove the ";" when calling the function:

A: You can just use the placeholder attribute. It is accepted by all major modern browsers and will save you from adding extra HTML tags and JavaScript code.
<input type="text" name="someName" placeholder="Some Text">

Following is the alternative for old browsers where placeholder is not recognized:
DEMO
HTML:
<input id="search_field" type="text" value="Enter keywords..." onfocus="ph(1);" onblur="ph(0);" onclick="ph(1);">

JavaScript:
function ph(x) {
    var txtSearch = document.getElementById("search_field");
    if (x == 1) {
        if (txtSearch.value == "Enter keywords...") {
            txtSearch.value = '';
        }
    }
    else {
        if (txtSearch.value == "") {
            txtSearch.value = 'Enter keywords...';
        }
    }
}

A: Check if the function was called or not.
If not then change it:
<input id="search_field" type="text" value="" onfocus="javascript:placeholder(0)" onblur="javascript:placeholder(1)">


text:
Q: Stopping postfix - are messages queued when postfix is idle? I am running some scans on my server tonight and would like to disable email notifications since there is a chance for a LOT of them to be sent out.
I am planning to issue
service postfix stop

while the web scan occurs.
If postfix is stopped, will mail messages go into a queue and be sent when the service is started again?  If so, is there a way to easily nuke any queued messages?   The messages would be triggered through php's mail function, which ordinarily hands off to postfix.

A: The PHP mail function will invoke the sendmail binary to send a message. So there is not a need for the postfix daemon to be running.
Sendmail will place the email in the maildrop queue. When postfix starts running, the pickup daemon will pick the message and send it. When postfix isn't running, emails stay in maildrop queue forever until they are picked up when postfix runs again.
Resources: Postfix Architecture Overview

Local submissions are received with the Postfix sendmail(1) compatibility command, and are queued in the maildrop queue by the privileged postdrop(1) command. This arrangement even works while the Postfix mail system is not running. The local pickup(8) server picks up local submissions, enforces some sanity checks to protect Postfix, and gives the sender, recipients and message content to the cleanup(8) server.

If so, is there a way to easily nuke any queued messages
Yes. Because the email is stored in maildrop queue, you can run postsuper -d ALL maildrop to nuke all of them. See man 1 postsuper.
# postsuper -d ALL maildrop
postsuper: Deleted: 1 message


text:
Q: How do I combine multiple rows into one column in SQL? My code looks like below:
select distinct
    HSP_ACCOUNT_ID
    ,TOT_ACCT_BAL
    ,DISCH_DATE_TIME
    ,UB_REV_CODE_ID
    ,PROC_CODE
    ,DATEDIFF(dd,act.DISCH_DATE_TIME,GETDATE()) as "Aging"

from HSP_ACCOUNT

where
    SERV_AREA_ID = 10
    and ACCT_BILLSTS_HA_C = '3' --Billed
    and DISCH_DATE_TIME >= '20171024'
    and TOT_ACCT_BAL is not null
    and TOT_ACCT_BAL <> 0

With results like below:
HSP_ACCOUNT_ID  TOT_ACCT_BAL    DISCH_DATE_TIME UB_REV_CODE_ID  PROC_CODE Aging
117244          830.03          10/24/2017  320         32074230  2
117244          830.03          10/24/2017  440         44008996  2
117244          830.03          10/24/2017  440         44008997  2
117244          830.03          10/24/2017  440         44008998  2
117244          830.03          10/24/2017  444         44492611  2

How can I get the all the different UB_REV_CODE_ID and PROC_CODE to populate on one row for each Account ID?

A: Group_concat() will achieve the required task.
select distinct
    HSP_ACCOUNT_ID
    ,TOT_ACCT_BAL
    ,DISCH_DATE_TIME
    ,Group_concat(Distinct UB_REV_CODE_ID separator ' ')
    ,Group_concat(Distinct PROC_CODE separator ' ')
    ,DATEDIFF(dd,act.DISCH_DATE_TIME,GETDATE()) as "Aging"

from HSP_ACCOUNT

where
    SERV_AREA_ID = 10
    and ACCT_BILLSTS_HA_C = '3' --Billed
    and DISCH_DATE_TIME >= '20171024'
    and TOT_ACCT_BAL is not null
    and TOT_ACCT_BAL <> 0
Group by HSP_ACCOUNT_ID;

Note: You should only use above solution if all other columns (except 2 codes) have same values in each row for particular Account Id.
Hope it helps!


text:
Q: Find an irreducible polynomial with zero $\cos(2\pi/7)$ I have a test that asks to find $\operatorname{Irr}(\cos(2\pi/7),\mathbb Q)$.
So I need $f \in  \mathbb Q[x]$, $f(\cos(2\pi/7))=0$ and $f$ irreducible.
How I can solve that, some hint?

A: Hint: Combine the following facts that you should know (if you don't, then you have more reviewing to do). Here $\zeta=e^{2\pi i/7}$.

*

*The number $\zeta$ is a zero of the irreducible polynomial
$$
p(x)=\frac{x^7-1}{x-1}=x^6+x^5+x^4+x^3+x^2+x+1.
$$
Irreducibility can be shown by applying Eisenstein to $p(x\pm1)$ - don't remember which sign works. Also, observe that
$$
\zeta^3+\zeta^2+\zeta+1+\zeta^{-1}+\zeta^{-2}+\zeta^{-3}=\zeta^{-3}p(\zeta).
$$

*We have
$$
\zeta+\zeta^{-1}=2\cos\frac{2\pi}7.
$$
Spend some quality time with the cube and square of this!


text:
Q: Getting URL that caused 404 error C# Is there away to find out the URL that has caused the 404 error.
I have a custom error page set up, and within that I am trying to catch what the URL that caused the 404 error is.
Getting the requested URL just returns the current 404 page.

A: If you are looking for the page that actually threw the error, it will be posted to the query string when directed to your custom error page.
Request.QueryString["aspxerrorpath"];


text:
Q: Decrease self priority for a short period and then increase it back In some cases, I want to decrease the running process priority to execute a costy operation and then increase it back to the original value. The process should do it by itself, without root permission.
I've tried to that inside a ruby app with Process.setpriority.
Ins't it a flaw in kernel's design?
Here it is an example in shell:
$ nice
0

Then
$ renice -n 19 -p $$
5094 (process' ID) old priority 0, new priority 19

Then
$ renice -n 0 -p $$
renice: failed to set priority for 5094 (process' ID): Permission denied

A: Usually only root (or processes with CAP_SYS_NICE privilege) may change their "nice" to higher priority (lower values). But since 2.6.12 version of kernel (http://man7.org/conf/lca2006/Linux_2.6_changes/rlimit_5.html), linux introduced additional way to increasing priority (lowering nice), the RLIMIT_NICE rlimit (man getrlimit). You can check it with ulimit -e in bash, and change by root before switching  (su) to usual user or to nobody (example).
So, what can you do to make your process temporary having low priority (higher nice value):

*

*Get the CAP_SYS_NICE privilege from root

*Set right RLIMIT_NICE (default is 0, so RLIMIT_NICE is disabled and this is the flaw in linux distributions), either by root ulimit -e VALUE or in system-wide /etc/security/limits.conf, item nice (this config is used by pam_limits.so PAM module, so check, is it called before you start the process. Usually it is called by login, *dm managers, crond and atd. Don't know is it called for processes started by init.d scripts)

Two examples of second variant from brauliobo, allow nice back to 0, system-wide. Add to /etc/security/limits.conf:
*              soft    nice    0 # ranges from -20 to 19

Or using sudo to root to change RLIMIT_NICE for single shell:
sudo bash
ulimit -e 20 # equivalent to 0, as it ranges from 0 to 40
sudo -u youruser bash
# now you can renice back to 0

Without help from root user you can:

*

*Fork second process to do the low-priority work and renice only it. Use inter-process communication to send work items and get results.

*You can call sched_yield often when doing low-priority work. This will enable other processes to preempt your program early.


text:
Q: What are important examples of essentially constant systems? This is the definition of an essentially constant systems.

Definition: :Let $M:I \rightarrow C$ be a filtered diagram. Assume that
(a) exists some $i$ such that $$X \rightarrow M_i \rightarrow X$$
  is identity.
(b) For each $j$, exists $k$, and a morphism $M_j \rightarrow M_k$ which factors through
  $$ M_j \rightarrow X \rightarrow M_i  \rightarrow M_k$$

But this all seems a little ad-hoc.

*

*What is the big picture of this definition? I suppose the key notion is the hom set commutes with colimits. Somehow relates to compact objects.

*What are some key examples of essentially constant systems?

A: The big picture is that a filtered diagram $M$ is essentially constant if it is isomorphic in the category $\text{ind-}C$ to a filtered diagram consisting of the single object $X$ and its identity morphism, i.e. isomorphic to the image of an object $X$ in $C$ under the natural embedding $C\hookrightarrow \text{ind-}C$.
Let me try to motivate / unpack this. Suppose we have two filtered diagrams $M\colon I\to C$ and $N\colon J\to C$, and we want to understand the arrows $\text{colim}M\to \text{colim}N$ which "come from the filtered diagrams". Well, an arrow $\text{colim}M\to \text{colim}N$ is determined by a coherent family of arrows $M_i\to \text{colim}N$ for all $i\in I$. But if we want these arrows to "come from the diagrams", we might reasonably require that each arrow $M_i\to \text{colim} N$ factors through one of the objects $N_j$ in the diagram $N$.
Ok, so for each $i\in I$, we want to look at arrows $M_i\to N_j$ for some $j\in J$. But we should consider two of these arrows to be equivalent if we can see that they induce the same arrow to the colimit, i.e. if they are "eventually the same": $f\colon M_i\to N_j$ and $f'\colon M_i\to N_{j'}$ are equivalent if there are arrows $h\colon N_j\to N_k$ and $h'\colon N_{j'}\to N_k$ in the diagram $N$ such that $h\circ f = h'\circ f$. The filteredness of $N$ implies that this is an equivalence relation. With a bit more thought, you can see that the family of all such equivalence classes of arrows out of $M_i$ is $\text{colim}_{j\in J} \text{Hom}(M_i,N_j)$.
This leads us to consider families $(f_i\colon M_i\to N_{j_i})_{i\in I}$ of (equivalence classes) of arrows to the diagram $N$. Of course, to turn such a family into an arrow $\text{colim}M \to \text{colim}N$, we need to assume the family is coherent with the diagram $M$. So if we have an arrow $h\colon M_i\to M_{i'}$ in the diagram, and $f_i\colon M_i\to N_{j_i}$ and $f_{i'}\colon M_k\to N_{j_{i'}}$ are the corresponding arrows in the family, then we want to assume $f_i$ and $f_{i'}\circ h$ are equivalent in the sense of the last paragraph. With a bit more thought, you can see that the family of all such coherent families of equivalence classes of arrows is $\text{lim}_{i\in I}\text{colim}_{j\in J} \text{Hom}(M_i,N_j)$. Which is exactly the definition of $\text{Hom}(M,N)$, the set of arrows between filtered diagrams in the construction of $\text{ind-}C$.
Next question: When are two filtered diagrams "essentially the same"? Well, it should be when they are isomorphic in the category described above. Unpacking this, an isomorphism $M\cong N$ is witnessed by a coherent family of arrows $(f_i\colon M_i\to N_{j_i})_{i\in I}$ and a coherent family of arrows $(g_j\colon N_j\to M_{i_j})_{j\in J}$ such that the families $(g_{i_j}\circ f_i)_{i\in I}$ and $(f_{i_j}\circ g_j)_{j\in J}$ are equivalent to the families of identity arrows on $M$ and $N$, respectively.
Let's unpack what this means in the case of an isomorphism between a filtered diagram $M\colon I\to C$ and a constant diagram consisting of a single object $X$ and the identity morphism $\text{id}_X$:

*

*The family of arrows in one direction is just a single arrow $g\colon X\to M_{i^*}$ for some $i^*\in I$. Coherence is trivial.

*The family of arrows in the other direction is $(f_i\colon M_i\to X)_{i\in I}$, and coherence says that for all $h\colon M_i\to M_j$ in the diagram, $f_i = f_j\circ h$.

*In one direction, we require that $f_{i^*}\circ g\colon X\to M_{i^*}\to X$ is the identity map $\text{id}_X$.

*In the other direction, we require that $(g\circ f_i)_{i\in I}$ is equivalent to the identity family $(\text{id}_{M_i})_{i\in I}$. For all $i\in I$, $g\circ f_i$ is an arrow $M_i\to X\to M_{i^*}$, and $\text{id}_{M_i}$ is an arrow $M_i\to M_i$, and these are equivalent if there is some $k\in I$ and arrows $h\colon M_{i^*}\to M_k$ and $h'\colon M_i\to M_k$ such that $h\circ g\circ f_i$ and $h'\circ \text{id}_{M_i} = h'$ are equal.
So condition (a) in your definition of filtered diagram corresponds to (1) and (3) above, and condition (b) corresponds to (4) above. Condition (2) above comes from the assumption on the stacks project page you link to that $X = \text{colim} M$.
I would prefer to make the definition "$M$ is essentially constant with value $X$" for an arbitrary object $X$, by conditions (1)-(4) above, and then prove that it follows that $X \cong \text{colim} M$.

I'm not sure I know any particularly interesting examples off the top of my head. One special case that comes up sometimes is when a particular object $X$ is cofinal in a directed diagram, in the sense that for all $i\in I$, there is some $i<j$ in $I$ such that $M_j = X$, and whenever $j<k$ in $I$ and $M_j = M_k = X$, the arrow $M_j\to M_k$ is $\text{id}_X$ (or, more generally, can be composed with a further arrow $M_k\to M_l = X$ to be the identity on $X$). In this situation, it follows that the colimit of the diagram is isomorphic $X$, because the diagram is essentially constant with value $X$.


text:
Q: How to calculate probability of being with in one standard deviation of the mean value for a continuous distribution for a pdf of $f(x) = 90x^8(1-x)$, $0 < x < 1$, otherwise $f(x)=0$
I have calculated a  of $F(x) = 10x^9 -9x^{10}$ for $0 < x < 1$
a mean of $9/11$
and a standard deviation of $\sqrt{.0123}$
I'm having a tough time figuring out what the  $\mathbb P(A < x < B)$ would be, and if I use the integral of the pdf or the cdf to calculate said probability.

A: HINT
$$\mathbb P(A < x < B) = \mathbb P(x < B) - \mathbb P(x \le A) = F(B) - F(A)$$


text:
Q: DIsplay data from JSON API using vuejs and axios Below is my JS and HTML code for a Vue.js application I'm building.
The data returns fine but I'm unable to display it on the front.
Any help would be appreciated.

data() {
    return {
      overview: this.getOverview()
    }

  },
  methods: {
    getOverview() {
      return axios.get('http://localhost:8000/v1/overview')
        .then(response => {
          this.results = response.data
          console.log('results data', this.results)
        })
        .catch(function(error) {
          console.log(error);
        })
    }
  }

    {{overview.id}}

    {{overview.schools}}

    {{overview.primary}}

    {{overview.secondary}}

 JSON data

{"schools":545,"counsellors":4,"reports":13,"sub_regions":[{"id":1,"name":"Barima-Waini","schools":45,"primary":42,"secondary":3},{"id":2,"name":"Pomeroon-Supenaam","schools":45,"primary":37,"secondary":8},{"id":3,"name":"Essequibo Islands-West Demerara","schools":72,"primary":59,"secondary":13},{"id":4,"name":"Georgetown","schools":69,"primary":54,"secondary":15},{"id":5,"name":"Outside Georgetown","schools":62,"primary":31,"secondary":31},{"id":6,"name":"Mahaica-Berbice","schools":39,"primary":32,"secondary":7},{"id":7,"name":"East Berbice-Corentyne","schools":71,"primary":54,"secondary":17},{"id":8,"name":"Cuyuni-Mazaruni","schools":31,"primary":28,"secondary":3},{"id":9,"name":"Potaro-Siparuni","schools":22,"primary":20,"secondary":2},{"id":10,"name":"Upper Takutu-Upper Essequibo","schools":49,"primary":45,"secondary":4},{"id":11,"name":"Upper Demerara-Upper Berbice","schools":40,"primary":32,"secondary":8}]}

A: Disclaimer: I've never really used Vue myself
The problem is that you are databinding in your view to a view model property named overview. The value of overview is a Promise that will inevitably resolve with undefined, if it resolves, because the final .then in your promise chain does not return a value:
return axios.get('http://localhost:8000/v1/overview')
  .then(response => {
     this.results = response.data;
     console.log('results data', this.results);
   })
   .catch(function(error) {
     console.log(error);
   });

As you can see, we are assigning the response from the API call to a result property but that is not what we are binding to. I believe that, as Bert suggests, you need assign to this.overview instead of this.result if possibly, I would prefer to simply return the resolved value in the promise chain.
Speaking of promise chains, since you are using Vue, you are transpiling, since you are transpiling, you should leverage async/await for superior readability.
Consider writing code such as
async getOverview() {
  try {
    const {data:{json:{sub_regions}}} = await axios.get('http://localhost:8000/v1/overview');
    console.log('results data', sub_regions);
    this.overview = sub_regions;
  }
  catch (error) {
    console.log(error);
    return [];
  }
}

Thank to Bert's link and helpful analysis, I have updated the answer to reflect a common Vue pattern
You will end up with something like this
new Vue({
  el: "#app",
  data() {
    return {
      overview: []
    }

  },
  methods: {
    async getOverview() {
      try {
        const {data:{json:{sub_regions}}} = await axios.get('http://localhost:8000/v1/overview');
        console.log('results data', sub_regions);
        this.overview = sub_regions;
      }
      catch (error) {
        console.log(error);
        return [];
      }
    }
  },
  created(){
    this.getOverview()
  }
})


text:
Q: Prove that either $a_n \to \infty $ or $a_n\to -\infty$ Let f be continuous and nonzero on R let $a_0$ be arbitrary and define $(a_n)$ recursively by $$a_n=a_{n-1}+f(a_{n-1}), n\ge 1$$ than either $a_n \to \infty $ or $a_n\to -\infty$,
Here
$a_n=a_{n-1}+f(a_{n-1})$
$a_n=a_{n-2}+f(a_{n-2})+f(a_{n-1})$
$a_n=a_{n-3}+f(a_{n-3})+f(a_{n-2})+f(a_{n-1})$
.............
.........
$a_n=a_{0}+f(a_0)+\cdots +f(a_{n-3})+f(a_{n-2})+f(a_{n-1})$
any help from here: thanks


text:
Q: Why does the HttpClient always give me the same response? Environment:
VS2012 Update 4
Windows Phone 8 SDK
a fresh new Windows Phone project based on WP OS 7.1
NuGet pack1: MS Async
NuGet pack2: MS HttpClient
What does the project do
a single test for a forum API:
to post a new thread in the forum and refresh the JSON to check if the "count" is accumulate.
What is the UI mean

1st textblock:
the response json will display here
3 buttons:
[refresh JSON]: use API1 to refresh the threads list
[New Post]: use API2 to post a new thread in the forum, title and text will display below
[IE]: open json in IE use API1
Thread information:
the thread you've just post use [New Post] button
What does the JSON mean
only need to focus 2 parts
count: 244 ---> total threads count in the forum
"57923" ---> the title of the 1st thread (the field "data" is a array of the threads list)
What is the test procedure
1. open the app
2. click [refresh JSON] to get the list
3. remember the "count" part and the "title" of the 1st thread
4. click [New Post] to post a new thread, the title of the thread will display below
5. click [refresh JSON] to see the latest threads list
6. expected: the "count" accumulate by 1 and the "title" part should be the same as below
Problem:
1. after clicking the [New Post], No matter how many times you hit [refresh JSON], the count will not accumulate!
2. but open the url in Chrome(Desktop), you will find that the JSON has already been updated!
3. close the app and reopen it, hit [refresh JSON], the JSON will updated as expected, but when you post a new thread, the problem occurs again
Why and How to solve it?
The code
private async void RefreshJSONButton_Click(object sender, RoutedEventArgs e)
{
    this.JsonView.Text = string.Empty;
    HttpClient client = new HttpClient();
    string url =
        "API1 Address Here";
    string x = await client.GetStringAsync(url);
    this.JsonView.Text = x;
    client.Dispose();
}

private async void NewPostButton_Click_1(object sender, RoutedEventArgs e)
{
    Random rnd = new Random();
    this.num = rnd.Next(1, 99999);

    // generate the title and content with random number
    string threadTitle = this.num.ToString();
    string threadContent = "111" + num.ToString();

    // generate the url
    string url =
        "API2 Address Here";
    url = url + "&title=" + threadTitle + "&content=" + threadContent;

    // use HttpClient to send the new thread
    HttpClient client = new HttpClient();
    string x = await client.GetStringAsync(url);
    client.Dispose();

    // display the thread informartion for further check
    this.titleView.Text = threadTitle;
    this.contentView.Text = threadContent;
}

A: It seems, you are hitting the same URL on every refresh click. Sometime Windows Phone stores the request and response in cache.
If possible, you add one more parameter to your request and on every click just change the value of this parameter. You can use GUID or Unix Timestamp.
You can try like:
 private async void RefreshJSONButton_Click(object sender, RoutedEventArgs e)
    {
        this.JsonView.Text = string.Empty;
        HttpClient client = new HttpClient();
    int unixTimestamp = (int)(DateTime.Now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

    string url =
    "http://API1 Address Here/Your queries&temp=unixTimestamp";
    string x = await client.GetStringAsync(url);
    this.JsonView.Text = x;
    client.Dispose();
    }


text:
Q: Keep the distinct rows among groups based on a column in dplyr My data frame looks like this
df <- data.frame(gene=c("A","B","C","A","B","D"),
                 origin=rep(c("old","new"),each=3),
                 value=sample(rnorm(10,2),6))

  gene origin     value
1    A    old 1.5566908
2    B    old 1.3000358
3    C    old 0.7668213
4    A    new 2.5274712
5    B    new 2.2434525
6    D    new 2.0758326

I want to keep the distinct genes between the groups of old and new in the origin column.
I want my data to look like this
  gene origin     value
3    C    old 0.7668213
6    D    new 2.0758326

A: Grouped by 'gene', look for the number of distinct 'origin' which is 1 in filter
library(dplyr)
df %>%
      group_by(gene) %>%
      filter(n_distinct(origin) == 1) %>%
      ungroup


text:
Q: Swift keyboard problem on presented view controller I am getting a problem with keyboard on presented view controller. I am presenting a bottom sheet from a controller. At this bottom sheet, I have a textView with becomeFirstResponder() delegate at viewDidLayoutSubViews(). But keyboard is pushing presented view controller like in picture. How can I present keyboard above presented view controller without pushing page ?
keyboard image

A: I had the same problem and fixed it using this code:
if #available(iOS 11.0, *) {
    tableview.contentInsetAdjustmentBehavior = .never
} else {
    automaticallyAdjustsScrollViewInsets = false
}

It does not let the inset of titleText/placeHolder be changed