text:
Q: TableView calculates wrong estimatedHeightForRowAt I'm making a chat like application, where the tableView displays dynamic height cells.

The cells have their views&subviews constrained in the right way

So that the AutoLayout can predict the height of the cells
(Top, Bottom, Leading, Trailing)

But still - as you can see in the video - the scroll indicator bar shows that wrong heights were calculated:
It recalculates the heights when a new row is appearing.
Video: https://youtu.be/5ydA5yV2O-Q
(On the second attempt to scroll down everything is fine)

Code:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

It is a simple problem. Can someone help me out?
Update 1.0
Added github:
https://github.com/krptia/Test

A:
But still - as you can see in the video - the scroll indicator bar shows that wrong heights were calculated:

So what you want is precise content height.
For that purpose, you cannot use static estimatedRowHeight.
You should implement more correct estimation like below.
    ...

    var sampleCell: WorldMessageCell?

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(UINib(nibName: "WorldMessageCell", bundle: nil), forCellReuseIdentifier: "WorldMessageCell")

        sampleCell = UINib(nibName: "WorldMessageCell", bundle: nil).instantiate(withOwner: WorldMessageCell.self, options: nil)[0] as? WorldMessageCell
    }

    ...

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        if let cell = sampleCell {
            let text = self.textForRowAt(indexPath)
            // note: this is because of "constrain to margins", which value is actually set after estimation. Do not use them to remove below
            let margin = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 20)
            // without "constrain to margins"
            // let margin = cell.contentView.layoutMargins
            let maxSize = CGSize(width: tableView.frame.size.width - margin.left - margin.right,
                                 height: CGFloat.greatestFiniteMagnitude)
            let attributes: [NSAttributedString.Key: Any]? = [NSAttributedString.Key.font: cell.messageLabel.font]
            let size: CGRect = (text as NSString).boundingRect(with: maxSize,
                                                                 options: [.usesLineFragmentOrigin], attributes: attributes, context: nil)
            return size.height + margin.top + margin.bottom
        }
        return 100
    }

This is too precise (actually real row height) and maybe slow, but you can do more approximate estimation for optimization.

A: You need to set tableFooterView to empty.
override func viewDidLoad() {
    super.viewDidLoad()
    tableView.tableFooterView = UIView()
    // your staff
}

A: The problem is with your estimatedHeightForRowAt method. As the name implies it gives the estimated height to the table so that it can have some idea about the scrollable content until the actual content will be displayed. The more accurate value will result in a more smooth scrolling and height estimation.
You should set this value to big enough so that it can represent the height of your cell with the maximum content. In your case 650 is working fine.
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return 650
}

The result would be far better with this approach.
Also, there is no need to implement delegate method for height until you want a variation on index bases. You can simply set table view property.
tableView.estimatedRowHeight = 650.0
tableView.rowHeight = .automaticDimension

Optimization
One more thing I noticed in your demo project. You've used too many if-else in your cellForRowAtIndexPath which is making it little slower. Try to minimize that. I've done some refinement to this, and it improves the performance.

*

*Define an array which holds your message text.
var messages = ["Lorem ipsum,"many more",.....]

*Replace your cellForRowAt indexPath with below:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell : WorldMessageCell
    cell = tableView.dequeueReusableCell(withIdentifier: "WorldMessageCell", for: indexPath) as! WorldMessageCell
    if indexPath.row < 14 {
        cell.messageLabel.text = messages[indexPath.row]
    }
    else if indexPath.row >= 14 && indexPath.row != 27 {
        cell.messageLabel.text = messages[14]
    }
    else if indexPath.row == 27 {
        cell.messageLabel.text = messages.last
    }
return cell
}

A: According to your answer on my comment that when you set

estimatedHeightForRowAt and heightForRowAt the same values it does
  work

I can confirm that you are right and that there is the problem that AutoLayout cannot calculate the right value for estimatedHeightForRowAt. So basically there are two possible things to do:

*

*find alternative layout that will produce better results

*make your own calculation for estimatedHeightForRowAt which will produce more accurate results (in general you should be able to tell what is expected height per text length and then add margins to that figure - you need to put a bit of effort to find the proper math, but it should work).

A:
Just remove highlighted view from UITableView and it's work like a charm.

Hope it helps.

A: This is expected behaviour when using coarse cell height estimates (or not providing them at all, as you do). The actual height is computed only when the cells come on screen, so the travel of the scroll bar is adjusted at that time. Expect jumpy insertion/deletion animations too, if you use them.

A: I hope you heard about this a lot. so take short break and come back on desk and apply 2 - 3 steps for step this.
1) Make sure Autolayouts of label of Cell is setup correct like below.

2) UILabel's number of lines set zero for dynamic height of text.

3) setup automatic dimension height of cell.
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

and I believe its should be work. see results of my code.

A: why you add view in table view , it can also work without it. I just delete that view and change some constraints(like bottom constraints change safe area to superview) , and it works fine.
see this video
download storyboard and add it to your project and then check

A: Configure your tableview with these in viewDidLoad()
        tableView.estimatedRowHeight = 100.0
        tableView.rowHeight = UITableView.automaticDimension
        tableView.tableFooterView = UIView()

And you should remove both height datasource method.

A: What you want to do is eliminate the extra blank cells. You can do so by setting the tableFooterView to an empty UIView in the viewDidLoad method. I cloned the code from your GitHub and revised the method:
override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(UINib(nibName: "WorldMessageCell", bundle: nil), forCellReuseIdentifier: "WorldMessageCell")
    tableView.tableFooterView = UIView()
}

setting the tableFooterView to nil worked for me as well
tableView.tableFooterView = nil


text:
Q: Rails uploading to Amazon S3 bucket I have two differnt buckets in the same Amazon S3 account. I can upload fine to one but not the other.
pictures.rb
def self.set_s3_direct_post
  return S3_BUCKET.presigned_post(key: "uploads/#{SecureRandom.uuid}/${filename}", success_action_status: '201', acl: 'public-read')
end

aws.rb
S3_BUCKET = Aws::S3::Resource.new.bucket(ENV['S3_FIRST_BUCKET'])

Trying to change bucket (with S3_SECOND_BUCKET instead of S3_FIRST_BUCKET) results in a failed upload. I notice that the url for a failed upload is in the form:
https://s3.amazonaws.com/%E2%80%9Csecond_bucket%E2%80%9D

but a successful upload looks like:
https://first_bucket.s3.amazonaws.com

How do I control this??

A: Unbelievable. I edited my ~/.profile file in TextEdit. The addition of the line:
export S3_SECOND_BUCKET="second_bucket"

put slightly curly double-quotes around second_bucket. Turns out these double-quotes are different to the ones Sublime Text 2 uses, which are straight (like above). The TextEdit versions weren't being recognised as quotes. Cheers TextEdit, you t**t.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python's os.listdir() with os.path.isdir() does not return all directories I'm traversing a directory tree (upwards) and I need to find all directories. However the output of os.listdir(), when combined with os.path.isdir() is not what I would expect.
For example, this only shows two directories (bin and dev):
    $ python
Python 2.7.9 (default, Mar  1 2015, 12:57:24)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> for d in os.listdir('/'):
...  if os.path.isdir(d):
...   print d
...
bin
dev
>>>

However, removing the os.path.isdir() call lists all entries, both files and directories:
>>> for d in os.listdir('/'):
...  print d
...
sbin
home
initrd.img
[...]
run
sys
>>>

The surprising bit is that running isdir on a directory that is not listed by the first snippet returns True:
>>> os.path.isdir('/run')
True
>>>

What am I missing?

A: Your os.path.isdir is checking if the directory exists under the current directory, not the directory that os.listdir is listing ('/').
Try this:
for d in os.listdir('/'):
    if os.path.isdir(os.path.join('/', d)):
        print d


text:
Q: Change jdbc.properties with context.xml I make Spring webapp and I use jdbc.properties files from DB.
In applicationContext.xml I have this
<context:property-placeholder location="classpath:cfg/properties/jdbc.properties"/>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
    p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
    p:password="${jdbc.password}" />

Now, I want to change place from my properties  from my DB , now I have context.xml file in tomcat and also context.xml in META-INF in webapp .
 in context.xml I have  :
<?xml version='1.0' encoding='utf-8'?>
<Context path="/webapp" docBase="../webapp/webapp.war" displayName="webapp">
<Environment name="jdbc.driverClassName" override="false"     type="java.lang.String" value="org.postgresql.Driver"/>
<Environment name="jdbc.dialect" override="false" type="java.lang.String"   value="..."/>
<Environment name="jdbc.databaseurl" override="false" type="java.lang.String" value="..."/>
<Environment name="jdbc.username" override="false" type="java.lang.String" value=""/>
<Environment name="jdbc.password" override="false" type="java.lang.String" value=""/>
</Context>

What I need to change in applicationContext to webapp looking properties from context.xml , or better  how I can put in jdbc.properties values from tomcat context.xml file?

A: And that's where JNDI comes in... In your Tomcat's conf directory, context.xml file add:
 <Resource name="jdbc/your_app_ds"
          auth="Container"
          type="javax.sql.DataSource"
          username="username"
          password="password"
          driverClassName="org.postgresql.Driver"
          maxActive="100"
          maxIdle="10"
          validationQuery="select 1"
          minEvictableIdleTimeMillis="300000"
          timeBetweenEvictionRunsMillis="100000"
          testWhileIdle="true"
          url="db_url"/>

Then in your Spring file all you need to do is to define JNDI entry like this:
<jee:jndi-lookup id="dataSource"
                 jndi-name="jdbc/your_app_ds"
                 expected-type="javax.sql.DataSource"/>

This way Spring will create javax.sql.DataSource implementation instance and you'll get a hold of it via dataSource id.
Just do not forget to specify schema location for jee prefix:
xmlns:jee="http://www.springframework.org/schema/jee"

and:
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd"

A: You can have a propery holder bean like
<!-- Load values for configuration placeholders, evaluated at startup only -->
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="ignoreResourceNotFound" value="true" />
    <property name="location" value="file:${user.dir}/jdbc.properties" />
</bean>


text:
Q: Azure Synapse: Connect to Apache spark pool using a local Python script I am working with Azure Synapse. Here, I can create a notebook, select one of the Apache Spark Pools and execute the following code:
%%pyspark
df = spark.sql("SELECT * FROM DataBaseName")
df.show(10)

I have the use-case where I need to be able execute code from a local Python script. How do I create a connection with a specific pool, push the code to the pool for execution and if applicable get the results?
As my local editor I am using Spyder.


text:
Q: Looking for Programming Language that allows you to change true and false For my curiosity sake I'm looking for a dynamic object oriented language that allows you to change true to false and vice versa.
Something like this:
true = false, false = true;

This should also affect any conditional statements, therefore 42 == 42 should return False.
Basically, with this premise, nothing in the language would be safe from the programmer.
Is there any language like this?

A: Smalltalk will let you do this.

Everything in Smalltalk-80 is
  available for modification from within
  a running program. This means that,
  for example, the IDE can be changed in
  a running system without restarting
  it. In some implementations, the
  syntax of the language or the garbage
  collection implementation can also be
  changed on the fly. Even the statement
  true become: false is valid in
  Smalltalk, although executing it is
  not recommended. When used
  judiciously, this level of flexibility
  allows for one of the shortest
  required times for new code to enter a
  production system.

http://en.wikipedia.org/wiki/Smalltalk

A: Python (before version 3, apparently):
True = False
print True, False

>>False False

But:
True = False
print 1==1, 1!=2, 2!=2

>>True True False

For details, see, for example:

*

*Why can't Python handle true/false values as I expect?

*Has TRUE always had a non-zero value?

A: There are two possible answers to your question.
One possibility: you might still be using true and false, but you live in a foreign land where you call them by different names. In that case, it's just a matter of what the compiler/debugger environment displays - that's changeable by modifying the programming tools. (Or, you could start with LISP, which lacks a boolean primitive.)
Or, maybe what you're saying is that you want it to have consequences. For example, if you wanted this not to print anything:
if (42==42) {
   print("This is true");
}

The consequences of this are beyond my ability to imagine, but if you were to redefine conditional primitives (if, switch, etc.) you could do it. It would probably be easiest in a bare-bones LISP, by creating new versions of those conditionals. Looks like Bryan discussed that when talking about Tcl.

Aside: Let's say you create a language where false is true, true is false, ifs are if nots, !=s are ==s, and so on. Perhaps if you inverted enough things you'd get back to the original language. :)

A: C/C++ would allow you to define macros so TRUE==FALSE and FALSE==TRUE
You could also overload the == operator to be equivalent to != (and vice versa) as a separate step.

A: There is a difference between changing the literals/constants that represent true and false and changing the meaning of boolean expressions. The first is easy and can be done trivially with either the program source, for example in C:
#define TRUE 0
#define FALSE 1

or the compiler source.
But changing how boolean expressions are evaluated in all circumstances would be less trivial but not too difficult. It would once again require changes to the compiler or interpreter source, though.

A: Tcl might do what you want. Maybe. You can't exactly redefine true and false since tcl doesn't really have such a thing as a true or false object or value, but you can redefine all the commands that act on expressions to return the opposite of what it normally does. For example, you can redefine "if" to return the opposite of the core definition of if.
Here's a trivial, incomplete example:
# keep the old if around
rename if ::_if

# make a new if with a negated condition
proc ::if {condition args} {
     set command [list _if !($condition) {*}$args]
     uplevel $command
}

Running this interactively I get:
% if true {puts true} else {puts false}
false
% if 1==1 {puts true} else {puts false}
false

(requires tcl 8.5+)

A: In the unlikely event that I wanted this, I would just re-define if, (or make IF a macro and then use it...)


text:
Q: Plot a function for every row in an R data frame This is my data frame:
Variables:
$ X1 (dbl) 3.742382, 4.185260, 3.869329, 4.468430, 4.287528, 4.422470, 4.23...
$ X2 (dbl) 7.0613552, 3.1143999, 6.4780125, 0.8486984, 3.4132880, 1.6816965...
$ X3 (dbl) -2.02416823, 9.10853246, -0.56165113, 16.16834346, 8.02026020, 1...
$ X4 (dbl) 15.0497971, 5.0139219, 13.8001589, -2.0927945, 6.5455396, -0.790...

Xn are the parameters of a 4th degree polynomial:
f(x) = X1*x + X2*x^2 + X2*x^3 + X2*x^4

Thus, each row represents a function. Is it possible to plot each function in the same graph?

A: I would try something like this (although it is not an optimal solution)
f <- function (x, X0, X1, X2, X3, X4){
  return (X0 + X1*x + X2*x^2 + X3*x^3 + X4*x^4)
}

x <- seq(-10,10,length.out = 100)
for (i in c(1:length(DF$X1)){
  plot( f(x, 0, DF$X1[i], DF$X2[i], DF$X3[i], DF$X4[i]) ,t='l')
  par(new = TRUE)
}

Please note that I have defined a function of degree 4 (therefore you need 5 coefficients to express it). Your data suggested that X0 = 0.
I also decided to plot the polynoms between -10 and 10, you can change it if you want...

A: As addition to @T.Des answer I have an alternative approach using dplyr and ggplot2 packages. Run the script step by step to see how it works.
library(dplyr)
library(ggplot2)

# get the parameters as a dataframe
dt = data.frame(x1 = c(2,4,5),
                x2 = c(6,7,2),
                x3 = c(1,2,4),
                x4 = c(2,1,8))

# create plot_id based on the number of plots you want to produce
dt$plot_id = 1:nrow(dt)

# input how many points you want for your plot
Np = 10

data.frame(expand.grid(dt$plot_id, 1:Np)) %>%                     # create all combinations of plot id and points
  select(plot_id = Var1,
         point=Var2) %>%
  inner_join(dt, by="plot_id") %>%                                # join back the parameters
  mutate(y = x1*point + x2*point^2 + x3*point^3 + x4*point^4,     # calculate your output value
         plot_id = as.character(plot_id)) %>%
  ggplot(., aes(point,y,color=plot_id)) +
  geom_line()

Based on my example dataset you should get something like:

A: You also could do it like this with pure base R functionality:
set.seed(1)
x  <- seq(-10, 10, length.out = 100)
xx <- rbind(x, x ^ 2, x ^ 3, x ^ 4)
m  <- matrix(rnorm(40), ncol = 4) # your coefficients
matplot(x, t(m %*% xx), type = "l")

So note that there is no constant term in your polynomial. You just need to adapt x to your data and run this code.

A: Something like this?
DF <- data.frame(X1 = rnorm(10), X2 = rnorm(10), X3 = rnorm(10), X4 = rnorm(10))

# fixed plot region:
xmin<-0
xmax<-10
ymin<- -10
ymax<-10

for (i in 1:10 ) {
curve(DF$X1[i]*x+DF$X2[i]*x^2+DF$X3[i]*x^3+DF$X4[i]*x^4, xlim=c(xmin,xmax), ylim=c(ymin,ymax), add=TRUE)
}

EDIT:By using ggplot:
library(ggplot2)
library(reshape)

xmin<-0
xmax<-10
step<-0.01

DF <- data.frame(X1 = rnorm(10), X2 = rnorm(10), X3 = rnorm(10), X4 = rnorm(10))

xx<-seq(xmin,xmax,by=step)
DF2<-data.frame(matrix("", ncol = length(DF$X1), nrow = length(xx)))
DF2$xx<-xx
for(i in 1:length(DF$X1)){
DF2[,i]<-DF$X1[i]*xx+DF$X2[i]*xx^2+DF$X3[i]*xx^3+DF$X4[i]*xx^4
}

DF3 <- melt(DF2 ,  id.vars = "xx")

ggplot(DF3, aes(xx,value)) + geom_line(aes(colour = variable))


text:
Q: Debug cpu usage (any process) on Device possible? Im wondering that there are a few apps in market, which show the cpu usage for each process.
I dont know how they get this infos. Anybody knows that?
The only solution i know is to read /proc//stat for any process, so I need Jiffies/ms and sysconf(_SC_CLK_TCK).
I parsed Jiffies via /proc/timer_list but i dont know where to get sysconf(_SC_CLK_TCK).


text:
Q: I have a method / function in python in which i'm trying to get a return value which i can then use as a variable in another function So i'm trying to learn Python and at the same time write some code to help myself out with some mundane tasks.
so i have a function which works just fine if i use the print statement to display just what i need, but when i replace the "print" statement for a "return" i only get the first element in the list, i know its because "return" causes the function to exit, but i have no idea how i can get this to return the rest of the elements.
i have tried lots of things and been now reading for hours :( and still getting no further.
objective: To read all the "*.common" files in a directory and then compare them with a text file containing some names, and if they match return the name of the *.common file so i can use it in another function as a variable.
code i have thus far
# This method gets the list of common files....
def get_common_files():
    path = (config_home)
    files = []

    for r, d, f in os.walk(path):
        for file in f:
            if '.common' in file:
                files.append(file)

    for f in files:
        return files

new_file = get_common_files()

def build_default_manifest():
    for line in fileinput.FileInput(new_manifest):
        for name in new_file:
            if line.strip() in name:
                print(name) # works as it should and displays all that i need
                return name  # only shows me the first element

good_name = build_default_manifest()
print(good_name)

i hope i've provided all that i need to but if not please feel free to comeback to me...

A: When you do this:
for f in files:
    return files

This is not quite right. There are 2 problems here. First, what this is doing is just returning files-- the whole thing, one time. Putting a loop body around the return doesn't really make sense. Likely you meant to type return f, to iterate over the results.... but that leads to a second problem...
The return statement will run the first time it is encountered, causing the function to end, and that's it. So just changing what is returned to return f still doesn't quite work: it will return only the first value in files.
This is actually really close to a slightly more advanced pattern called a generator. If you replace the above with this:
for f in files:
    yield f

then your function should work. Explaining why it works is not quite as easy, but this question
has some good answers that should help.
Just out of curiosity, did you write this from scratch yourself, or did you follow an example from somewhere? I'm just a bit surprised at how close you got to the generator pattern, apparently unintentionally, and assuming you were not aware of it before.

A: def build_default_manifest():
    for line in fileinput.FileInput(new_manifest):
        for name in new_file:
            if line.strip() in name:
                yield name

good_name = build_default_manifest()
for name in good_name:

    print(name)

like Z4-tier said, sounds like you need a generator.
you can use each element in good_name for a function call like normal.

A: Perhaps I'm missing something here but isn't your for loop (for r, d...) already creating your list called 'files'? So, why not just change:
for f in files:
    return files

to
return files

which should just return the entire list?


text:
Q: Meaning of "under issue" I was recently checking for the status of an application filed for a specific purpose when I came across the phrase "under issue" as in "the letter dated xxx is under issue".
My question is, how can something be under issue? It can either be issued or not.
Does it mean that the letter is yet to be issued?

A: This is not a common phrase; I think it's Indian English. I understand it as meaning "the letter is in the process of being issued", i.e. the decision has been taken to write that letter (a reply to the application, presumably?), and either the content is being written, or it's waiting for someone's signature, or it's in the mail.
Google Books turns up very few occurrences (most of the time, when the two words "under issue" appear next to each other, it's in unrelated constructions like "under issue 42b". Here are a few citations:

Necessary notification under FERA to give effect to the revised procedure is under issue. [India News]
  An Army instruction to this effect is under issue. [Communication from the India Ministry of Defense]
  Necessary amendment to Rule 18 (…) is under issue. [India Ministry of Finance memo]


text:
Q: Can't a Filter or Listener use spring beans? I have a listener class in web.xml like this:
<listener>
    <listener-class>com.datx.monitoring.model.MonitoringHttpSessionListener</listener-class>
</listener>

And for this class, I have defined a bean like this:
<bean id="monitoringHttpSessionListener"
    class="com.datx.monitoring.model.MonitoringHttpSessionListener" autowire="byName"/>

But this bean is not able to use other beans. Every time this class is called, it has null properties.
This class is the exact same as the other which is working fine. The only difference is, this class is used as a listener and the other is not. Why is that?

A: There is a simple reason for this: There are two beans. One was created by your web container (which uses web.xml) and the other by Spring (which uses your bean definition). The web container and Spring know nothing about each other.
What you need to do is create a normal listener which gets the application context with
WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());

This will allow you to look up beans. Now you can define a bean which the filter can modify.
Note: You will want to give this bean the request scope or there will be chaos.


text:
Q: Is it possible to use google.protobuffer to serialize data without prefixing the length of each data field? By default, unless ive done something wrong, protobuf prefixes all data fields with the length of the data that follows. for example, if i do:
class Program
{
    static void Main(string[] args)
    {
        MessagePayload msg = new MessagePayload()
        {
            Message = "hello"
        };

        var bytes = new byte[8];

        var output = new CodedOutputStream(bytes);

        output.WriteMessage(msg);

        Console.WriteLine(CryptoBytes.ToHexStringLower(bytes));

        Console.ReadLine();
    }
}

it prints out:
07120568656c6c6f

but what i want is:
0568656c6c6f

is there a way to have protobuf do this somehow, without manually removing the length fields?

A: No. As described in the encoding here https://developers.google.com/protocol-buffers/docs/encoding strings must all be prefixed with their size. "A wire type of 2 (length-delimited) means that the value is a varint encoded length followed by the specified number of bytes of data. "

A: The only byte that is removable there is the 07 - that isn't part of the regular protobuf specification, and the raw protobuf output for that message is just 120568656c6c6f. The leading 07 is an unrelated length prefix that is presumably part of CodedOutputStream, but is not part of the regular protobuf output. You can probably avoid that by not using CodedOutputStream, but just using the other available methods perhaps on msg.
The 12 here means "field number: 2, type: length-delimited". That tells me that Message quite possibly isn't the only field defined on MessagePayload, so no: you can't remove that. And even if it was the only field on MessagePayload: the protobuf specification doesn't care: every field present gets a field header.
To be honest, if all you want is to send is a string, then: don't use protobuf - just use UTF-8 to encode the string, prepend the length-prefix in whatever way you choose (protobuf uses "varint"), and you're done. However, if you want to send more complex structured data, you'll need some overheads to allow for that. That's what the 12 is here.
For the record: there are 6 "wire types" defined in protobuf, and only one of them (wire type 2) involves a length prefix. Many fields don't involve a length prefix. In your example, the only length prefix in the actual protobuf data is the 05, which is one of the bytes you said you wish to keep.


text:
Q: Using operator new on non-pod structs + Initializer list I was trying out some stuff allocating structs, which contain non-pod members, on the heap and initializing them using initializer lists. However, the compiler encountered an error on my code. This snippet reproduces it:
#include <vector>

struct A {
    int a;
};

struct B {
    int a;
    std::vector<int> b;
};

int main() {
    std::vector<int> some_vec;
    A a = {1}; // OK
    A b = A{1}; // OK
    A *c = new A{1}; // OK(leaks, NP)
    B d = {1, some_vec}; // OK
    B e = B{1, some_vec}; // OK

    B *f = new B{1, some_vec}; // Fails to compile

    B *g = new B({1, some_vec}); // OK
}

(I know that leaks, I'm aware of that, it's just a test snippet)
The line pointed out fails to compile, on GCC 4.6.3, with this error:
test.cpp: In function 'int main()':
test.cpp:19:29: error: no matching function for call to 'B::B(<brace-enclosed initializer list>)'
test.cpp:19:29: note: candidates are:
test.cpp:7:8: note: B::B()
test.cpp:7:8: note:   candidate expects 0 arguments, 2 provided
test.cpp:7:8: note: B::B(const B&)
test.cpp:7:8: note:   candidate expects 1 argument, 2 provided
test.cpp:7:8: note: B::B(B&&)
test.cpp:7:8: note:   candidate expects 1 argument, 2 provided

Apparently the compiler can't initialize my struct using the provided initializer list. The strange this is that the next line after the one that produces an error, which(at far as I can see) just copies(probably moves) a B from another that was constructed using that same initializer list, does not produce any error.
Is there anything wrong I am doing? I mean, I can live using that last line on the snippet provided, but is there any reason why I can't just create a struct using operator new and an initialization list?

A: The code should compile and work. I tested it with gcc 4.7.0, and it works fine, so the bug has been fixed it seems. If you read 8.5.4 List-initialization in the standard, they say List intialization can be used as the initializer in a new expression (5.3.4).


text:
Q: Is there a more efficient way of evaluating this limit? $$\lim_{x\to 0} \frac{\sin(x)-\arctan(x)}{x^2\ln(1+2x+x^2)}$$
This was a multiple choice question so it should not take me such a long time but the only way I see how to attack it is just L'Hôpital rule multiple times which is so inefficient as it keeps getting bigger and I'm more likely to make errors. The limit is $ \frac{1}{12} $ but I'm not sure how to show it. If there are any helpful tips on how to reduce the amount of calculation and make it simpler, it'd be appreciated.

A: HINT
${\ln(1+2x+x^2)}=2\ln(1+x)$ and $\lim_{x\to 0} \frac{\ln (x+1)} x = 1$ therefore:
$\lim_{x\to 0} \frac{\sin(x)-\arctan(x)}{x^2\ln(1+2x+x^2)} = \lim_{x\to 0} \frac{\sin(x)-\arctan(x)}{2x^2\ln(1+x)} = \lim_{x\to 0} \frac{\sin(x)-\arctan(x)}{2x^3 \frac {\ln(1+x)} x} = \lim_{x\to 0} \frac{\sin(x)-\arctan(x)}{2x^3}  \lim_{x\to 0} \frac  1 {\frac {\ln (x+1)}{x}} = \lim_{x\to 0} \frac{\sin(x)-\arctan(x)}{2x^3}$
then use L'Hospital or, even better:
$\lim_{x\to 0} \frac{\sin(x)-\arctan(x)}{2x^3} = \lim_{x\to 0} \frac{\sin(x)-x + x -\arctan(x)}{2x^3}=\lim_{x\to 0} \frac{\sin(x)-x} {2x^3} + \lim_{x\to 0} \frac{x - \arctan(x)} {2x^3}$

A: Use Taylor's formula and equivalence of functions:

*

*$\sin x-\arctan x= x-\dfrac{x^3}6+o(x^3)-\Bigl(x-\dfrac{x^3}3+o(x^3)\Bigr)=\dfrac{x^3}6+o(x^3)\sim_0\dfrac{x^3}6$,

*$\ln(1+2x+x^2)=2\ln(1+x)=2x+o(x)\sim_02x$,
so that $$\frac{\sin(x)-\arctan(x)}{x^2\ln(1+2x+x^2)}\sim_0\frac{\dfrac{x^3}6}{x^2\cdot 2x}=\frac1{12}.$$

A: If you know about the Taylor development approach, you should be aware that the first order approximation of both $\sin x$ and $\arctan x$ are $x$. As both functions are odd, there is no quadratic term, and the difference will feature a cubic term if the cubic coefficients differ. So you can expect a numerator approximated by $ax^3$.
In the denominator, $\ln(1+y)$ yields $y$, so that $\ln(1+2x+x^2)$ yields $2x+x^2$ and other terms (starting from quadratic). Together with the factor $x^2$, the approximation is $2x^3$.
Hence all you need are the third order Taylor coefficients, which you might know by heart to be $-1/3!$ and $-1/3$, giving the limit
$$\frac{-\frac16+\frac13}2.$$

If you don't know the coefficients, derive three times
$$\sin x\to\cos x\to-\sin x\to-\cos x,$$ giving the Taylor coefficient $-1/3!$
For the arc tangent,
$$\arctan x\to\frac1{1+x^2}.$$ You can continue to evaluate the derivatives but it is easier to use the geometric series summation formula to write
$$\frac1{1+x^2}=1-x^2+\cdots$$ which integrates as
$$\arctan x=x-\frac{x^3}3+\cdots$$

A: You could replace
$\ln(1+2x+x^2)=2\ln(1+x)\sim2x$.

A: We can proceed as follows
\begin{align}
L &= \lim_{x \to 0}\frac{\sin x - \arctan x}{x^{2}\log(1 + 2x + x^{2})}\notag\\
&= \lim_{x \to 0}\frac{\sin x - \arctan x}{x^{2}\log(1 + x)^{2}}\notag\\
&= \frac{1}{2}\lim_{x \to 0}\frac{\sin x - \arctan x}{x^{2}\log(1 + x)}\notag\\
&= \frac{1}{2}\lim_{x \to 0}\dfrac{\sin x - \arctan x}{x^{3}\cdot\dfrac{\log(1 + x)}{x}}\notag\\
&= \frac{1}{2}\lim_{x \to 0}\frac{\sin x - \arctan x}{x^{3}}\notag
\end{align}
Now you can either use L'Hospital's Rule or Taylor series approach (this one being easier) and easily get the answer as $1/12$.
Note that it is always a good idea to simplify the expression (whose limit is to be evaluated) via the use of identities (related to the functions involved) and standard limits like $\lim\limits_{x \to 0}\dfrac{\log(1 + x)}{x} = 1$ or $\lim\limits_{x \to 0}\dfrac{\sin x}{x} = 1$ before applying the technique of L'Hospital's Rule or Taylor series.


text:
Q: object not being displayed in pygame I was using the pygame engine and the background loads but not the image of one. I tried debugging using a tutorial and it didn't work. Can somebody help?
I first tried using the flip command and that didn't work. I changed the variables names and that didn't work.
code:

# Importing stuff
import pygame
import sys
import time
import os
from pygame.locals import *

# Initialize
x = 500
y = 500
pygame.init()
pygame.font.init()
size = pygame.display.set_mode((x,y))
pygame.display.set_caption("GR Sticks VERA")

# Define
bg = pygame.image.load("assets/bg.png")
bg = pygame.transform.scale(bg,(500,500))
i1 = pygame.image.load("assets/1.png")
i2 = pygame.image.load("assets/2.png")
i3 = pygame.image.load("assets/3.png")
i4 = pygame.image.load("assets/4.png")
fvc = pygame.image.load("assets/favicon.png")
clock = pygame.time.Clock()
pygame.display.set_icon(fvc)
loop=True
start=True

# Functions
def one(ox, oy):
            size.blit(i1, (ox, oy))
ox = (500 * 0.45)
oy = (500 * 0.8)

# Loop
while loop == True:
            size.blit(bg, (0, 0))
            if start == True:
                     one(ox,oy)
            else:
                        pygame.quit()
            for event in pygame.event.get():
                        if event.type == QUIT:
                                    pygame.quit()
                                    sys.exit()
            pygame.display.flip()
            pygame.display.update()
            clock.tick(60)
if loop == False:
            pygame.quit()
            sys.exit()


text:
Q: How to optimize this Fortran subroutine with many loops? I am dealing with subroutine that is very inefficient when the array size becomes large, for example, NN=1000, KK=200, MM = 200. But, I can not come up with ideas to optimize it.
program main

  implicit none

  integer :: NN, KK, MM
  integer, allocatable, dimension(:,:) :: id
  complex*16, allocatable, dimension(:) :: phase
  complex*16 :: phase_base(3)
  real*8, allocatable, dimension(:,:) :: wave_base

  complex*16, allocatable, dimension(:,:) :: wave
  integer :: i, j, k, n

  NN = 1000
  KK = 200
  MM = 200

  allocate(id(MM,3))
  allocate(phase(KK))
  allocate(wave_base(KK, NN*(NN+1)/2 ))
  allocate(wave(NN, NN))

  id(:,:) = 2

  phase_base(:) = (1.0d0,1.0d0)

  wave_base(:,:) = 1.0d0

  phase(:) = (1.0d0,1.0d0)

  call  noise_wave(NN, KK, MM, id, phase, phase_base, wave_base, wave)

  deallocate(id)
  deallocate(phase)
  deallocate(wave_base)
  deallocate(wave)

end program main

subroutine noise_wave(NN, KK, MM, id, phase_1, phase_base, wave_base, wave)
  implicit none

  integer, intent(in) :: NN, KK, MM
  integer, intent(in), dimension(MM, 3) :: id
  complex*16, intent(in) :: phase_1(KK)
  complex*16, intent(in) :: phase_base(3)
  real*8,  intent(in) :: wave_base(KK, NN*(NN+1)/2 )

  complex*16, intent(out) :: wave(NN, NN)

  integer :: i, j, k, p, n
  integer :: x, y, z
  real :: start, finish
  complex*16 :: phase_2, phase_2_conjg

  do p = 1, MM

    x = id(p, 1)
    y = id(p, 2)
    z = id(p, 3)

    phase_2 = (phase_base(1) ** x) * (phase_base(2) ** y) * (phase_base(3) ** z)

    phase_2_conjg = conjg(phase_2)

    n = 0
    do j = 1, NN
      do i = 1, j   ! upper triangle

        n = n + 1

        do k = 1, KK

          wave(i,j) = wave(i,j) + wave_base(k,n) * phase_1(k) * phase_2_conjg

        enddo

        wave(j,i) = conjg(wave(i,j) )

      enddo
    enddo
  enddo

end subroutin

Could someone give me some hint? (I have fulfill the suggested optimizations. Also, following Ian's suggestion, I have added a small test. Thus you can test it directly.)

A: You might get a measurable speedup if you change your loop nest to
  do p = 1, MM

     x = id(p, 1)
     y = id(p, 2)
     z = id(p, 3)
     phase = (phase_base(1) ** x) * (phase_base(2) ** y) * (phase_base(3) ** z)
     conjg_phase = conjg(phase)  ! new variable, calculate here, use below

     n = 0
     do j = 1, NN
        do i = 1, j
           n = n + 1
           do k = 1, KK
              wave(i,j) = wave(i,j) + wave_base(k,n) * conjg_phase
           enddo
        enddo
        wave(j,i) = conjg(wave(i,j) )
     enddo
  enddo

(and it might still be correct if I've understood the code !).  Even little computations like the ones I've lifted out of the bottom of the loop nest are a drag if repeated often enough.  And the execution speed might benefit from moving those values in and out of cache less often too.
It might be worth (a little) swapping the dimensions of id, then reading id(1:3,p) is likely to be more cache-friendly than the current version.
And if the execution speed is still not to your taste, time to learn OpenMP (if you don't know it already).

A: Here are my solution following the nice ideas above. There is still some room for efficiency gain before OpenMP. For example, the first k loop in the subroutine can be eliminated by sum function.
program main

  implicit none

  integer :: NN, KK, MM
  integer, allocatable, dimension(:,:) :: id
  complex*16, allocatable, dimension(:) :: phase
  complex*16 :: phase_base(3)
  real*8, allocatable, dimension(:,:) :: wave_base

  complex*16, allocatable, dimension(:,:) :: wave
  integer :: i, j, k, n

  NN = 1000
  KK = 200
  MM = 200

  allocate(id(MM,3))
  allocate(phase(KK))
  allocate(wave_base(KK, NN*(NN+1)/2 ))
  allocate(wave(NN, NN))

  id(:,:) = 2

  phase_base(:) = (1.0d0,1.0d0)

  wave_base(:,:) = 1.0d0

  phase(:) = (1.0d0,1.0d0)

  call  noise_wave(NN, KK, MM, id, phase, phase_base, wave_base, wave)

  deallocate(id)
  deallocate(phase)
  deallocate(wave_base)
  deallocate(wave)

end program main

subroutine noise_wave(NN, KK, MM, id, phase_1, phase_base, wave_base, wave)
  implicit none

  integer, intent(in) :: NN, KK, MM
  integer, intent(in), dimension(MM, 3) :: id
  complex*16, intent(in) :: phase_1(KK)
  complex*16, intent(in) :: phase_base(3)
  real*8,     intent(in) :: wave_base(KK, NN*(NN+1)/2 )
  complex*16, intent(out):: wave(NN, NN)

  integer :: i, j, k, p, n
  integer :: x, y, z
  real :: start, finish
  complex*16 :: phase_2, phase_2_conjg
  complex*16 :: wave_tmp(NN*(NN+1)/2)
  complex*16 :: wave_tmp_2(NN*(NN+1)/2)

  do k = 1, KK

    wave_tmp(:) = wave_tmp(:) + wave_base(k,:) * phase_1(k)

  enddo

  do p = 1, MM
    phase_2 = product(phase_base(:)**id(p,:) )
    phase_2_conjg = conjg(phase_2)

    wave_tmp2(:) = wave_tmp2(:) + wave_tmp(n) * phase_2_conjg
  enddo

  n = 0
  do j = 1, NN
    do i = 1, j
        n = n + 1
        wave(i,j) = wave_tmp2(n)
        wave(j,i) = conjg(wave_tmp2(n) )
    enddo
  enddo

end subroutine


text:
Q: Rotational dynamics about a point or an axis? In several books and sites, it is written that torque is calculated about an axis, and angular momentum is calculated about a point. In MIT's Angular momentum lecture pdf, Angular momentum has been calculated about a point and then this has been used to calculate the torque about that point.
In this page, it has been explicitly mentioned that angular momentum is defined about a point in an inertial frame.
On some other websites, it was mentioned that torque is defined about a point and each point determines a unique axis in itself, about which the torque is the same for every point on that axis. Is this true? For central axes?
Which is true? Is torque calculated about a point or an axis? Is angular momentum calculated about a point or an axis? If torque and angular momentum are not defined in the same sense, then how can they be linked to Newton's equations (maybe due to the axial property of moment of inertia?)?

A: The discussion is mostly semantic. They are both calculated relative to a point, in the case of the torque the point has the additional meaning that if you put an axle trough the point, the  object will start to rotatte around it if the net torque is not zero. It happens also that the torque will be the same if you chose any other point along the axis (axel).

A: Well for a rotation the reference taken is the axis not a point as for any system of particles, given a point, it can be rotated in many different ways so to define a unique rotation you choose an  axis, and that applies to both angular momentum and torque. But let's say you want to calculate the angular momentum of the earth as it is rotating and simultaneously revolving, so both motions would contribute to angular momentum and for the revolution part the angular momentum would be defined about a point but the one associated with rotation would be defined about the axis.


text:
Q: Catalina configuration test (catalina.sh configtest) I have a feeling that there might be something wrong with my Tomcat installation, so I run the following command for sanity check.
$TOMCAT_HOME/bin/catalina.sh configtest

What does this output mean, or how to go about fixing? Thinking of re-installing Tomcat. OS is Ubuntu.
Using CATALINA_BASE:   /usr/share/tomcat7
Using CATALINA_HOME:   /usr/share/tomcat7
Using CATALINA_TMPDIR: /usr/share/tomcat7/temp
Using JRE_HOME:        /usr
Using CLASSPATH:       /usr/share/tomcat7/bin/bootstrap.jar:/usr/share/tomcat7/bin/tomcat-juli.jar

Jul 01, 2016 12:28:41 AM org.apache.catalina.startup.ClassLoaderFactory validateFile
WARNING: Problem with directory [/usr/share/tomcat7/common/classes], exists: [false], isDirectory: [false], canRead: [false]

Jul 01, 2016 12:28:41 AM org.apache.catalina.startup.ClassLoaderFactory validateFile
WARNING: Problem with directory [/usr/share/tomcat7/common], exists: [false], isDirectory: [false], canRead: [false]

Jul 01, 2016 12:28:41 AM org.apache.catalina.startup.ClassLoaderFactory validateFile
WARNING: Problem with directory [/usr/share/tomcat7/server/classes], exists: [false], isDirectory: [false], canRead: [false]

Jul 01, 2016 12:28:41 AM org.apache.catalina.startup.ClassLoaderFactory validateFile
WARNING: Problem with directory [/usr/share/tomcat7/server], exists: [false], isDirectory: [false], canRead: [false]

Jul 01, 2016 12:28:41 AM org.apache.catalina.startup.ClassLoaderFactory validateFile
WARNING: Problem with directory [/usr/share/tomcat7/shared/classes], exists: [false], isDirectory: [false], canRead: [false]

Jul 01, 2016 12:28:41 AM org.apache.catalina.startup.ClassLoaderFactory validateFile
WARNING: Problem with directory [/usr/share/tomcat7/shared], exists: [false], isDirectory: [false], canRead: [false]

Jul 01, 2016 12:28:41 AM org.apache.catalina.startup.Catalina initDirs
SEVERE: Cannot find specified temporary folder at /usr/share/tomcat7/temp

Jul 01, 2016 12:28:41 AM org.apache.catalina.startup.Catalina load
WARNING: Unable to load server configuration from [/usr/share/tomcat7/conf/server.xml]

Configuration error detected!

A: I had the same problem. I was running Tomcat 7 on Ubuntu 14.04. The problem is in the file catalina.properties. In my computer it is located in /var/lib/tomcat7/conf/.
This file has a lot of paths with the variables ${catalina.base} and ${catalina.home}. This variables are set in the file catalina.sh. In my computer it is located in /usr/share/tomcat7/bin/.
For some reason the Tomcat 7 is using the ${catalina.home} wich is /usr/share/tomcat7/ instead of ${catalina.base} wich is /var/lib/tomcat7/.
To correct this you need to replace the texts below:

*

*${catalina.home}/common/classes => ${catalina.base}/common/classes

*${catalina.home}/common/.jar => ${catalina.base}/common/.jar

*${catalina.home}/server/classes => ${catalina.base}/server/classes

*${catalina.home}/server/.jar => ${catalina.base}/server/.jar

*${catalina.home}/shared/classes => ${catalina.base}/shared/classes

*${catalina.home}/shared/.jar => ${catalina.base}/shared/.jar

After the replacements, run configtest.sh again to verify.

A: you can modify or add setenv.sh file in bin folder of your tomcat as below
export JAVA_HOME="[your java home]"
export CATALINA_BASE="[your tomcat home]"
export CATALINA_HOME=" [ your tomcat home]"
export CATALINA_PID="$CATALINA_BASE/logs/tomcat.pid"

This fix work for me.

A: I ran into this after upgrading an Ubuntu 16.04 box to 18.04. As part of the upgrade I merged the Tomcat 8 settings to an existing Tomcat 7 file and forgot to remove these two lines:
<!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
<Listener className="org.apache.catalina.core.JasperListener" />

Only the last one was actually causing issues, but if you yank it you will probably want to remove the related comment too.
After making that change, I was able to start Tomcat 8 on the newly upgraded box without issue.


text:
Q: MySQL Query, (access mainquery from subquery) I have a problem that I need a WHERE clause in a subquery that depends on the results of the main Query, otherwise my results would be wrong and the query takes too long / is not executeable.
The circumstances that I need this query to create a view which I need for a search server support the problem that I cannot split this into two queries, nor process it with a script dynamically.
The problem occurs with the following query:
    SELECT `s`.`id` AS `seminar_id`, (SUM( `sub`.`seminar_rate` ) / COUNT( `sub`.`seminar_id` )) AS `total_rate`
    FROM
    (
        SELECT (SUM( value ) / COUNT( * )) AS `seminar_rate` , `r`.`seminar_id`
        FROM `rating` r
        INNER JOIN `rating_item` ri ON `r`.`id` = `ri`.`rating_id`
        WHERE `r`.`seminar_id` = `s`.`id`/* <- Here is my problem, this is inacessible */
        GROUP BY `r`.`seminar_id`
    ) AS sub,
    `seminar` s
    INNER JOIN `date` d
    ON `s`.`id` = `d`.`seminar_id`
    INNER JOIN `date_unit` du
    ON `d`.`id` = `du`.`date_id`
    LEFT JOIN `seminar_subject` su
    ON `s`.`id` = `su`.`seminar_id`
    LEFT JOIN `subject` suj
    ON `su`.`subject_id` = `suj`.`id`
    INNER JOIN `user` u
    ON `s`.`user_id` = `u`.`id`
    INNER JOIN `company` c
    ON `u`.`company_id` = `c`.`id`
    GROUP BY `du`.`date_id`, `sub`.`seminar_id`

This query should calculate a total rate out of ratings for each Seminar.
However my ratings are stored in my "rating" table and should be processed live.
(Sidenote: If you wonder about all the joins: This query has alooot more SELECT'ed fields, I just removed them because they are not nesessary to solve the problem and to make the query look less complicated [I know it still is >.>]...)
The reason is that I want this results to be sortable by my search engine later depending
on the users sort parameters, thatswhy I need it inside this query.
The problem itself is pretty obvious:
ERROR 1054 (42S22): Unknown column 's.id' in 'where clause'
The subselect doesnt know about the results of the main query, is there a solution to bypass this?
Could someone give me a hint to get this working?
Thanks in advance.

A: Using your subquery in the JOIN you can eliminate the WHERE clause and achieve nearly the same result. Here is your modified query. Hope this solves your problem.
SELECT `s`.`id` AS `seminar_id`, (SUM( `sub`.`seminar_rate` ) / COUNT( `sub`.`seminar_id` )) AS `total_rate`
FROM `seminar` s
INNER JOIN
(
    SELECT (SUM( value ) / COUNT( * )) AS `seminar_rate` , `r`.`seminar_id`
    FROM `rating` r
    INNER JOIN `rating_item` ri ON `r`.`id` = `ri`.`rating_id`
    /*WHERE `r`.`seminar_id` = `s`.`id` <- Here is my problem, this is inacessible */
    GROUP BY `r`.`seminar_id`
) AS sub ON s.id = sub.`seminar_id`
INNER JOIN `date` d
ON `s`.`id` = `d`.`seminar_id`
INNER JOIN `date_unit` du
ON `d`.`id` = `du`.`date_id`
LEFT JOIN `seminar_subject` su
ON `s`.`id` = `su`.`seminar_id`
LEFT JOIN `subject` suj
ON `su`.`subject_id` = `suj`.`id`
INNER JOIN `user` u
ON `s`.`user_id` = `u`.`id`
INNER JOIN `company` c
ON `u`.`company_id` = `c`.`id`
GROUP BY `du`.`date_id`, `sub`.`seminar_id`


text:
Q: Differences between between concepts related to Gödel's Incompleteness theorems: self-referencing, diagonalization and fixed point theorem? I am studying the proof of Gödel's first Incompleteness theorem at the moment and I don't understand the differences between self-referencing, diagonalization and fixed point related to Gödel's proof.
In my opinion, they all mean taking the Gödel number of a formula as an argument into the formula itself.
Can someone please explain me the differences?
Thanks in advance.

A: It would probably help if you provide instances of each. But if you're just talking about their use in Gödel incompleteness theorems, then I suppose they all mean different aspects of the same thing. Application of the fixed point lemma is often referred to as diagonalization (of a given formula), and then that formula is said to be referring to itself.
I recommend:
Raymond Smullyan, 1994. Diagonalization and Self-Reference. Oxford Univ. Press.
Raymond Smullyan, 1991. Gödel's Incompleteness Theorems. Oxford Univ. Press.


text:
Q: java inputstream not reading leading hex bytes I've got a Telnet Client defined as:
    TelnetClient telnet = new TelnetClient();
    telnet.connect(server, port);

I then get the inputstream:
    InputStream in = telnet.getInputStream();

and then try to read stuff on it, in a loop:
    while (true) {
    int TEST = in.read();
    }

everything seems to go fine as I receive the "text" part of the input... but I'm missing the (very important for me!) leading bytes.
Here is a snoop of what I see going on the port:
    64: a88f ffff 3034 3131 3032 3030 3030 3030    ¨...041102000000
    80: 3030 322e 3031 3131 2e36 2e34 2020 3135    002.0111.6.4  15
    96: 2e39 2e33 2020 3030 3132 30                .9.3  00120

notice the "ffff": that's the leading part I need (everything before is garbage: part of the TCP communication).
However, when printing my "TEST" variable, I only see the "041102...etc".
I've tried using BOMInputStream too, but I can't get it either.
=> would you have any idea on how I can receive those ?
Thanks for your help !

A: The input stream provided by a TelnetClient instance is only going to provide the data characters.  Telenet protocol signalling stuff will have been filtered out by the TelnetClient code.
If you want to get hold of the signalling information, options, etcetera, you will need to use other methods in the TelnetClient API.  There are a variety of approaches you could possibly try.  For example, you could register an option handler, or a notification handler, or you could register a "spy stream".

A: You should be just using Socket instead of TelnetClient if you really want to see all of the data.


text:
Q: Default input and output buffering for fopen'd files? So a FILE stream can have both input and output buffers. You can adjust the output stream using setvbuf (I am unaware of any method to play with the input buffer size and behavior).
Also, by default the buffer is BUFSIZ (not sure if this is a POSIX or C thing). It is very clear what this means for stdin/stdout/stderr, but what are the defaults for newly opened files? Are they buffered for both input and output? Or perhaps just one?
If it is buffered, does output default to block or line mode?
EDIT: I've done some tests to see how Jonathan Leffler's answer affected real world programs. It seems that if you do a read then a write. The write will cause the unused portion of the input buffer to dropped entirely. In fact, the there will be some seeks that are done to keep things at the right file offsets. I used this simple test program:
/* input file contains "ABCDEFGHIJKLMNOPQRSTUVWXYZ" */
#include <stdio.h>
#include <stdlib.h>

int main() {

    FILE *f = fopen("test.txt", "r+b");
    char ch;
    fread(&ch, 1, 1, f);
    fwrite("test", 4, 1, f);
    fclose(f);
    return 0;
}

resulted in the following system calls:
read(3, "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n", 4096) = 27 // attempt to read 4096 chars, got 27
lseek(3, -26, SEEK_CUR)                 = 1        // at this point, I've done my write already, so forget the 26 chars I never asked for and seek to where I should be if we really just read one character...
write(3, "test", 4)                     = 4        // and write my test
close(3)                                = 0

While these are clearly implementation details I found them to be very interesting as far as how the standard library could be implemented. Thanks Jonathan for your insightful answer.

A: A single file stream has a single buffer.  If the file is used for both input and output, then you have to ensure that you do appropriate operations (fseek() or equivalents) between the read and write (or write and read) operations.
The buffering behaviour of the standard channels is platform dependent.
Typically, stdout is line buffered when the output goes to the terminal.  However, if stdout is going to a file or pipe rather than to a terminal, it most usually switches to full buffering.
Typically, stderr is either line buffered or unbuffered, to ensure that error messages get seen (for example, even if the program is about to crash).
Typically, stdin is line buffered; this means you get a chance to edit your input (backspacing over errors, etc).  You would seldom adjust this.  Again, if the input is coming from a file (or pipe), the behaviour might be different.
Newly opened files will generally be fully buffered.  A particular implementation might change that to line buffering if the device is a terminal.
Your premise - that there are two buffers - is incorrect.

Section 7.19.3 of C99, it says:

At program startup, three text streams are predefined and need not be opened explicitly
  — standard input (for reading conventional input), standard output (for writing
  conventional output), and standard error (for writing diagnostic output). As initially
  opened, the standard error stream is not fully buffered; the standard input and standard
  output streams are fully buffered if and only if the stream can be determined not to refer
  to an interactive device.

So, as originally stated, stderr is either unbuffered or line buffered (it is not fully buffered).


text:
Q: how do i know if it gives pass true back Does JavaScript expression assert("1" === 1) gives PASS(TRUE) back ?

A: No, '===' means identical. "1" and 1 aren't identical because "1" is a string and 1 is a integer. Using '==' would return true.

A: No it would return false.
The reason for this is because === is an equality check without coercion therefore the types are not converted. This means, effectively what you are comparing is a String to an Number which obviously aren't the same thing.
See Does it matter which equals operator (== vs ===) I use in JavaScript comparisons? for more info on the use of == vs ===.

A: String "1" is not === to integer 1, so you're evaluating assert(false) which returns fail.
("1"===1) = false
assert(false) => fail


text:
Q: PHP Simple HTML DOM Parser - Parsing php'd data I have a php file called items.php which has table with tr and td. The contents of the table are dynamically created like this:

Item Name	Price

<?php
$sqlquery="select * from items_data";
$result=mysqli_query($connection,$sqlquery);
if(mysqli_num_rows($result)>0){
    while($row = mysqli_fetch_assoc($result)) {
    ?>
<?php echo $row['item_name'];?>
        <input type="checkbox" name="items[]" value="<?php echo $row['item_name'];?>" <?php echo ($row['availability']=='Yes' ? "checked":"");?>/>

<?php       }
}
?>

Now I use a Simple HTML DOM Parser.
<?php
require "simple_html_dom.php";
$html = file_get_html('items.php');
$rows = $html->find('td');
foreach($rows as $row) {
   echo $row->plaintext;
}
?>

The result of this is the static data which is the first row of the table:
Item_name and Item_Price.
The Php data isnt getting parsed.
My question is, How to parse the php data from html file ?


text:
Q: iOS using SQLITE database. SQLITE_ROW returning 100 even with a limit set Using SQLite Database Browser, I can send a query:
"SELECT latitude, longitude FROM locations WHERE businessid = 1453 LIMIT 3;"
and I get three rows of data. Well for some reason in my app's code the SQLITE_ROW value is 100 determined by assigning it to an int and logging. So this makes some sort of infinite loop and the app freezes indefinitely. I would really like to know why this code works for other areas of my app where I'm reading in other tables but not here. Here is the code.
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{

    for (int i = 0; i < appDelegate.userList.count; i++) // for each location in the user list, add to surrounding data
    {
        RMLocationItem *temp = [appDelegate.userList objectAtIndex:i];
        NSString *sqlStatement1 = [[NSString alloc]init];
        sqlStatement1 = [NSString stringWithFormat:@"SELECT latitude, longitude FROM locations WHERE businessid = %d limit 5;", temp.businessId];
        const char *sqlStatement = [sqlStatement1  UTF8String];
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
         {
            //sqlite3_bind_int(compiledStatement, 1, temp.businessId);
            //int sr = SQLITE_ROW;
            //NSString* myNewString = [NSString stringWithFormat:@"%d", sr];
            //NSLog(myNewString);
            while( sqlite3_step(compiledStatement) == SQLITE_ROW)
            {

                double latitude = (double) sqlite3_column_double(compiledStatement, 0);
                double longitude = (double) sqlite3_column_double(compiledStatement, 1);

                sqlite3_reset(compiledStatement);

                RMLocationItem *newLocation = [[RMLocationItem alloc]initWithName: temp.nameOfPlace distance:0 Id:temp.businessId longitude:longitude latitude:latitude address:NULL city:NULL];

                [appDelegate.surroundingRestaurants addObject:newLocation];

            }
        }
        else  NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));

        // Release the compiled statement from memory
        sqlite3_finalize(compiledStatement);

    }
    sqlite3_close(database);

EDIT: Solved thank you, just like @rmaddy said, I took sqlite3_reset(compiledStatement); out and moved finalize up to just after the while loop.


text:
Q: React Select with Async - Failing to load options I am attempting to create a react-select async input field that provides model numbers based on user input. My API is working, as is the Fetch, which is producing the exact 'options' object required to populate dropdown (I checked both the network requests and the console).
The problem is that when I start typing, the dropdown shows that it is loading, but no options are added to it.

Here is an example output from the Fetch call:
{options: [{value: "WA501006", label: "WA501006"}]}.
This is my code:
getModelsAPI = (input) => {

        if (!input) {
            return Promise.resolve({ options: [] });
        }

        const url = `(...)?cmd=item_codes_json&term=${input}`;

        fetch(url, {credentials: 'include'})
            .then((response) => {
                return response.json();
            })
            .then((json) => {
                const formatted = json.map((l) => {
                    return Object.assign({}, {
                        value: l.value,
                        label: l.label
                    });
                })
                return { options: formatted }
            })
    }

onChange = (value) => {
    this.setState({
        value: value
    })
}

<Select.Async
  value={this.state.value}
  loadOptions={this.getModelsAPI}
  placeholder="Enter Model"
  onChange={this.onChange}
/>

A: I think you need to return from the getModelsAPI function:
getModelsAPI = (input) => {

        if (!input) {
            return Promise.resolve({ options: [] });
        }

        const url = `(...)?cmd=item_codes_json&term=${input}`;

        return fetch(url, {credentials: 'include'})
            .then((response) => {
                return response.json();
            })
            .then((json) => {
                const formatted = json.map((l) => {
                    return Object.assign({}, {
                        value: l.value,
                        label: l.label
                    });
                })
                return { options: formatted }
            })
    }


text:
Q: Jupyter notebook does not work from a specific conda virtual environment In order to use libraries installed in a specific conda virtual environment I would first activate it and the call jupyter from it:
conda activate my_env
jupyter notebook --notebook-dir ~/Projects/my_dir/

However, after cloning and installing a new library
cd companys_library
pip install -e .

Jupyter became unusable:
 - files and directories in my_dir do not appear.
 - creating new folders via the interface (new->folder) does not work (no error message, just not effect).
 - Python isn't even specified in the types of notebooks that can be created via the interface (new->notebooks: it's empty)
Jupyter functionality in the other conda environments is unaffected.
How can I restore the Jupyter functionality in this environment?


text:
Q: Menu closes when clicking outside it but only opens once I've created a collapsible menu and I want it to be closed when user clicks on body. I've coded it but it just work for once in every refresh. I mean it opens when I click menu button and nicely closed when I click on body but if I want to reopen the menu, button doesn't do anything.
I tried addclass instead of toggleclass but it doesn't work. even i tried toggleClass instead of removeClass but something worse had happened, every time I click on BODY, menu is going to open and close.
What's going wrong?

$(window).click(function() {
  "use strict";
  $("HTML, body").click(function() {
    $(".menu").removeClass("menu_slide");
  });
});

$(document).ready(function() {
  "use strict";
  $(".menu_button").click(function() {
    $(".menu").toggleClass("menu_slide");
  });
});
.menu_button {
  position: fixed;
  cursor: pointer;
  color: #727272;
  /*margin-top: -10vw;*/
  margin-left: 3vw;
  margin-top: 3vw;
  text-shadow: 2px 1.5px 2px #0C0C0C;
  z-index: 200;
}

.slash {
  font-family: 'Montserrat-Medium';
  font-size: 4vw;
  letter-spacing: 0.5vw;
  text-shadow: 2px 1.5px 2px #0C0C0C;
  z-index: 200;
  -webkit-transition: 0.3s ease-out;
  -moz-transition: 0.3s ease-out;
  -o-transition: 0.3s ease-out;
  transition: 0.3s ease-out;
}

.menu {
  width: 50vw;
  height: 100vh;
  background-color: #D1D1D1;
  z-index: 10;
  position: fixed;
  left: -50vw;
  top: 0vh;
  -moz-transition: 0.8s ease-in-out;
  -o-transition: 0.8s ease-in-out;
  -webkit-transition: 0.8s ease-in-out;
  transition: 0.8s ease-in-out;
}

.menu_slide {
  left: 0vw;
  -moz-transition: 0.8s ease-in-out;
  -o-transition: 0.8s ease-in-out;
  -webkit-transition: 0.8s ease-in-out;
  transition: 0.8s ease-in-out;
}

.menu ul {
  position: absolute;
  left: 20vw;
  top: 18vw;
}

.menu ul li {
  font-family: 'Montserrat-Light';
  font-size: 1.5vw;
  line-height: 2vw;
  letter-spacing: 0.3vw;
  color: #1C1C1C;
  cursor: pointer;
}

///

About /

CV /

Photos /

Videos /

Contact /

A: The issue is because the clicks on the .menu element are propagating up to the body where the class you just added gets immediately removed. Your nested event handler within window.click is doing a similar job, which is why nested event handler should generally be avoided.
To fix this you need to add a stopPropagation() call to a parent element of the menu. You should also only attach the first click handler, which hides the menu, directly on the document. Try this:

$(document).click(function() {
  $(".menu").removeClass("menu_slide");
});

$(document).ready(function() {
  $(".menu_button").click(function() {
    $(".menu").toggleClass("menu_slide");
  });

  $('.menu-container').on('click', function(e) {
    e.stopPropagation();
  });
});
.menu_button {
  position: fixed;
  cursor: pointer;
  color: #727272;
  /*margin-top: -10vw;*/
  margin-left: 3vw;
  margin-top: 3vw;
  text-shadow: 2px 1.5px 2px #0C0C0C;
  z-index: 200;
}

.slash {
  font-family: 'Montserrat-Medium';
  font-size: 4vw;
  letter-spacing: 0.5vw;
  text-shadow: 2px 1.5px 2px #0C0C0C;
  z-index: 200;
  -webkit-transition: 0.3s ease-out;
  -moz-transition: 0.3s ease-out;
  -o-transition: 0.3s ease-out;
  transition: 0.3s ease-out;
}

.menu {
  width: 50vw;
  height: 100vh;
  background-color: #D1D1D1;
  z-index: 10;
  position: fixed;
  left: -50vw;
  top: 0vh;
  -moz-transition: 0.8s ease-in-out;
  -o-transition: 0.8s ease-in-out;
  -webkit-transition: 0.8s ease-in-out;
  transition: 0.8s ease-in-out;
}

.menu_slide {
  left: 0vw;
  -moz-transition: 0.8s ease-in-out;
  -o-transition: 0.8s ease-in-out;
  -webkit-transition: 0.8s ease-in-out;
  transition: 0.8s ease-in-out;
}

.menu ul {
  position: absolute;
  left: 20vw;
  top: 18vw;
}

.menu ul li {
  font-family: 'Montserrat-Light';
  font-size: 1.5vw;
  line-height: 2vw;
  letter-spacing: 0.3vw;
  color: #1C1C1C;
  cursor: pointer;
}

///

About /

CV /

Photos /

Videos /

Contact /


text:
Q: Adding Boost to CMake project? Background
I'm a complete newb with C++ and I've been running into one headache after another, so forgive me if this is incredibly simple and I'm just that dumb...
I have a project that should ultimately compile and run in Linux. Unfortunately after lots of issues with my C++ development environemnt (still unresolved), I gave up on trying to develop in Linux and moved to Windows Visual Studio 2017. My hope was to get my code working in Windows and then, since C++ is supposedly a portable language, it should just work in Linux with minimal changes.
For a day or so Visual Studio seemed to be working. I could write code, hit "compile", and like magic it would run. I threw together a few classes to construct a directed acyclic graph, used the standard library for a hash table, and then I tried to create a socket...
Windows and Linux use different libraries for sockets (<sys/socket.h> vs <winsock.h>) so I needed some way to abstract the differences, and I preferred a well-established standard. Googling around I found the Boost library that seemed to fit my needs... That's when everything went to hell.
My project setup
Because this project will be developed across a variety of platforms and IDEs (some people use Windows + Visual Studio, some people use Mac + Eclipse, and others use Linux + VIM) I opted to make it a CMake project. After several hours of reading and learning and research it seems like CMake should give me what I want (convenient and reproducible cross-platform builds with little or no dependency issues)

My source code (directly from the Boost Getting Started on Windows guide) is as follows:
CMakeProject2.cpp
#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
    using namespace boost::lambda;
    typedef std::istream_iterator<int> in;

    std::for_each(
        in(std::cin), in(), std::cout << (_1 * 3) << " ");
}

Per the Boost Getting Started on Windows guide, I downloaded Boost from here:
https://dl.bintray.com/boostorg/release/1.67.0/source/boost_1_67_0.zip
(interestingly, the Getting Started guide is titled "Boost Getting Started on Windows - 1.69.0", yet it linked to Boost versions 1.67.0)
After downloading and extracting the ZIP file, I had a whole mess of files - but no idea where to put them:

Attempts to Get It Working So Far
I tried to add the Boost library to my project, but none of the expected menu options were available:

Although I couldn't find a single page that warns you of this gotcha, apparently CMake projects don't have the elusive "Properties" window - and instead third party libraries must somehow be included via the CMakeLists.txt file
For starters, I copied the entire 540 MB contents of the Boost ZIP file to within my project under the folder name "Boost":

I then tried a series of different CMakeList.txt commands:
Per How do you add Boost libraries in CMakeLists.txt?:
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost REQUIRED COMPONENTS lambda)

if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})
    add_executable(CMakeProject2 "CMakeProject2.cpp" "CMakeProject2.h")
    target_link_libraries(CMakeProject2 ${Boost_LIBRARIES})
endif()

Per https://www.selectiveintellect.net/blog/2016/7/29/using-cmake-to-add-third-party-libraries-to-your-project-1:
include("Boost")
add_subdirectory("Boost")
add_subdirectory("boost")
add_subdirectory("Boost/boost")
add_subdirectory("Boost/boost/lambda")

target_link_libraries(boost)
target_link_libraries(Boost)

Per https://cmake.org/pipermail/cmake/2009-November/033249.html:
SET (Boost_FIND_REQUIRED TRUE)
SET (Boost_FIND_QUIETLY TRUE)
SET (Boost_DEBUG FALSE)
set (Boost_USE_MULTITHREADED TRUE)
set (Boost_USE_STATIC_LIBS TRUE)
SET (Boost_ADDITIONAL_VERSIONS "1.67" "1.67.0")

FIND_PACKAGE(Boost COMPONENTS  lambda)
INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS})
LINK_DIRECTORIES(${Boost_LIBRARY_DIRS})

I tried several other incantations (not being familiar with C++ or CMake as a tool) and either received errors from CMakeLists.txt, or from CMakeProject2.cpp about cannot open source file "boost/lambda/lambda.hpp". In fact, with regards to those "CMakeLists.txt" errors, after adding enough lines to my file I started to crash Visual Studio regularly. Note that I have an 8th generation i7, 32 gigabytes of RAM, and an M.2 NVMe hard drive -- so I was rather impressed that a few lines in a text file pissed off Microsoft enough to lock up my computer for 10 minutes at a time.
Failing all of that, I tried copying the files I needed directly into my project:

Now, again, I'm new to C/C++ development and everything that can go wrong has gone wrong. So far I've spent almost two weeks and barely managed to compile a single "Hello, World" app across two computers, three IDEs, and four compilers. I've yet to have any success including a third party library, from anywhere, of any popularity level or simplicity level, and actually compile a functioning program that references the library. So believe me when I say: I don't know the difference between a "header-only library" and... whatever the alternative is. I just know that, according to the Boost Getting Started on Windows guide, most of Boost is "headers only" and therefore I shouldn't have any build step -- it should be simple to use it. Furthermore, this example (using boost::lambda) is - per their instructions - a header-only library, and should therefore be extremely easy to use.
I now updated the source code slightly to look in the current directory, instead of looking in the system include directory (which, as far as I'm aware at this point, doesn't exist in Windows):
#include "boost/lambda/lambda.hpp"
#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
    using namespace boost::lambda;
    typedef std::istream_iterator<int> in;

    std::for_each(
        in(std::cin), in(), std::cout << (_1 * 3) << " ");
}

Now I can manually verify that this file exists (the file CMakeProject2\CMakeProject2\boost\lambda\lambda.hpp can be found in File Explorer) - yet I'm still getting errors:
cannot open source file "boost/lambda/lambda.hpp"
Some further Googling led me to update my CMakeLists.txt file once more, putting it in its current form:
# CMakeList.txt : CMake project for CMakeProject2, include source and define
# project specific logic here.
#
cmake_minimum_required (VERSION 3.8)

# Add source to this project's executable.
file(GLOB CMakeProject2_SRC
    "*.h"
    "*.cpp"
    "**/*.h"
    "**/*.cpp"
    "**/*.hpp"
    "boost/lambda/lambda.hpp"
)
add_executable (CMakeProject2 ${CMakeProject2_SRC})
#add_executable (CMakeProject2 "CMakeProject2.cpp" "CMakeProject2.h")

# TODO: Add tests and install targets if needed.

Despite this I'm still getting the error:
cannot open source file "boost/lambda/lambda.hpp"
At this point I'm ripping my hair out. What am I doing wrong? What do I not know? How is something as simple as the Boost-equivalent of "Hello, World" not working for me?

A: Following recipe should work
Download Boost binaries from official boost binaries location and install to say C:\Boost
Most times you do not need to build Boost on your own.
Your CMakeLists.txt should look like follows
cmake_minimum_required (VERSION 3.8)

project(boostAndCMake)

set(BOOST_ROOT "C:\Boost") # either set it here or from the command line
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost REQUIRED COMPONENTS system) # header only libraries must not be added here

add_executable(CMakeProject2 CMakeProject2.cpp CMakeProject2.h)
target_include_directories(CMakeProject2 PUBLIC ${Boost_INCLUDE_DIRS})
target_link_libraries(CMakeProject2 ${Boost_LIBRARIES})

Because we used REQUIRED on the find_package call, CMake will fail execution and skip the rest of the script if it cannot be found. So no need to check Boost_FOUND. You need to check it, when you omit REQUIRED.
Now from the command line call from the directory where your script resides:
cmake -H. -Bbuildit -G "Visual Studio 15 2017" -DBOOST_ROOT=C:\Boost

This creates a build directory named buildit in the current directory, further creates a solution for Visual Studio 2017 inside the build directory and provides the setting for the variable BOOST_ROOT that is used in the find_package call to identify the Boost directory on your computer. To see what options are available on the find_package(Boost ...) call see FindBoost documentation in CMake.
Header Only Libraries
If your libraries are header only you need to omit them from the find_package(Boost ...) call. To see which libraries are not header only see this post.
Using newer Boost versions
If your CMake installation cannot find the requested version, e.g. 1.69.0, but supports the naming scheme of the more recent Boost version you can use it with set(Boost_ADDITIONAL_VERSIONS "1.69.0" "1.69"). Last change of the Boost naming scheme was from 1.65.1 to 1.66.

A: Here's a working setup for Boost 1.68 with CMake 3.12. Boost 1.69 is apparently "too new" for cmake to detect it properly. Since boost is not buildable by cmake, cmake itself must provide a FindBoost.cmake module that must keep up with boost changes.
So anyway, the CMakeLists.txt is as small as this:
cmake_minimum_required(VERSION 3.11)

project(foobar)

find_package(Boost 1.68 REQUIRED)
add_executable(foo foo.cpp)
target_link_libraries(foo PUBLIC Boost::boost)

Of course, you can split it in many subdirectories.
Invoking CMake in the command line should look like this:
cmake -DCMAKE_PREFIX_PATH=path_to_local_directory ..

Where path_to_local_directory is the installation path of all library you want to depend on. It will work for Boost, nlohmann_json, glfw3, Qt, you name it *(1). For my case, it was C:/local/ and another case was ../external/ (yes, it can be a directory local to the project!)
Let's take a peek at my own C:/local/:

ls -l /c/local/
total 12
drwxr-xr-x 1 myself 197609 0 May 26  2018 boost_1_67_0/
drwxr-xr-x 1 myself 197609 0 Sep  5 02:02 boost_1_68_0/

WARNING: Ensure your compiler architecture is the same as the installed boost version. Or else cmake will simply not find it.
I think that about it. The next CMake version (3.14) should work with the latest boost.

*(1) The said library will either need to export it's CMake target or you must provide a FindXXX.cmake

A: I'm using CMake 3.22 with Boost version 1.78.
The simplest solution is to set the Boost_INCLUDE_DIR when calling Cmake:
cmake -DBoost_INCLUDE_DIR=boost

Pass the directory to where the Boost libraries are. If you're using Visual Studio you can also set this in your CMake Settings:

Or, in the CMakeSettings.json file:
"cmakeCommandArgs": "-DBoost_INCLUDE_DIR=boost",

In my opinion, this is better than using the set function because you're not hard coding the path.

A: Add a target_include_directories(CMakeProject2 PRIVATE .) into your CMakeList.txt.
The . is the relative path of boost/lambda/lambda.hpp from CMakeLists.txt
And you should not add any .hpp file to the source list.


text:
Q: Prevent AutoMapper to treat string as collection in LINQ ProjectTo I've the following set of classes to map (only in one direction, from Data* to Api*):
// Top level

public class DataEntity
{
  public NestedDataEntity Nested { get; set; }
  // ... other primitive/complex properties
}

public class ApiEntity
{
  public NestedApiEntity Nested { get; set; }
  // ... other primitive/complex properties
}

// Nested level

public class NestedDataEntity
{
  public string Items { get; set; }
}

public class NestedApiEntity
{
  public IEnumerable<ApiSubItem> Items { get; set; }
}

public class ApiSubItem
{
  // there are properties here. Not needed for the sake of example
}

Mapping is configured within a Profile as in the following bit of code:
// mapping profile

public class MyCustomProfile : Profile
{
  public MyCustomProfile()
  {
    CreateMap<DataEntity, ApiEntity>();
    CreateMap<NestedDataEntity, NestedApiEntity>();

    CreateMap<string, IEnumerable<ApiSubItem>>()
      .ConvertUsing<TextToSubItemsConverter>();
  }
}

// type converter definition

public class TextToSubItemsConverter :
  ITypeConverter<string, IEnumerable<ApiSubItem>>
{
  public IEnumerable<ApiSubItem> Convert(
        string dataItems, IEnumerable<ApiSubItem> apiItems, ResolutionContext context)
  {
    // actually, deserialize & return an ApiSubItem[]
    // here just return some fixed array

    return new ApiSubItem[]
    {
      new ApiSubItem(),
      new ApiSubItem(),
      new ApiSubItem(),
    };
  }
}

// Main

public class Program
{
  public static void Main(string[] args)
  {
    Mapper.Initialize(cfg =>
    {
      cfg.AddProfile<MyCustomProfile>();
    });

    Mapper.AssertConfigurationIsValid();

    DataEntity dataEntity = new DataEntity()
    {
      Nested = new NestedDataEntity()
      {
        Items = "Ignored text",
      },
    };

    // This maps ok, no issues
    ApiEntity apiEntity = Mapper.Map<DataEntity, ApiEntity>(dataEntity);

    IQueryable<DataEntity> dataEntities = new[] { dataEntity }.AsQueryable();

    // This exposes the System.Char to ApiSubItem issue
    ApiEntity apiEntityProjected = dataEntities.ProjectTo<ApiEntity>().First();
  }
}

Mapping configuration passes initial validation at startup, but then when an actual mapping is required I get exception:

System.InvalidOperationException: Missing map from System.Char to my.whatever.namespace.ApiSubItem. Create using Mapper.CreateMap.

If I omit completely the configuration between string and IEnumerable<ApiSubItem>, initial validation complains about the same context:

Context:
    Mapping from type System.Char to my.whatever.namespace.ApiSubItem

although when added, it seems like it's not picked up by AutoMapper.
The mapping happens in a static context, through a ProjectTo<ApiEntity>() call on top of LINQ query over DbSet<DataEntity>. I've checked that converter does not require any dependency, just in case.
AutoMapper is 5.0.2, running in an MVC API web application under ASP.Net Core 1 RTM.
I've checked similar issues here on SO, but with no luck. Does anyone know how to make this type of scenario work? I guess I'm not the first one trying to (Auto)map from a string to a collection. TA
EDIT Added both failing and non-failing case to example
EDIT 2 After further search, somewhere someone suggested to ignore the field and perform mapping in AfterMap(). With this profile, exception is not thrown but resulting Items field is null:
CreateMap<DataEntity, ApiEntity>();
CreateMap<NestedDataEntity, NestedApiEntity>()
    .ForMember(api => api.Items, options => options.Ignore())
    .AfterMap((data, api) =>
    {
        api.Items = Mapper.Map<IEnumerable<ApiSubItem>>(data.Items);
    });

CreateMap<string, IEnumerable<ApiSubItem>>()
    .ConvertUsing<TextToSubItemsConverter>();

EDIT 3 Reworded question title to make it more specific for projection

A: I guess the actual answer is along the lines of "projections and converter/resolvers don't play nicely together". From AutoMapper Queryable.Extensions wiki:

Not all mapping options can be supported, as the expression generated must be interpreted by a LINQ provider. [...]
Not supported:

*

*[...]

*Before/AfterMap,

*Custom resolvers,

*Custom type converters

EDIT Workaround:
In this particular scenario, I've later found to be useful having an intermediate DTO entity that could grab some more fields, not needed for the final API entity but still needed for business logic.
In such DTO entity I left the string field as in DataEntity, so I could use projection and let AutoMapper/LinqToSQL grab only needed fields from DB.
Then, between DTO entity and API entity already in memory, I could apply a second mapping which also took advantage of custom converter for string ==> IEnumerable<ApiSubItem> mapping. HTH


text:
Q: Dockerfile Django not opening in browser I'm using Django 2.x and dockerizing the application.
I have the following Dockerfile content.
FROM python:3.7-alpine

# Install Rabbit-mq server
RUN echo @testing http://nl.alpinelinux.org/alpine/edge/testing >> /etc/apk/repositories

RUN apk --update add \
 libxml2-dev \
 libxslt-dev \
 libffi-dev \
 gcc \
 musl-dev \
 libgcc curl \
 jpeg-dev \
 zlib-dev \
 freetype-dev \
 lcms2-dev \
 openjpeg-dev \
 tiff-dev \
 tk-dev \
 tcl-dev \
 mariadb-connector-c-dev \
 supervisor \
 nginx \
 --no-cache bash

# Set environment variable
ENV PYTHONUNBUFFERED 1

# Set locale variables
ENV LC_ALL C.UTF-8
ENV LANG C.UTF-8

# -- Install Application into container:
RUN set -ex && mkdir /app

# -- Adding dependencies:
ADD . /app/

# Copy environment variable file
ADD src/production.env /app/src/.env

COPY scripts/docker/entrypoint.sh /app/

# Switch to the working directory
WORKDIR /app

RUN chmod ug+x /app/entrypoint.sh

# Install Pipenv first to use pipenv module
RUN pip install pipenv

# -- Adding Pipfiles
ONBUILD COPY Pipfile Pipfile
ONBUILD COPY Pipfile.lock Pipfile.lock
RUN pipenv install --system --deploy

RUN mkdir -p /etc/supervisor.d
COPY configs/docker/supervisor/supervisor.conf /etc/supervisor.d/supervisord.ini

EXPOSE 80 8000

CMD ["/app/entrypoint.sh"]

and the entrypoint.sh hash
#!/usr/bin/env bash

exec gunicorn --pythonpath src qcg.wsgi:application -w 3 -b 0.0.0.0:8000 -t 300 --max-requests=100

I use the command to build the image
docker build . -t qcg_new

and running it using
docker run qcg_new

It runs the docker and the gunicorn server is also running on 8000 port
[2019-09-16 09:03:31 +0000] [1] [INFO] Starting gunicorn 19.9.0
[2019-09-16 09:03:31 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
[2019-09-16 09:03:31 +0000] [1] [INFO] Using worker: sync
[2019-09-16 09:03:31 +0000] [10] [INFO] Booting worker with pid: 10
[2019-09-16 09:03:31 +0000] [11] [INFO] Booting worker with pid: 11
[2019-09-16 09:03:31 +0000] [12] [INFO] Booting worker with pid: 12

But when I visit http://127.0.0.1:8000 or http://localhost:8000 in the browser, it does not opens.

A:
The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the
  image and the person who runs the container, about which ports are
  intended to be published. To actually publish the port when running
  the container, use the -p flag on docker run to publish and map one or
  more ports, or the -P flag to publish all exposed ports and map them
  to high-order ports.

see it here
so you need to -p 8000:8000 in your run command


text:
Q: Cycling through minimized windows In Mac OS X, how can cycle through minimized windows and/or maximize them using a shortcut?
I noticed that I cannot cycle through minimized windows with ⌘-``.

A: If full keyboard access is turned on in the system preferences, you can also use Ctrl + F3 to give the dock the keyboard focus. With the cursor keys you can then navigate to the the minimized window and use Return to unminimize the window.

A: In addition to the built-in ways of cycling through windows, there is a nice shareware utility called Witch that is like Command + Tab on steroids. (You can easily remap keyboard shortcuts so that Witch uses Command + Tab, too.)
The website for the software is here (complete with a very nice screenshot).
The program costs 10 euros to register, but appears to work for a very long time without registration -- I finally did so after several months of use.
Highly recommended, especially for someone like me who came over from the Windows world recently and for whom the native Mac way of window-switching didn't quite mesh with my habits.

A: Ctrl - F4 will cycle through open windows.
Command + Tab should work for all open applications.

A: I do not believe there is. However, leaked Snow Leopard images show minimised windows in Exposé. Not helpful at the moment, but worth bearing in mind.

A: If you want to maximize a minimized application, cmd-tab to it, then keep holding cmd down and press the option key.  Then release both option and command and the window will maximize.
Witch is great for shareware, but for free, this shortcut is your best option.
Also, my workflow changed quite a bit from windows (where I minimized all kinds of things) to the mac, where I hide stuff (cmd-H) instead.  I find hiding to be superior to minimizing.
I also love the shortcut of holding opt-cmd down and clicking on an icon in the toolbar to hide everything besides the clicked on application.  Tidies things up and makes it easy to access the desktop.
Snow Leopard Update:
If you cmd-tab to an application and then keep holding cmd and hit the up or down arrows, you'll enter an expose-like mode where all of the windows for that app (including the minimized ones) are selectable.  Then you can just use your arrow keys to select the right window and hit enter to select it.

A: Here is a previous discussion with all kinds of useful os x shortcuts including the Ctrl-F4 mentioned by John T.
https://superuser.com/questions/3927/windows-to-mac-os-migration-tips-cheat-sheet


text:
Q: Retagging after a product name change (eg, visual-studio-11 to visual-studio-2012) What's the proper protocol for handling retagging of questions when a product's name changed from a code name to a release name?  In particular, I'm asking about visual-studio-11 (the pre-release "code name" if you will) becoming branded as visual-studio-2012 after the release of the Release Candidate last week.
Should all questions tagged with the now defunct code name be retagged with the new name?  Should all questions with the old tag simply be left there, since that tag accurately reflected the name of the product they were asked about?  Or should they be retagged with some amount of thoughtfulness?

A: Probably Synonym tags are a solution. Read this article : https://stackoverflow.com/privileges/suggest-tag-synonyms
From what I understood from the above article,(if I've understood right) If a new tag is created and the old tag is made a synonym of the new one, the older questions will get retagged to the new tag.