text:
Q: Operator overloading function in class c++ This is my standalone operator overloading function.
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

typedef vector <string> record_t;
typedef vector <record_t> data_t;

istream& operator >> ( istream& ins, record_t& record )
  {

  record.clear();
  string line;
  getline( ins, line );
  stringstream ss( line );
  string field;
  while (getline( ss, field, '\t' ))
    {
    stringstream fs( field );
    string f("");  // (default value is 0.0)
    fs >> f;
    record.push_back( f );
    }
  return ins;
  }

istream& operator >> ( istream& ins, data_t& data )
  {

  data.clear();
  record_t record;
  while (ins >> record)
    {
    data.push_back( record );
    }
  return ins;
  }

int main()
  {
  // Here is the data we want.
  data_t data;

  ifstream infile( "split.idx" );
  infile >> data;

  if (!infile.eof())
    {
    cout << "Fooey!\n";
    return 1;
    }

  infile.close();

  // Otherwise, list some basic information about the file.
  cout << "Your CSV file contains " << data.size() << " records.\n";

  return 0;
  }

Here I've two Operator Overloading functions.
istream& operator >> ( istream& ins, record_t& record )
istream& operator >> ( istream& ins, data_t& data )

Now I wish to write the function in a Class format. So I declared the typedef data and record variables in Header File called ("Headers.h")
typedef vector <string> record_t;
typedef vector <record_t> data_t;

Now I wrote a class.
FileHandler1.h
#ifndef _FILEHANDLER
#define _FILEHANDLER
#endif

class FileHandler1
{

    public :

        istream& operator >> ( istream& ins, record_t& record );

        istream& operator >> ( istream& ins, data_t& data );

};

FileHandler1.cpp
#include "Headers.h"
#include "FileHandler1.h"
istream& FileHandler1:: operator >> ( istream& ins, record_t& record )
{
//Same set of code I posted initially
}

istream& FileHandler1:: operator >> ( istream& ins, data_t& data )
{
// Same set of code
}

Now I got below error.

error: 'std::istream& FileHandler1::operator>>(std::istream&,
  record_t&)' must take exactly one argument

How can I fix this bug ?

A: A binary operator, such as operator>>, can be implemented as either a non-member function or a member function. When it is implemented as a non-member function, it takes two arguments, let's say T and U. When it is implemented as a member function, it takes one argument - just U - and the left operand is the type of the class it is a member of.
That is, doing t >> u, where operator>> is a member of T, calls t.operator>>(u).
Here, you're trying to make operator>> a member of FileHandler1, even though the left operand of >> is not of that type. If you were allowed, the operator would have to be a member of istream, but that's not up to you because it's a standard type. You have to implement these functions as non-member functions.
If you do have an operator>> member of FileHandler1, it will have to be declared with a single argument:
FileHandler1& operator >> ( U& right_operand );

And then you must use it with a FileHandler1 object as the left operand:
FileHandler1 fh;
U u;
fh >> u; // Equivalent to fh.operator>>(u)

A: The input operators in classes is for when a class instance is the input stream. E.g. in your case:
FileHandler1 fh1;
fh1 >> something;

The above translates into:
fh1.operator>>(something);

This is the reason that member input operator only takes a single argument, which is what the error message tells you.
This doesn't seem to be what you want, so you have to keep the input operators as free-standing functions.


text:
Q: Css left:100% going beyond the device screen size I am fairly new to web-development so it could be something very novice that I am doing wrong.
Question : I am trying to add a circle to the top-right position. For this I am making a div and giving it 100px height and width with border radius 50% to make a circle and to move to right I am doing left 100%.
What I expect is my browser shows me a circle on top-right, instead what happens is my browser introduces a scroll bar and pushes the circle to further right.
Here is the code that I have tried along with screenshots of the problem I am facing.

<!DOCTYPE html>

    <title>Scenario 6</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">

Expected -
Actual -
I do not know that if this is some browser zoom error or something wrong in the code. Any help is much appreciated. Thanks.

A: This happens because you have set left: 100%; on #circle. So the circle started to draw from startX = 100% width of screen (left = 100%) position. Therfore, it can be drawn outside of the screen.
Instead of left: 100%;, use right: 0 and the problem will be resolved.

<!DOCTYPE html>

  <title>Scenario 6</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">

A: See the following code:
<!DOCTYPE html>

 <title>Scenario 6</title>
 <meta name="viewport" content="width=device-width,initial-scale=1">

For left position you have to add left: calc(100% - 100px). 100px minus because your box has 100px width and add box-sizing: border-box;

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to enable all HTTP methods on Apache The apache server I have in my company blocks
some HTTP methods that are required for WebDav.
I would like to help my admin to enable HTTP
methods I need. He sent me httpd.config file
but I'm unable to find the section which blocks
methods I need (like LOCK and UNLOCK)
In directory section I have:
AllowOverride AuthConfig FileInfo Indexes Limit Options=Indexes,Includes,IncludesNOEXEC,MultiViews,SymLinksIfOwnerMatch,FollowSymLinks,None

My admin also have told me that he did not find .htaccess
So my question is - where does the Apache block methods I need
(does the apache enables only "default" http methods?)
And second question is - can I unlock the methods I need by
listing them in httpd.conf file in directory section, for example:
  <Limit GET PUT POST DELETE PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK>
  Require valid-user
  </Limit>

I don't want to use the mod_dav module (i want to use sabre server).
I just want to unlock http methods that are required for WebDav
Thank you,
Mike


text:
Q: The broker is not responding to the connection request message correctly The return code is MqttConnectReturnCode.notAuthorized I'm trying to connect my Flutter App with mqtt broker but unfortunately this happened. May I know why this happened??
[log] mqtt-client::NoConnectionException: The maximum allowed connection attempts ({3}) were exceeded. The broker is not responding to the connection request message correctly The return code is MqttConnectReturnCode.notAuthorized

A: You exceeded your login attempts for connecting Mqtt, this issue is related to your
 MQTT client

it only give you three attepts to log in correctly ,after that it will close the login
you need to fix it by using
MQTT client setting


text:
Q: CSS Not being rendered, and error: "Firefox can't establish a connection to the server at localhost:4353." My website was working fine on Friday using localhost, and now none of the css is being rendered, and if I try to click on a link, I get an error that a connection can't be established. I opened up another project before looking at this one, and ever since, I have had problems. Any ideas?

A: As the error clearly states, your server is not running.
You need to start the development server.


text:
Q: creating a trigger that executes sql statement over ssh in mysql I have 2 (th and ct) servers that are completely separated each with it's own database I want to sync a table(et) in th with ct
    I want if new inserts are done in table th a trigger will fire a ssh connection to ct server and insert the new rows I think the script should look something like the following  but I can't figure out the syntax
 DROP TRIGGER IF EXISTS et-sync
CREATE TRIGGER et-sync AFTER INSERT ON th.et
FOR EACH ROW BEGIN
 ssh user@11.11.2.11 "mysql -uroot -ppassword -e \"INSERT  db_testplus.user SET t = NEW.t;""
END;

and should I use this or just use Percona Toolkit for MySQL
(pt-table-sync) as I don't think adding a tool to control database sync at that scale is worth it(added complexity)
I know that adding replicas is properly the best solution but considering the current system design I thought of postponing the redesign of ct database for some time as it will take sometime to make it from scratch and it's an important part for the business
any suggestions ??

A: For security reasons, MySQL does not allow launching processes from within itself.
Usually the alternative is to make a cron job to do orchestrate the actions, reaching into the database as needed to communicate and coordinate.


text:
Q: Find the limit and differential equation We have the following equality:
$$ f(x + \Delta x) = f(x) + a \Delta x \, f(x) - 10 \, b \Delta x $$
with a & b constants. If we take $\lim_{\Delta t \to 0}$ , we get a differential equation. My question is, what is the limit? I always have trouble with these types of limits, because in my head I just imagine that all the terms with a factor $\Delta x$ disappear. But in our case, we would get that $f(x) = f(x)$, which is obviously not what we want.

A: Hint: Subtract $f(x)$ from both sides and then divide both sides by $\Delta x$. When you take the limit as $\Delta x\to 0$, you should recognize what the left side becomes.

A: As answered by @MPW:
Given $$f(x + \Delta x)=f(x) + a\Delta xf(x)-10b\Delta x$$
Which, upon rearrangement yields
$$f(x + \Delta x) - f(x) = a\Delta xf(x) - 10b \Delta x$$
Dividing through by $\Delta x$, gives
$$\frac{f(x+\Delta x)-f(x)}{\Delta x} =\frac{a\Delta xf(x)-10b\Delta x}{\Delta x}$$
Now taking the limit as $\Delta x \to 0$ yields:
\begin{align*}\lim_{\Delta x \to0} \frac{f(x+ \Delta x)-f(x)}{\Delta x} &=\lim_{\Delta x \to 0} \frac{a\Delta xf(x) - 10b \Delta x}{\Delta x} \\ &=\lim_{\Delta x \to0}  \frac{\Delta x(af(x)-10b)}{\Delta x} \\ &= \lim_{\Delta x \to0}  (af(x)-10b) \\ &=af(x)-10b\end{align*}


text:
Q: AWS Cloudformation integration with github Well, I'm starting to use AWS CloudFormation to provision my infra as a code. So I have some doubts about it:

*

*My cloudformation code is inside github, I would like to trigger a cloudformation stack update automatically when I new commit is made in the master branch. Is this possible?

*Cloudformation can provision my EC2 instances, but I need to configure these instances after this, for example: Install nginx, change port in nginx, move files, and so on. How can I automate it using cloudformation ?

A: *

*You can set up a two-step CodePipeline, which uses GitHub as the source/trigger. In the second step configure a CloudFormation action that updates your stack.

*You have a few options here:

*

*Create your own AMI with all additional packages installed.

*Use user data to install packages at instance startup time.

*Dockerize your app, and launch it in ECS/EC2 instead of raw EC2.


text:
Q: JQuery - Click on background I have a design with a layover, like this:
.layover{
    width: 100%;
    height: 100%;
    display: none;
    position: absolute;
    background: rgba(0,0,1,0.7);
    z-index: 1000;
}

I use show this when a button is clicked, easy. It has another div in it, but I want to close this things when the .layover is clicked. But if I click the form over it, it still closes!
My javascript trying to close it:
$(".layover").on("click", function(){
    if(overlay_active){
        $(".layover").fadeOut();
        overlay_active = false;
    }
});

How can I make it that just if I click .layover that it closes, and not if I click on the childs of .layover?

A: Try this:
$(".layover").on("click", function(e){
    if(e.target !== e.currentTarget) return;

    if(overlay_active){
        $(".layover").fadeOut();
        overlay_active = false;
    }
});


text:
Q: Binomial Theorem Identities What's the actual difference between these two formulas (they're both in the chapter regarding binomial theorem).  They're from two different textbooks :
$${n\choose k}+{n\choose k+1}={n+1\choose k+1}$$
and
$${n-1\choose k}+{n-1\choose k-1}={n\choose k}$$
I'll be appreciated if someone explain it to me either combinatorially or algebraically.  Thanks!

A: There's no real difference: they express the same fact about binomial coefficients. To see this, first replace $n$ by $m$ and $k$ by $\ell$ in the second equation to get
$$\binom{m-1}\ell+\binom{m-1}{\ell-1}=\binom{m}\ell\;.\tag{1}$$
Now let $\ell=k+1$ and $m=n+1$; then $(1)$ becomes
$$\binom{n}{k+1}+\binom{n}k=\binom{n+1}{k+1}\;,$$
which is your first equation.
In terms of Pascal's triangle each of these equations says that each entry is the sum of the two above it.

A: $$\binom n k+\binom n{k+1}$$
$$=\frac {n!}{k!(n-k)!}+\frac{n!}{(k+1)!(n-k-1)!}$$
$$=\frac{n!}{(k+1)! (n-k)!}\left(k+1+n-k\right)$$
$$=\frac{(n+1)!}{\{(n+1)-(k+1\}!)(k+1)!}$$
$$=\binom{n+1}{k+1}$$

A: We simply use the definition of Combination $${n \choose k} = {n! \over {(n-k)!k!}}$$
The top one goes like this $${n \choose k} + {n \choose k+1}$$
$$= {n! \over {(n-k)!k!}} +{n! \over {(n-(k+1))!(k+1)!}}$$
$$= {{n!(k+1) }\over {(n-k)!k!(k+1)}} +{{n!(n-k)} \over {(n-k)!k!(k+1)}}$$
$$={n![(k+1)+(n-k)]\over{(n-k)!(k+1)!}}$$
$$={(n+1)!\over{(n-k)!(k+1)!}}$$
$$={ {n+1} \choose {k+1}}$$
The bottom one can be proven using the top one just by substitution :)

A: Combinatorial proof of Pascal identity
Denote by $$C^k(I_n)=\{A:A\subset I_n,|A|=k\},|C^k(I_n)|=\binom{n}{k}$$ the set of all k-subsets of set $I_n=\{0,1,2,...,n-2,n-1\}$ and then define a set
$$C'=\{A:A=C_1\cup\{n-1\},C_1\in C^{k-1}(I_{n-1})\}$$
now is clear that
$$|C'|=|C^{k-1}(I_{n-1})|=\binom{n-1}{k-1}$$
because
$$C^k(I_n)=C'\cup C^k(I_{n-1})$$
$$C'\cap C^k(I_{n-1})=\emptyset$$
follow that
$$|C^k(I_n)|=|C'|+|C^k(I_{n-1})|$$
or
$$\binom{n}{k}=\binom{n-1}{k-1}+\binom{n-1}{k}$$


text:
Q: Closed form paradox: Is $e$ a closed form expression? Is Euler's constant, $e$, considered to be a closed form expression?
If yes, then our definition of closed form must allow limits, so all limits restricted to elementary functions would have a closed form.
If no, then $\lim\limits_{n\to\infty}\left(1+\frac1n\right)^n$ has no closed form.
No matter what definition of "closed form" we use, both outcomes don't seem right. Am I missing something?

A: Based on comments from @freakish, I will self-answer.
Typically, definitions of closed form include the use of the exponential function, $e^x$, so they admit $e$ as a closed form. These definitions can exclude the use of limits to produce new expressions (even though $e$ is defined by a limit).


text:
Q: Pass external function to a class method I would like to understand how to pass an external function to a class method.
For example say I am trying to call a function 'job' every second.
import schedule
import time

def set_timer_minutes(func):
    schedule.every(1/60).minutes.do(func)

def job():
    print("I'm working...")

set_timer_minutes(job)
while 1:
    schedule.run_pending()
    time.sleep(1)

The above code prints 'I'm working' every second.
But if I try to put it in a class
class Scheduler:
    def set_timer_minutes(self,func):
        schedule.every(1/60).minutes.do(func)
        while 1:
            schedule.run_pending()
            time.sleep(1)

def job():
    print("I'm working...")

x= Scheduler
x.set_timer_minutes(job)

I get

TypeError: set_timer_minutes() missing 1 required positional argument:
  'func'

A: You need to create an instance of Scheduler.
x = Scheduler()

instead of
x = Scheduler


text:
Q: Cannot change dependencies of configuration ':compile' after it has been resolved I have a simple java project that uses json.jar library. gradle.build file content is:
apply plugin: 'java'
jar {
  manifest {
    attributes(
      'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
      'Main-Class': 'main.java.Main'
    )
  }
}
dependencies {
  compile 'org.json:json:20160212'
}

problem is when I want to add json to my classpath and use it, this error happens
* Where:
Build file '/home/tina-admin/Documents/myJavaProjects/LongMan/build.gradle' line: 11

* What went wrong:
A problem occurred evaluating root project 'LongMan'.
> Cannot change dependencies of configuration ':compile' after it has been resolved.

how can I solve this?

A: First, you have to add a repositories block to specify where dependencies are retrieved from (usually before dependencies {...}.
repositories {
  mavenCentral()
}

Then, if you put the dependencies block before the jar block it seems to work, although I'm not sure about why it doesn't work the other way (maybe jar {...} uses the compile configuration and "locks" it).

A: Try to set org.gradle.configureondemand to false if you use it in gradle.properties

A: this bit me - i had to move my jar / fat jar block to under the dependencies / repositories blocks - here's my gradle kotlin that worked:
import org.gradle.jvm.tasks.Jar

plugins {
    java
    kotlin("jvm")
    kotlin("kapt")

}

group = "com.secbot"
version = "1.0-SNAPSHOT"

tasks {
    "build" {
        dependsOn(fatJar)
    }
}

tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>() {
    sourceCompatibility = "11"
    targetCompatibility = "11"
    kotlinOptions.jvmTarget = "11"
}

repositories {
    mavenCentral()
    mavenLocal()
    jcenter()
    google()
    maven(url= "https://oss.sonatype.org/content/groups/public")
    maven(url ="https://jitpack.io")
}

dependencies {

    implementation("com.google.code.gson:gson:2.8.6")

    implementation(kotlin("stdlib"))
}
val jar by tasks.getting(Jar::class) {
    manifest {
        attributes["Main-Class"] = "com.foo.Application"
    }
}
val fatJar = task("fatJar", type = Jar::class) {
    baseName = "${project.name}-fat"
    manifest {
        attributes["Implementation-Title"] = "Foo Bar!"
        attributes["Implementation-Version"] = version
        attributes["Main-Class"] = "com.foo.Application"
    }
    from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) })
    with(tasks.jar.get() as CopySpec)
}

A: Wow - Can't believe this happened to me as well
Cannot change dependencies of dependency configuration ':implementation' after it has been included in dependency resolution.

I was able to resolve this by having this code:
kotlin {
    sourceSets {
        val main by getting {
            dependencies {
                implementation("ca.blah:blah:1.0.0")
            }
        }
    }
}

Be located before the dependencies { } block instead of at the end of the build.gradle.kts file.

A: Here is what resolved that issue for me. Add this to your framework gradle. Cheers!
apply from: 'https://raw.githubusercontent.com/sky-uk/gradle-maven-plugin/master/gradle-mavenizer.gradle'

Ref-
https://github.com/sky-uk/gradle-maven-plugin


text:
Q: How to compare two Vectors and clip the first Vector values by the maximum value in another Vector using Math.NET Numerics I have two arrays
double[] a = new double[] {1,2,3,4,5};
double[] b = new double[] {2,3,2,3,5};

which I convert into two vectors:
Vector<double> A = Vector<double>.Build.DenseOfArray(a);
Vector<double> B = Vector<double>.Build.DenseOfArray(b);

I would like to compare the values of 'A' against 'B' and return a vector where elements 2 and 3 (0,1,2,3,4) are clipped because they are greater than the equivalent value in 'b' e.g:
[1,2,2,3,5]

Can anyone explain how to do this without resorting to a for loop?

A: Looks like the Map2 method can do what you want.  From the documentation:

Vector<T> Map2(Func<T, T, T> f, Vector<T> other, Zeros zeros)
Applies a function to each value pair of two vectors and returns the results as a new vector.

Note that the third parameter is actually optional and has a default value of Zeros.AllowSkip.
You can use the method like this:
Vector<double> C = A.Map2((x, y) => (x > y ? y : x), B);

Demo fiddle: https://dotnetfiddle.net/hfWJhI


text:
Q: Is there a general way to differentiate between homeomorphism and homotopy equivalence in a mental picture? Let $X$ and $Y$ are two topological spaces.

*

*The spaces $X$ and $Y$ are said to be homeomorphic if there exists a homeomorphism between them.

*The spaces $X$ and $Y$ are said to be homotopy equivalent if there exist continuous maps $f:X \rightarrow Y$ and $g:Y \rightarrow X$ such that $g \circ f$ is homotopic to $1_X$ and $f \circ g$ is homotopic to $1_Y$.
In the beginning of a Topology course we sometimes hear that Topology is like a rubber sheet geometry. Also sometimes we have proved several results using these kinds of intuitions to begin with like $\sum S^n = S^{n+1} $ ,$CS^n= D^{n+1}$. Here one can explicitly find  homeomorphisms between ($S^{n+1}$ and $\sum S^n$) and ($D^{n+1}$ and $CS^n$). (Here $\sum$ is suspension and $C$ is the cone.)
Little strangely, one will use the "same kind of intuition" to show that any convex set like $X = R^n$ is homotopy equivalent to $Y=$ "a point" by linear homotopy. But here obviously  $R^n$ is not homeomorphic to a point (as clearly bijectivity fails).
But the real problem starts with the intuition when $Y$ is not as simple as "a point" .
My question:
Is there a general way to differentiate between homeomorphism and homotopy equivalent intuitively in a mental picture? Or in other words, whenever we draw a mental picture of an object made of rubber like material, then when we squeeze it or extend it, what do we actually subconsciously think ? Is it homotopy, homeomorphism, deformation retract,...etc.?
Thanks in advance.

A: My intuition is that bending, squeezing and extending is all homeomorphism. These are easily reversible, they don't loose (topological) information.
More aggressive deformations, e.g. collapsing a dimension (I'm thinking about collapsing $[0,1]^2$ to $[0,1]\times\{0\}$), would be a deformation retraction. Some information (e.g. the dimension) may be lost in the process. Of course homeomorphism is a special case of such deformation.
Note that deformation retractions and homotopy equivalences are very closely related: two spaces are homotopy equivalent if and only if they are both deformation retracts of some superspace. And so I usually think about them as pretty much the same thing, even though technically they are not.


text:
Q: Best OOP practice for object vs dataservice I am working on a new project and am curious as to how I should go about doing something properly.
Lets say I have a table called "leads" in my database. This clearly means that a single "lead" would be an object, and I'd need a class in order to create, update, or pull information for said "lead" object.
Now here is where my question comes in. Lets say I have a page called leads.php with a table that I want to populate with multiple "leads" from my database. Do I create the method for listing all leads within the "lead" class itself, or do I create a seperate "data service" class, which would represent a service object used to retrieve multiple leads?
Any help would be greatly appreciated.

A: If you add a method Lead.list() where it returns a list of leads it's violation of SRP, as the fetching a list of Leads is not the responsibility of Lead object.
So the best option is to use a data service or a repository. For example LeadRepository could have methods GetAll(), GetById(id)


text:
Q: Internal Server Error heroku/django I stack in heroku django tutorial after deploy project to heroku server.
When I open heroku I have on website : Internal Server Error.
This is my heroku logs:

2015-04-19T11:37:10.239891+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=secure-waters-8181.herokuapp.com request_id=6a5e44bf-4691-4207-9c8f-d2b18bf46a23 fwd="213.108.119.145" dyno=web.1 connect=2ms service=6ms status=500 bytes=244
2015-04-19T11:37:37.790381+00:00 heroku[router]: at=info method=GET path="/" host=secure-waters-8181.herokuapp.com request_id=25f8ea3a-a81d-45dd-a576-5ce58029b75e fwd="213.108.119.145" dyno=web.1 connect=0ms service=2ms status=500 bytes=244
2015-04-19T11:37:37.789336+00:00 app[web.1]: [2015-04-19 11:37:37 +0000] [9] [ERROR] Error handling request
2015-04-19T11:37:37.789341+00:00 app[web.1]: Traceback (most recent call last):
2015-04-19T11:37:37.789343+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 93, in handle
2015-04-19T11:37:37.789344+00:00 app[web.1]:     self.handle_request(listener, req, client, addr)
2015-04-19T11:37:37.789346+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 134, in handle_request
2015-04-19T11:37:37.789347+00:00 app[web.1]:     respiter = self.wsgi(environ, resp.start_response)
2015-04-19T11:37:37.789349+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/dj_static.py", line 83, in __call__
2015-04-19T11:37:37.789351+00:00 app[web.1]:     return self.application(environ, start_response)
2015-04-19T11:37:37.789354+00:00 app[web.1]:     self.load_middleware()
2015-04-19T11:37:37.789356+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 44, in load_middleware
2015-04-19T11:37:37.789353+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 168, in __call__
2015-04-19T11:37:37.789357+00:00 app[web.1]:     mw_class = import_string(middleware_path)
2015-04-19T11:37:37.789358+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/module_loading.py", line 26, in import_string
2015-04-19T11:37:37.789360+00:00 app[web.1]:     module = import_module(module_path)
2015-04-19T11:37:37.789361+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/importlib/__init__.py", line 37, in import_module
2015-04-19T11:37:37.789362+00:00 app[web.1]:     __import__(name)
2015-04-19T11:37:37.789364+00:00 app[web.1]: ImportError: No module named security

and this is my settings.py:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'hellodjango.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'hellodjango.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'

# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES['default'] =  dj_database_url.config()

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers
ALLOWED_HOSTS = ['*']

# Static asset configuration
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

I have to change something in database setting or I miss click when I doing tutorial ? I not have idea to fix it...
( sorry for my snippet format, I dont have idea to copy my code in diffrent way )

A: In the MIDDLEWARE_CLASSES of settings.py, you have 'django.middleware.security.SecurityMiddleware',, which is new in Django 1.8. Either make sure Heroku is using Django 1.8, or remove that line from MIDDLEWARE_CLASSES.


text:
Q: Boundary conditions for a ODE from Volterra integral equation I am modeling a cyclic voltammetry experiment. The mathematical model for it boils down to a Volterra integral equation of the first kind, with an unknown function $\chi(z)$ and known constants $\xi$ and $\theta$:
$$\int_0^{\sigma t}\frac{\chi(z)\mathrm{d}z}{(\sigma t-z)^{1/2}} = \frac{1}{1+\xi\theta e^{-\sigma t}}.$$
Is this a well-posed integral equation? I am troubled by the fact that the right-hand side does not vanish as $\sigma t$ tends to zero.
To solve this integral equation, I am differentiating both sides with respect to $\sigma t$ to obtain an ordinary differential equation:
$$\frac{\chi(z)}{\sqrt{z}}+2\sqrt{z}\chi^\prime(z) = \frac{-\xi\theta e^{-z}}{(1+\xi\theta e^{-z})^2}.$$
What boundary condition should I assume to solve this differential equation?


text:
Q: Synchronous Call to REST on Contact update We have a requirement to update back-end (using REST) system when a contact is updated. Using triggers we cannot  call webservice synchronously.
Is there a way we can implement this other than customizing the edit page with visual-force page.

A: Different ways one can make calls synchronously:

*

*A custom Visualforce page or button initiates an Apex SOAP callout in a synchronous manner.

*A custom Visualforce page or button initiates an Apex HTTP callout in a synchronous manner.

*A trigger that's invoked from Salesforce data changes performs an Apex SOAP or HTTP callout in a synchronous manner.

*A batch Apex job performs an Apex SOAP or HTTP callout in a synchronous manner.
May be option 4 is what you might be looking for.
More info on making calls synchronous here : Remote Process Invocation—Request and Reply

A: If you are just using the standard "Edit" button, you don't have a way to make a callout synchronously. Even if you write a trigger, you cannot make a callout from trigger synchronously.
Not completely sure about your use case, as if you want to make a callout every time a contact record is updated or only specific field. But if you can split the update operation to make the callout only when specific fields are updated instead of the whole record, then you can introduce a custom button using a VF page or Lightning component, to update those specific fields and then invoke the web service callout synchronously. This way you can still continue using the standard edit operation on the contact with minimal change by utilizing a custom button.
If that's not what you need, then you will need to either make the callout asynchronously or customize your overall Edit operation.

A: I am sure you have your reasons. But most of the times (if not all), synchronous call-outs are detrimental to user experience.
I would rather keep that async and show the status of back-end updates - that gives the perception that the performance is better even though the back-end operations can take the same time.


text:
Q: Why is the library built for armv7 even though I set -march=armv6? I'm trying to build libx264 for armv6, but what I get seems to be built for armv7. I'm using this configure line:
./configure --host=arm-linux-gnueabihf --enable-static --cross-prefix=${CCPREFIX} --prefix=... --extra-cflags='-march=armv6' --extra-ldflags='-march=armv6' --extra-asflags='-march=armv6'

which results in an output like this:
[...]
arm-linux-gnueabihf-gcc -Wno-maybe-uninitialized -Wshadow -O3 -ffast-math  -Wall -I. -I. -march=armv6 -std=gnu99 -D_GNU_SOURCE -fomit-frame-pointer -fno-tree-vectorize   -c -o common/opencl.o common/opencl.c
arm-linux-gnueabihf-gcc -Wno-maybe-uninitialized -Wshadow -O3 -ffast-math  -Wall -I. -I. -march=armv6 -std=gnu99 -D_GNU_SOURCE -fomit-frame-pointer -fno-tree-vectorize   -c -o encoder/slicetype-cl.o encoder/slicetype-cl.c
arm-linux-gnueabihf-gcc -I. -I. -march=armv6 -c -DSTACK_ALIGNMENT=4 -DHIGH_BIT_DEPTH=0 -DBIT_DEPTH=8 -o common/arm/cpu-a.o common/arm/cpu-a.S
[...]

now this is what I see:
$ readelf -A x264
Attribute Section: aeabi
File Attributes
  Tag_CPU_name: "7-A"
  Tag_CPU_arch: v7
  Tag_CPU_arch_profile: Application
  Tag_ARM_ISA_use: Yes
  Tag_THUMB_ISA_use: Thumb-2
  Tag_FP_arch: VFPv3
  Tag_Advanced_SIMD_arch: NEONv1
  Tag_ABI_PCS_wchar_t: 4
  Tag_ABI_FP_denormal: Needed
  Tag_ABI_FP_exceptions: Needed
  Tag_ABI_FP_number_model: IEEE 754
  Tag_ABI_align_needed: 8-byte
  Tag_ABI_enum_size: int
  Tag_ABI_HardFP_use: Deprecated
  Tag_ABI_VFP_args: VFP registers
  Tag_CPU_unaligned_access: v6
  Tag_DIV_use: Not allowed

also I see this:
$ readelf -A encoder/slicetype-cl.o
Attribute Section: aeabi
File Attributes
  Tag_CPU_name: "6"
  Tag_CPU_arch: v6
  Tag_ARM_ISA_use: Yes
  Tag_THUMB_ISA_use: Thumb-1
  Tag_FP_arch: VFPv2
  Tag_ABI_PCS_wchar_t: 4
  Tag_ABI_FP_number_model: Finite
  Tag_ABI_align_needed: 8-byte
  Tag_ABI_align_preserved: 8-byte, except leaf SP
  Tag_ABI_enum_size: int
  Tag_ABI_HardFP_use: Deprecated
  Tag_ABI_VFP_args: VFP registers
  Tag_ABI_optimization_goals: Aggressive Speed
  Tag_CPU_unaligned_access: v6

but:
$ readelf -A common/arm/cpu-a.o
Attribute Section: aeabi
File Attributes
  Tag_CPU_name: "7-A"
  Tag_CPU_arch: v7
  Tag_CPU_arch_profile: Application
  Tag_ARM_ISA_use: Yes
  Tag_THUMB_ISA_use: Thumb-2
  Tag_FP_arch: VFPv3
  Tag_Advanced_SIMD_arch: NEONv1

Can someone explain why those commands seem to output an armv6 binary once but an armv7 binary in the other case? May that be the reason why the resulting binary is marked as armv7?
Thank you for any explanation.

A: It is likely that cpu-a.S (it is used for CPU detection, right) is missing an .object_arch directive, to override the architecture automatically chosen by the assembler (due to the .fpu neon directive).
You should be able to fix this using:
.object_arch armv6

near the start of the file.


text:
Q: FullCalendar: Default timezone irrespective of client's location I am trying to create an appointment-scheduling application with fullcalendar. I want to represent time-slots on the calendar in only one timezone(i.e., EST) across all locations. So even if a person from PST zone is viewing the calendar, the times should be in EST. Also, even he/she schedules clicks a slot, the time should be in EST. How can I set a default time-zone for the calendar irrespective of location.

A: I believe this can be done by specifying the timezone string when you initialize your calendar:
$('#calendar-selector-id-name').fullCalendar({
    timezone: 'American/Indiana/Indianapolis'
});

You mentioned the gcal.js and so, I am wondering if this needs to be defined like:
$('#calendar-selector-id-name').fullCalendar({
    timezone: 'American/Indiana/Indianapolis',
    eventSources:[{
        url: 'https://www.google.com/calendar/feeds/...',
        currentTimezone: 'American/Indiana/Indianapolis'
    }]
});

Demo
Docs
Timezone problems when using Google Calendar #1801
EDIT
@jaykumarark did some further research and dug up the following:
Google Calendar - htmlLink not always defined #2844
Which revealed that for GoogleApps calendars, an initialized htmlLink variable is not provided for events that only share free/busy information, and hide event details.
Jay also noted discovering the following work-around:
"commenting line 144 in gcal.js //url=injectQsComponent(url, 'ctz=' + timezoneArg); I could represent times in a particular timezone irrespective of location."
So, in summary:

*

*Currently, setting timezone, irrelevant of location, seems to work
fine with GoogleApps calendars, as long one of the 3 "Share all
information, ..." sharing settings is selected.

*Adam Shaw has acknowledged the issue of
htmlLink requiring an existence check, i.e. at some point the
javascript error will be addressed.

*Jay has provided a work-around, for those looking to implement
a synonymous solution.

Please refer to comments below for additional information/clarifications.


text:
Q: How to handle the Direction of printing grid panel in ext.net I'm using a grid panel in my web page ..
i added a toolbar contains printing button in the grid panel to print the content of the grid view ..
the layout direction of the grid is from Right to Left (RTL) to be suitable with arabic ..
but when i press on the button (print) the grid direction appeared from left to right , which is not correct ..
< ext:Button ID="btnPrintPageGrid" runat="server" Text="طباعة الصفحة الحالية فقط" Icon="Printer" Handler="this.up('grid').print({currentPageOnly : true  });" />
i searched for any option to add to the functionality of the button , but i didn't find, also i tried to add (rtl : true) , but it doesn't work...
Any help ???

A: I use for printing ms report viewer and recommend you.
Make a qualitative report on the aspx page and show it in a frame in the pop up window.
And there is alignment problems do not happen.
Or build report as html and also insert it into the frame.
Here is working sample: http://jsfiddle.net/D4K3E/1/,
here is the code:
ShowPrintWindow = function (frameUrl, title, width, height, hidePrintButton) {
    height = height ? height : 509;
    width = width ? width : 675;
    if (typeof (title) == 'undefined') title = 'Печать';
    var win = Ext.create('Ext.window.Window', {
        id: 'printWindow',
        width: width,
        height: height,
        autoDestroy: true,
        title: title,
        iconCls: 'icon-printer',
        modal: true,
        items: [{
            border: false,
            html: '<iframe id="printFrame" src="' +
            frameUrl +
            '" width="' +
            (width - 12) +
            '" height="' +
            (height - 61) +
            '" frameborder="0"></iframe>'
        }],
        layout: 'fit',
        buttons: [{
            iconCls: 'icon-printer',
            text: 'Print',
            hidden: hidePrintButton ? true : false,
            listeners: {
                click: {
                    fn: function (item, e) {
                        printIframe('printFrame');
                    }
                }
            }
        }, {
            text: 'Close',
            listeners: {
                click: {
                    fn: function (item, e) {
                        Ext.getCmp('printWindow').close();
                    }
                }
            }
        }]
    }).show();
};

function printIframe(id) {
    var iframe = document.frames ? document.frames[id] : document.getElementById(id);
    var ifWin = iframe.contentWindow || iframe;
    iframe.focus();
    ifWin.print();
    return false;
}


text:
Q: why there is error when i use the overload i'm using boost::asio, i want to know why there is error when i use different overload;
```
#include<boost/asio.hpp>
using namespace boost::asio;
int main(int argc,char* argv[]){
    io_service ios;
    ip::tcp::acceptor acc(ios);
}
```

it can run when i use the command"g++ -o server server.cpp -lboost_system -lboost_thread -lpthread"
there is another situation:
```
#include<boost/asio.hpp>
using namespace boost::asio;
int main(int argc,char* argv[]){
    io_service ios();
    ip::tcp::acceptor acc(ios);
}
```

it cant run and there is the errorinfo:
In file included from /usr/include/boost/asio/executor.hpp:338,
                 from /usr/include/boost/asio/basic_socket.hpp:27,
                 from /usr/include/boost/asio/basic_datagram_socket.hpp:20,
                 from /usr/include/boost/asio.hpp:24,
                 from server.cpp:1:
/usr/include/boost/asio/impl/executor.hpp: In instantiation of 'boost::asio::execution_context& boost::asio::executor::impl< <template-parameter-1-1>, <template-parameter-1-2> >::context() [with Executor = boost::asio::io_context (*)(); Allocator = std::allocator<void>]':
/usr/include/boost/asio/impl/executor.hpp:177:22:   required from here
/usr/include/boost/asio/impl/executor.hpp:179:22: error: request for member 'context' in '((boost::asio::executor::impl<boost::asio::io_context (*)(), std::allocator<void> >*)this)->boost::asio::executor::impl<boost::asio::io_context (*)(), std::allocator<void> >::executor_', which is of non-class type 'boost::asio::io_context (*)()'
  179 |     return executor_.context();
      |            ~~~~~~~~~~^~~~~~~

A: io_service ios();

This declares a function called ios returning io_service. This is known as the "Most Vexing Parse".
Either use {} instead of () (since C++11) or just leave the parentheses.


text:
Q: How to create Pandas DataFrame with single values from another DataFrame? I'm about to learn python. I hope this is not a stupid question but I could really need some help with this:
I have the following DataFrame "df_sales_2016_us" with 2935 entries. This is the head.
        Gender  Country     Size (US)   year    Month
7610    Female  United States   8.0     2016    1
7613    Female  United States   9.0     2016    1
7617    Male    United States   9.5     2016    1
7618    Female  United States   10.5    2016    1
7619    Male    United States   8.5     2016    1

"Month" contains values from 1 to 12 for each month.
"Size (US") contains 16 different shoe size from 6.0 to 15
I would now like to create a new DataFrame looking like this:

*

*The columns are the Month from 1 to 12 while the rows are the different shoe sizes from 6.0 to 15.

*The single values should be the number of shoes for each size sold in each month.

How can I achieve this? This a table created with the value "0" just to clearify my goal.
        1   2   3   4   5   6   7   8   9   10  11  12
6.0     0   0   0   0   0   0   0   0   0   0   0   0
6.5     0   0   0   0   0   0   0   0   0   0   0   0
7.0     0   0   0   0   0   0   0   0   0   0   0   0
7.5     0   0   0   0   0   0   0   0   0   0   0   0
8.0     0   0   0   0   0   0   0   0   0   0   0   0
8.5     0   0   0   0   0   0   0   0   0   0   0   0
9.0     0   0   0   0   0   0   0   0   0   0   0   0
9.5     0   0   0   0   0   0   0   0   0   0   0   0
10.0    0   0   0   0   0   0   0   0   0   0   0   0
10.5    0   0   0   0   0   0   0   0   0   0   0   0
11.0    0   0   0   0   0   0   0   0   0   0   0   0
11.5    0   0   0   0   0   0   0   0   0   0   0   0
12.0    0   0   0   0   0   0   0   0   0   0   0   0
13.0    0   0   0   0   0   0   0   0   0   0   0   0
14.0    0   0   0   0   0   0   0   0   0   0   0   0
15.0    0   0   0   0   0   0   0   0   0   0   0   0

I tried to create the following DataFrame df_test, but I am out of options to proceed and think this is a totally wrong approach. (Here as an example only for "Month" "1"). Is there any option to get only the specific value needed for each column/row?
df_test = pd.DataFrame({'1':[df_sales_2016_us["Month"]==1],
                        '2':[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                        '3':[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                        '4': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                        '5': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                        '6': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                        '7': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                        '8': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                        '9': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                        '10': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                        '11': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                        '12': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
                       }, index=[df_sales_2016_us["Size (US)"].unique()])

df_test.sort_index()

The result for the way above is of course the following table as my approach does not get the single values needed but just informs, if "Month" is "1". But I have no idea how to go on from here or how to switch to another way to solve this. If someone would have an idea for this I would be very grateful. Thank you so much!
                                      1     2   3   4   5   6   7   8   9   10  11  12
6.0     7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
6.5     7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
7.0     7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
7.5     7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
8.0     7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
8.5     7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
9.0     7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
9.5     7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
10.0    7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
10.5    7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
11.0    7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
11.5    7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
12.0    7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
13.0    7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
14.0    7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0
15.0    7617 True 7619 True 7629 True 7...  0   0   0   0   0   0   0   0   0   0   0

A: You can do pd.crosstab:
pd.crosstab(df['Size (US)'], df['Month'])

If you want to count the sales by gender, you can do that too:
pd.crosstab([df['Gender'], df['Size (US)']], df['Month'])


text:
Q: Python SKLearn: Logistic Regression Probabilities I am using the Python SKLearn module to perform logistic regression. I have a dependent variable vector Y (taking values from 1 of M classes) and independent variable matrix X (with N features). My code is
        LR = LogisticRegression()
        LR.fit(X,np.resize(Y,(len(Y))))

My question is, what does LR.coef_ and LR.intercept_ represent. I initially thought they held the values intercept(i) and coef(i,j) s.t.
log(p(1)/(1-p(1))) = intercept(1) + coef(1,1)*X1 + ... coef(1,N)*XN
.
.
.
log(p(M)/(1-p(M))) = intercept(M) + coef(M,1)*X1 + ... coef(M,N)*XN

where p(i) is the probability that observation with features [X1, ... ,XN] is in class i. However when I try to convert
V = X*LR.coef_.transpose()
U = V + LR.intercept_
A = np.exp(U)
A/(1+A)

so that A is the matrix of p(1) ... p(M) for the observations in X. This should be the same value as
LR.predict_proba(X)

however they are close, but different. Why is this?

A: The coef_ and intercept_ attributes represent what you think, your probability calculations are off because you forgot to normalize: after
P = A / (1 + A)

you should do
P /= P.sum(axis=1).reshape((-1, 1))

to reproduce the scikit-learn algorithm.


text:
Q: Find elements with same date and sum values in array I have an array of objects with example values
[
    {name:"Name1",date:"2018-08-01", optimalValue:"33", realValue:"55"},
    {name:"Name2",date:"2018-08-03", optimalValue:"17", realValue:"23"},
    {name:"Name3",date:"2018-08-01", optimalValue:"23", realValue:"12"},
    {name:"Name4",date:"2018-08-04", optimalValue:"12", realValue:"11"},
]

I want to find in this array element with same date and sum values in optimalValue and realValue and have similar array like this:
[
    {date:"2018-08-01", optimalValue:"56", realValue:"77"},
    {date:"2018-08-03", optimalValue:"17", realValue:"23"},
    {date:"2018-08-04", optimalValue:"12", realValue:"11"},
]

A: Just use a hashtable to find / group duplicates:
const hash = {}, result = [];

for(const { date, name, optimalValue, realValue } of input) {
  if(!hash[date])
      result.push(hash[date] = { date, name, optimalValue: 0, realValue: 0 });
  hash[date].realValue +=+ realValue;
  hash[date].optimalValue +=+ optimalValue;
}

A: You can use the function reduce for grouping and sum the values and the function Object.values to extract the desired array.

let array = [{name:"Name1",date:"2018-08-01", optimalValue:"33", realValue:"55"},{name:"Name2",date:"2018-08-03", optimalValue:"17", realValue:"23"},{name:"Name3",date:"2018-08-01", optimalValue:"23", realValue:"12"},{name:"Name4",date:"2018-08-04", optimalValue:"12", realValue:"11"},],
    result = Object.values(array.reduce((a, {name, date, optimalValue, realValue}) => {
      a[date] = (a[date] || {date, optimalValue: 0, realValue: 0});
      a[date].realValue = String(Number(a[date].realValue) + Number(realValue));
      a[date].optimalValue = String(Number(a[date].optimalValue) + Number(optimalValue));
      return a;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You can use Array.reduce() for that. Since you require optimalValue and realValue as a string type, you can convert those into string after summing up the value using parseInt():

var arr = [
{name:"Name1",date:"2018-08-01", optimalValue:"33", realValue:"55"},
{name:"Name2",date:"2018-08-03", optimalValue:"17", realValue:"23"},
{name:"Name3",date:"2018-08-01", optimalValue:"23", realValue:"12"},
{name:"Name4",date:"2018-08-04", optimalValue:"12", realValue:"11"},
];

var res = arr.reduce((acc, obj)=>{
  var existObj = acc.find(item => item.date === obj.date);
  if(existObj){
    existObj.realValue = (parseInt(existObj.realValue) + parseInt(obj.realValue)).toString();
     existObj.optimalValue = (parseInt(existObj.optimalValue) + parseInt(obj.optimalValue)).toString();
    return acc;
  }
  acc.push(obj);
  return acc;
},[]);
console.log(res);


text:
Q: Fill in null values using previous value using FIRST_VALUE or LAST_VALUE I am having a problem with filling in blank values using previous not null values.
I have tried using the FIRST_VALUE and LAST_VALUE formula, but I dont quite manage to get the desired results.
Here is an query with example data and what I have been trying to do.
WITH test_data AS  (
SELECT 'A10-79' AS target_group, '2020w1' AS week, 'TV' AS placement, 10.1 AS views UNION ALL
SELECT NULL,  '2020w2', 'TV', 0.3 UNION ALL
SELECT Null,  '2020w3', 'TV', 4.3 UNION ALL
SELECT Null,  '2020w4', 'TV', 5.1 UNION ALL
SELECT 'A40-79', '2020w1', 'TV', 7.1 AS views UNION ALL
SELECT NULL,  '2020w2', 'TV', 0.1 UNION ALL
SELECT Null,  '2020w3', 'TV', 2.3 UNION ALL
SELECT Null,  '2020w4', 'TV', 3.1
)

SELECT
FIRST_VALUE(target_group IGNORE NULLS) OVER (ORDER BY week ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW) AS target_group,
week,
placement,
views
FROM test_data

And this produces this result

And this is what I would like to get

The problem is that I cant seem to find a way where it will fill in just the blanks with the previous or first value, and not overwrite every field.

A: Ideally, you would try to improve your source data, as it is unlikely you can guarantee that unlabeled data would always be in the proper order.
However, in the spirit of answering the question, please consider the following:
WITH test_data AS  (
SELECT 'A10-79' AS target_group, '2020w1' AS week, 'TV' AS placement, 10.1 AS views UNION ALL
SELECT NULL,  '2020w2', 'TV', 0.3 UNION ALL
SELECT Null,  '2020w3', 'TV', 4.3 UNION ALL
SELECT Null,  '2020w4', 'TV', 5.1 UNION ALL
SELECT 'A40-79', '2020w1', 'TV', 7.1 AS views UNION ALL
SELECT NULL,  '2020w2', 'TV', 0.1 UNION ALL
SELECT Null,  '2020w3', 'TV', 2.3 UNION ALL
SELECT Null,  '2020w4', 'TV', 3.1
),
temp1 as (
    -- Let's add a row id since the source table has no underlying indication of ordering
    select *, row_number() over() as my_rn from test_data
),
temp2 as (
    -- Let's create some separation between the target groups
    select
        *,
        sum(case when target_group is null then 0 else 1 end) over (order by my_rn) as my_partition
    from temp1
)
-- Now we can fill in the missing values
select
    first_value(target_group ignore nulls) over (partition by my_partition order by my_rn) as target_group,
    week,
    placement,
    views
from temp2
order by 1,2


text:
Q: Running time Array#unshift vs Array#shift I expected the running time of Array#shift and Array#unshift both to be Θ(n). Reason being that the machine needs to loop through each array member and assign it to the key left or right to it.
In the case of Array#unshift, assuming that only one value is passed in as an argument and that there are lots of array members, I assumed that the value assignment for array[0] is not having a significant impact on the running time. In other words, when the number of array members is high and the number of variables passed into Array#unshift is low, I expected Array#shift and Array#unshift to have the same running time.
When running benchmarks on Ruby 2.1.2, these assumptions do not hold true. Why?
Code:
require 'benchmark'

GC.disable

number_of_elements = 25_600_000

a1 =[]
a2 = []
a3 = []
a4 = []
q1 = Queue.new
q2 = Queue.new

puts number_of_elements

number_of_elements.times do
  q1.enq(true)
  q2.enq(true)
  a1 << true
  a2 << true
  a3 << true
  a4 << true
end

number_of_operations = 1

Benchmark.bm do |bm|
  puts "Queue#enq('test')"
  bm.report do
    number_of_operations.times { q1.enq('test') }
  end

  puts "Queue#deq"
  bm.report do
    number_of_operations.times { q2.deq }
  end

  puts "Array#shift"
  bm.report do
    number_of_operations.times { a1.shift }
  end

  puts "Array#unshift"
  bm.report do
    number_of_operations.times { a2.unshift('test') }
  end

  puts "Array#pop"
  bm.report do
    number_of_operations.times { a3.pop }
  end

  puts "Array#<<"
  bm.report do
    number_of_operations.times { a4 << 'test' }
  end
end

Result:
25600000
       user     system      total        real
Queue#enq('test')
   0.000000   0.000000   0.000000 (  0.000006)
Queue#deq
   0.010000   0.020000   0.030000 (  0.029928)
Array#shift
   0.010000   0.020000   0.030000 (  0.032203)
Array#unshift
   0.080000   0.060000   0.140000 (  0.143272)
Array#pop
   0.000000   0.000000   0.000000 (  0.000004)
Array#<<
   0.000000   0.000000   0.000000 (  0.000007)

A: In MRI Ruby 2.1.2, unshift does realloc the array and copy it entirely:
              static VALUE
rb_ary_unshift_m(int argc, VALUE *argv, VALUE ary)
{
    long len = RARRAY_LEN(ary);

    [...]

    ary_ensure_room_for_unshift(ary, argc);
    ary_memcpy(ary, 0, argc, argv);
    ARY_SET_LEN(ary, len + argc);
    return ary;
}

shift apparently does not always do something like that:
              static VALUE
rb_ary_shift_m(int argc, VALUE *argv, VALUE ary)
{
    VALUE result;
    long n;

    [...]

    rb_ary_modify_check(ary);
    result = ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST);
    n = RARRAY_LEN(result);
    if (ARY_SHARED_P(ary)) {
        if (ARY_SHARED_OCCUPIED(ARY_SHARED(ary))) {
            ary_mem_clear(ary, 0, n);
        }
        ARY_INCREASE_PTR(ary, n);
    }
    else {
        RARRAY_PTR_USE(ary, ptr, {
            MEMMOVE(ptr, ptr + n, VALUE, RARRAY_LEN(ary)-n);
        }); /* WB: no new reference */
    }
    ARY_INCREASE_LEN(ary, -n);

    return result;
}


text:
Q: How can I read html with some rows with only one column? I am trying to read the following table:
http://unicode.org/emoji/charts/full-emoji-list.html
In order to do this I am triying with the following code:
pd.read_html('http://unicode.org/emoji/charts/full-emoji-list.html', skiprows=2, encoding="utf-8")[0]

The problem is that if I use skiprows the first two columns are skipped, but pick 3 columns as a header, and the other problem is that the header is multiple times on the table.
So how can read this, avoiding, the multiple headers, and columns with only one row?
Thanks

A: Try this
df = pd.read_html('http://unicode.org/emoji/charts/full-emoji-list.html',encoding="utf-8")[0]
df.columns = [i[2] for i in df.columns]

Now if you print df, it looks like this
                     №                                               Code           Browser  ...               DCM              KDDI                  CLDR Short Name
0                    1                                            U+1F600                 �  ...                 —                 —                    grinning face
1                    2                                            U+1F603                 �  ...               NaN               NaN      grinning face with big eyes
2                    3                                            U+1F604                 �  ...                 —                 —  grinning face with smiling eyes
3                    4                                            U+1F601                 �  ...               NaN               NaN   beaming face with smiling eyes
4                    5                                            U+1F606                 �  ...               NaN                 —          grinning squinting face
...                ...                                                ...               ...  ...               ...               ...                              ...
2063  subdivision-flag                                   subdivision-flag  subdivision-flag  ...  subdivision-flag  subdivision-flag                 subdivision-flag
2064                 №                                               Code           Browser  ...               DCM              KDDI                  CLDR Short Name
2065              1814  U+1F3F4 U+E0067 U+E0062 U+E0065 U+E006E U+E006...           �������        ...                 —                 —                    flag: England
2066              1815  U+1F3F4 U+E0067 U+E0062 U+E0073 U+E0063 U+E007...           �������        ...                 —                 —                   flag: Scotland
2067              1816  U+1F3F4 U+E0067 U+E0062 U+E0077 U+E006C U+E007...           �������        ...                 —                 —                      flag: Wales

[2068 rows x 15 columns]


text:
Q: Loop through files in _posts subfolder - Jekyll I am using Prose.io as my CMS for github. In which I have set the root directory to /_posts. In /_posts I have made a folder "staticpages", this contains some markdown files with text. Can I loop through these files? I can't seem to figure out how.
So my file tree looks like:
root
   |
   _posts/
      |
      staticpages/
         |
         myfile.md

And I want to:
{% for pages in posts.staticpages %} {{ page.title }} {% endfor %}

A: Here you go:
In your _config.yml you specify
defaults:
  - scope:
      path: "_posts/staticpages"
    values:
      static: "true"

and in your layout file (or page) you filter the posts and loop with:
{% assign posts = site.posts | where:"static", "true" %}
{% for post in posts %}...

This works very well for me...

A: You can browse to a folder by setting it in the URL.
If the default URL is:

http://prose.io/#<account>/<repository>/

Then you can add the branch and folder relative path in the URL:

http://prose.io/#<account>/<repository>/tree/master/_posts/staticpages


text:
Q: SAS Define a Macro on a Unix Server Hi I'm trying to define and run a SAS Macro on a Unix Server.
options symbolgen mprint mlogic;
*options nosymbolgen nomprint nomlogic;

rsubmit;

%let trend_MM = 1;
%let run_date = &sysdate.;

/* loop through Trend_MM number of times to retrieve the MTR completed per each month. */
%macro Trend();
%local start_dt;
%local end_dt;
%local i;

/* loop through each month */
%do i = &Trend_MM. %to 0 %by -1;

/* Calculate set start/end dates to start/end of month */
%let start_dt = %qsysfunc(intnx(month,"&run_date."d,%eval(-1*&i.),b),date9.);
%let end_dt = %qsysfunc(intnx(month,"&run_date."d,%eval(-1*&i).,e),date9.);

    /* select MTR claims in month */
    proc sql;
        create table MTR_&i. as
        select a.claim_id_360
              ,a.claim_id_external
              ,a.timestamp
              /* v02: a) export date part of the timestamp */
              ,datepart(a.timestamp) as timestamp_dt
              ,a.status_data
              ,a.status_label
              ,a.RFE_template_name
              ,a.brand_name
              ,case when b.claim_id_360 is not missing then "Y" else "N" end as MTR_compl
              ,c.MTR_count
              ,b.last_MTR_comp format = ddmmyy10.
        from
            /* Base population are all claims where final status is not   */
            (
             select distinct *
             from allg360r._travel_rfe_state_change_hist
             (keep = claim_id_360 claim_id_external timestamp status_data status_label RFE_template_name brand_name)
             where datepart(timestamp) between "&start_dt."d and "&end_dt."d
             group by claim_id_360
             having timestamp = max(timestamp) and strip(upcase(status_label)) ne "Move to Review"
            ) a

            left join
        /*     subset with claims that have had a  status in the reference period to obtain  */
        /*     claims that have had such status completed in the period.                                     */
        /*     Also retrieve date of last MTR completed                                                      */
            (
             select distinct claim_id_360, datepart(timestamp) as last_MTR_comp
             from allg360r._travel_rfe_state_change_hist
             (keep = claim_id_360 claim_id_external timestamp status_data status_label RFE_template_name brand_name)
             where (datepart(timestamp) between "&start_dt."d and "&end_dt."d) and status_label = "Move to Review"
             group by claim_id_360
             having timestamp = max(timestamp)
            ) b
            on a.claim_id_360 = b.claim_id_360

            left join

        /*   Add count of how many since inception of claim  */
        /* v02: b) count how many times in MTR since beginning */
            (
             select distinct
                    claim_id_360
                   ,count(claim_id_360) as MTR_count
             from allg360r._travel_rfe_state_change_hist
             (keep = claim_id_360 claim_id_external timestamp status_data status_label RFE_template_name brand_name)
             where status_label = "Move to Review"
             group by claim_id_360
            ) C
            on a.claim_id_360 = c.claim_id_360
        ;
        quit;

    /* create/append to dataset of all months */

    %if &i. = &trend_MM. %then
      %do;
        proc sql;
            drop table work.MTR;
            create table work.MTR like work.MTR_&i.;
        quit;
      %end;

    proc append base = work.MTR data = work.MTR_&i.;
    run;
%end;

%mend Trend;

%trend

endrsubmit;

It seems to be working fine but I keep getting this error in the log:

995  endrsubmit;
       ----------
       180
ERROR 180-322: Statement is not valid or it is used out of proper
  order.

The error seems to disappear if I put a semicolon after the macro invocation. This doesn't make sense to me because the macro ends with a run; and putting a semicolon after invocation shouldn't make any difference.
Any ideas why this is happening?

A: The reason is - you defined your macro with brackets ()
Add some brackets to the invocation and it will execute without a semicolon.
%trend()

A: Believe it or not, because you defined your macro with an empty parameter list:
%macro Trend();
  %put TREND running;
%mend trend;

When you try to call the macro like %trend SAS is expecting you to send it a list of parameters, even an empty list will suffice.  So the macro call has not ended.  The semicolon will end the macro call, but you are right that it is not needed, an is a bad habit to add extra semicolons.  When you call a macro that has a parameter list  defined (even in this case, has 0 parameters the parentheses were on the macro definition so the list is still defined in some sense), you can invoke it like %trend() .  The parentheses end the macro call.
With PC SAS, you can test this nicely by highlighting just %trend and submitting it. The macro will not run. Then if you submit () the macro will run.
Update:
Since correcting the macro invocation didn't work, I suspect it may be a bug in how the word scanner recognizes the endrsubmit statement. Assuming it's replicable, I would probably add a comment which provides a semicolon. At least that way it's clear that the semicolon is not part of ending the macro invocation.  Sorry I can't test as don't have SAS/connect available.
Something like:
* endrsubmit needs a semicolon before it ??? ;
endrsubmit ;


text:
Q: How to solve the integral of $\frac 1{(x^2+1)^2}$ I need to evaluate
$$
\int_0^1 \dfrac 1{(x^2+1)^2}.
$$
I was absent for this lecture and I'm sort of lost on where to go.
I set $x = \tan (\theta)$ and $dx = \sec^2(\theta)\, d\theta$. And this implies that
$$x^2 + 1 = \tan^2(\theta) + 1 = \sec^2(\theta).$$
Now I have the integral of $\dfrac {\sec^2(\theta)}{(\sec^2\theta)^2}\, d\theta.$
I don't think I've done this properly, but if you could explain the process of doing trig substitutions in general, I would be greatly appreciative.

A: Your are on the right track, but be careful as you are doing definite integral, you need also to change the lower and upper limit.
Now $x = \tan \theta$. When $x = 0$, $\theta = 0$; when $x = 1$, $\theta = \frac{\pi}{4}$. So you have
$$\int_0^1 \frac{1}{(1+ x^2)^2} dx = \int_0^{\pi/4} \frac{\sec ^2 \theta}{(\sec ^2\theta)^2}d\theta = \int_0^{\pi/4} \frac{1}{\sec ^2\theta }d\theta = \int_0^{\pi/4} \cos^2\theta d\theta$$
Now use the half angle formula
$$\cos ^2\theta = \frac{1}{2} (1+ \cos(2\theta))$$
to get
$$\int_0^{\pi/4} \cos^2\theta d\theta = \frac{1}{2} \int_0^{\pi/4} \big(1  + \cos (2\theta)\big) d\theta.$$
Can you fill in the remaining steps?

A: You have almost done! What is $\dfrac{1}{\sec\theta}$? Is that equal to $\cos\theta$? So you need to take a definite integral of $\cos^2\theta$ on that interval. Moreover, I'd like to warn you for taking any substitution for definite integral so fast. Indeed, we should satisfy some important conditions to do any substitution easily. See Relation to the fundamental theorem of calculus again.

A: make a change of variable $$x = \tan t, t = \tan^{-1} x \to dt = \frac{dx}{1+x^2}   $$
$$\int_0^1 \frac{dx}{(1+x^2)^2} = \int_0^{\pi/4} \frac{dt}{1+ \tan^2 t} = \int_0^{\pi/4} \cos^2 t \,dt = \frac 12\int_0^{\pi/4} 1 + \cos 2t \, dt = \frac 12\left( \frac{\pi}{4} + \frac12\right)$$


text:
Q: Issue with rowSelector in ice faces I have a ice faces jspx page with the following structure
<ice:dataTable..>
  <ice:columns>
    <ice:rowSelector .../>
    <f:facet name="header">
      <ice:outputText ..../>
    </f:facet>
    <ice:outputText ...../>
  </ice:columns>
</ice:dataTable..>

On load of the page the following exception is thrown saying dataTable is not parent of rowSelector . But i have verified that the data table is the parent component of rowSelector .
Has anyone faced similar issue ? I could not find anything with this issue, that has a solution.
java.lang.RuntimeException: RowSelectorRenderer: decode. Could not find an Ice:dataTable as a parent componenent
        at com.icesoft.faces.component.ext.RowSelector.getParentDataTable(RowSelector.java:505)
        at com.icesoft.faces.component.ext.RowSelector.updateCurrentSelection(RowSelector.java:131)
        at com.icesoft.faces.component.ext.RowSelector.setValue(RowSelector.java:125)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at com.sun.facelets.tag.BeanPropertyTagRule$LiteralPropertyMetadata.applyMetadata(BeanPropertyTagRule.java:49)
        at com.sun.facelets.tag.MetadataImpl.applyMetadata(MetadataImpl.java:36)
        at com.sun.facelets.tag.MetaTagHandler.setAttributes(MetaTagHandler.java:62)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:144)
        at com.sun.facelets.tag.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:47)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:47)
        at com.sun.facelets.tag.ui.DefineHandler.applyDefinition(DefineHandler.java:64)
        at com.sun.facelets.tag.ui.DecorateHandler.apply(DecorateHandler.java:116)
        at com.sun.facelets.impl.DefaultFaceletContext$TemplateManager.apply(DefaultFaceletContext.java:337)
        at com.sun.facelets.impl.DefaultFaceletContext.includeDefinition(DefaultFaceletContext.java:307)
        at com.sun.facelets.tag.ui.InsertHandler.apply(InsertHandler.java:68)
        at com.sun.facelets.tag.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:47)
        at com.sun.facelets.tag.jsf.core.ViewHandler.apply(ViewHandler.java:109)
        at com.sun.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:49)
        at com.sun.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:25)
        at com.sun.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:248)
        at com.sun.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:294)
        at com.sun.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:273)
        at com.sun.facelets.impl.DefaultFaceletContext.includeFacelet(DefaultFaceletContext.java:140)
        at com.sun.facelets.tag.ui.DecorateHandler.apply(DecorateHandler.java:105)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.jsf.core.ViewHandler.apply(ViewHandler.java:109)
        at com.sun.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:49)
        at com.sun.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:25)
        at com.sun.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:248)
        at com.sun.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:294)
        at com.sun.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:273)
        at com.sun.facelets.impl.DefaultFaceletContext.includeFacelet(DefaultFaceletContext.java:140)
        at com.sun.facelets.tag.ui.IncludeHandler.apply(IncludeHandler.java:65)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:47)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:47)
        at com.sun.facelets.tag.ui.DefineHandler.applyDefinition(DefineHandler.java:64)
        at com.sun.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:131)
        at com.sun.facelets.impl.DefaultFaceletContext$TemplateManager.apply(DefaultFaceletContext.java:337)
        at com.sun.facelets.impl.DefaultFaceletContext.includeDefinition(DefaultFaceletContext.java:307)
        at com.sun.facelets.tag.ui.InsertHandler.apply(InsertHandler.java:68)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:47)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:47)
        at com.sun.facelets.tag.ui.DefineHandler.applyDefinition(DefineHandler.java:64)
        at com.sun.facelets.tag.ui.DecorateHandler.apply(DecorateHandler.java:116)
        at com.sun.facelets.impl.DefaultFaceletContext$TemplateManager.apply(DefaultFaceletContext.java:337)
        at com.sun.facelets.impl.DefaultFaceletContext.includeDefinition(DefaultFaceletContext.java:307)
        at com.sun.facelets.tag.ui.InsertHandler.apply(InsertHandler.java:68)
        at com.sun.facelets.tag.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:47)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:47)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:47)
        at com.sun.facelets.tag.jsf.ComponentHandler.applyNextHandler(ComponentHandler.java:314)
        at com.sun.facelets.tag.jsf.ComponentHandler.apply(ComponentHandler.java:169)
        at com.sun.facelets.tag.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:47)
        at com.sun.facelets.tag.jsf.core.ViewHandler.apply(ViewHandler.java:109)
        at com.sun.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:49)
        at com.sun.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:25)
        at com.sun.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:248)
        at com.sun.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:294)
        at com.sun.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:273)
        at com.sun.facelets.impl.DefaultFaceletContext.includeFacelet(DefaultFaceletContext.java:140)
        at com.sun.facelets.tag.ui.DecorateHandler.apply(DecorateHandler.java:105)
        at com.sun.facelets.tag.jsf.core.ViewHandler.apply(ViewHandler.java:109)
        at com.sun.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:49)
        at com.sun.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:25)
        at com.sun.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:248)
        at com.sun.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:294)
        at com.sun.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:273)
        at com.sun.facelets.impl.DefaultFaceletContext.includeFacelet(DefaultFaceletContext.java:140)
        at com.sun.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:113)
        at com.sun.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:49)
        at com.sun.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:25)
        at com.sun.facelets.impl.DefaultFacelet.apply(DefaultFacelet.java:95)
        at com.icesoft.faces.facelets.D2DFaceletViewHandler.renderResponse(D2DFaceletViewHandler.java:273)
        at com.icesoft.faces.application.D2DViewHandler.renderView(D2DViewHandler.java:155)
        at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:110)
        at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
        at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
        at com.icesoft.faces.webapp.http.core.JsfLifecycleExecutor.apply(JsfLifecycleExecutor.java:51)
        at com.icesoft.faces.context.View$2$1.respond(View.java:85)
        at com.icesoft.faces.webapp.http.servlet.ServletRequestResponse.respondWith(ServletRequestResponse.java:242)
        at com.icesoft.faces.context.View$2.serve(View.java:119)
        at com.icesoft.faces.context.View.servePage(View.java:192)
        at com.icesoft.faces.webapp.http.core.MultiViewServer.service(MultiViewServer.java:111)
        at com.icesoft.faces.webapp.http.common.ServerProxy.service(ServerProxy.java:43)
        at com.icesoft.faces.webapp.http.servlet.MainSessionBoundServlet$4.service(MainSessionBoundServlet.java:187)
        at com.icesoft.faces.webapp.http.servlet.BasicAdaptingServlet.service(BasicAdaptingServlet.java:51)
        at com.icesoft.faces.webapp.http.servlet.PathDispatcher.service(PathDispatcher.java:55)
        at com.icesoft.faces.webapp.http.servlet.SessionDispatcher.service(SessionDispatcher.java:100)
        at com.icesoft.faces.webapp.http.servlet.PathDispatcher.service(PathDispatcher.java:55)
        at com.icesoft.faces.webapp.http.servlet.MainServlet.service(MainServlet.java:205)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at com.adminserver.pas.web.helper.LoginFilter.doFilter(LoginFilter.java:95)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
        at java.lang.Thread.run(Thread.java:662)

A: Row selector sometimes cause problems with dynamic columns.
Try adding a fake ice:column and put the selector under that tag like suggested here.


text:
Q: Regex how to match an optional character in front of a greedy capture? I'm using python re. I have a string in the following format:
<root>.<entry_2>.<entry_3>.<entry_4>.<entry_5>...<entry_n>-<op_1>:<op_2>=<value>`

I would like to capture four groups: .<entry_2>.<entry_3>...<entry_n> in one group, <op_1> in a second group, <op_2> in a third group, and <value> in the fourth group. However, I would also like -<op_1> to be optional. So, if - doesn't exist, then the second group returns empty. My current matching expression is ^.+?(\..+)[-](.*):(.*)=(.*). But [-] and [:] require those characters in order to match. And making them optional forces the first capture to overrun the - and : characters if they do exist. Is there a better way to approach this?

A: >>> s = '<root>.<entry_2>.<entry_3>.<entry_4>.<entry_5>...<entry_10>-<op_1>:<op_2>=<value>'
>>> re.findall(r'(\.<entry_.*entry_\d+>)(?:-(<op_\d+>))?:(<op_\d+>)=(<[^>]+>)', s)
[('.<entry_2>.<entry_3>.<entry_4>.<entry_5>...<entry_10>', '<op_1>', '<op_2>', '<value>')]

>>> s = '<root>.<entry_2>.<entry_3>.<entry_4>.<entry_5>...<entry_10>:<op_2>=<value>'
>>> re.findall(r'(\.<entry_.*entry_\d+>)(?:-(<op_\d+>))?:(<op_\d+>)=(<[^>]+>)', s)
[('.<entry_2>.<entry_3>.<entry_4>.<entry_5>...<entry_10>', '', '<op_2>', '<value>')]

I have changed entry_n to entry_10 so that it has digits instead of n for the code snippet to work.
^\+spm_.+? isn't present in input sample, so I didn't include it, but you can add it if you need it
The four groups are:

*

*(\.<entry_.*entry_\d+>)

*(?:-(<op_\d+>))? --> optional group

*:(<op_\d+>)

*=(<[^>]+>)
You can also use re.search(r'pat', s).groups() but you will get None instead of empty string for the optional group. Forgot that you could change it, use .groups(default='') to get empty string instead of None


text:
Q: Bondal-Orlov Theorem I'm trying to read a proof of the reconstruction theorem by Bondal and Orlov asserting that an equivalence of derived categories of coherent sheaves $F:D^b(X)\cong D^b(Y)$ gives isomorphism between smooth projective schemes $X$ and $Y$ with (dual) canonical bundle ample. Precisely the one that can be found sketched here https://www.math.ucla.edu/~rouquier/papers/leeds.pdf (at p. 367).
Now, I mainly would like to ask for some references in order to understand this proof, because many things remain mysterious to me (I didn't even get where do we use some of the hypothesis we made on the schemes). Anyway I'll write down a first question that arose.
For a closed subset $Z\subseteq Y$ we set $D^b_Z(Y)$ the full subcategory of $D^b(X)$ of complexes with all cohomology sheaves supported in $Z$. I belive that $F^{-1}(D^b_Z(Y))$ is thick since the argument is, and clearly it's stable under the Serre functor $S_X=-\otimes\omega_X[dim(X)]$, since Serre functors commute with equivalences. But why this would imply that it is of the form $D_{\Phi(Z)}(X)$ for a closed $\Phi(Z)\subseteq X$? And why should $\Phi$ be injective between closed subsets of $Y$ into closed subsets of $X$?
Thanks in advance!


text:
Q: Getting Error in Jinja using in Django Project I am Facing an error in jinja while working on tables.
I have a model name HOD which uses user as foreign key and contains other details about Hod such as mobile no, department, year, etc.
Now I have a table in my html code in which I used jinja to load all hod details in the table using jinja for loop but I am unable to get first name and last name of hod.
This is my code:

    #
    First
    Last
    Department
    Year
    Mobile No

    {%for hod in hods%}

    {{hod.id}}
    {{user.hod.first_name}}
    {{user.hod.last_name}}
    {{hod.hod_of_department}}
    {{hod.hod_of_year}}
    {{hod.mobile_no}}

  {%endfor%}

A: You are trying to get firstname, lastname from the user which is not there:
{% for hod in hods %}

    {{hod.id}}
    {{hod.first_name}}
    {{hod.last_name}}
    {{hod.hod_of_department}}
    {{hod.hod_of_year}}
    {{hod.mobile_no}}

  {% endfor %}


text:
Q: tabBar.hidden = true not hiding complete tab bar it lefts white space in bottom of view I have 2 tab item in my tab bar controller, my requirement is to hide tab bar when user move to child screens (Other than root of each tab).
I have tried hidesBottomBarWhenPushed but some how its not working due to view hierarchy.
Also tabBar.hidden = true hiding the tab bar icon instead the complete tab bar. randomly it works when i scroll up down again and again the table view used on root view
self.tabBarController.tabBar.hidden = true;

I am calling this line before presenting the new view in (prepare for segue method)
On debug its seems tab bar is hidden but it left white space in bottom which remain there
Before - Normal

After tabBar.hidden = true

A: user bellow code to hide the tabbar. for example "Tab1 and Tab2" is two tabbars, if u r moving Tab1 to inside viewcontrollerA. U can write the bellow code in "viewcontrollerA"
 -(BOOL)hidesBottomBarWhenPushed
   {
      return YES;
    }


text:
Q: Request with Retrofit and RxJava giving error I'm developing an app that in the main activity there is a viewpager, 3 tabs load the content from the webservice, when I change quickly between the tabs, one request gets the body from another request, then I get 500 internal error, because the body of request is wrong.
I'm using retrofit and rxjava to make the requests, like below:
CustomApplication.getApi().appointmentList("application/json", userPrefs.getToken(), appointmentFilter)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<AppointmentInstanceList>() {
                @Override
                public void onCompleted() {
                    if (mProgressBar != null)
                        mProgressBar.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onError(Throwable e) {
                    if (mProgressBar != null)
                        mProgressBar.setVisibility(View.INVISIBLE);

                    showViewNoResults();

                    String message = getString(R.string.error_request);

                    if (e != null && e instanceof RetrofitError) {
                        RetrofitError retrofitError = (RetrofitError) e;
                        if (retrofitError.getKind() == RetrofitError.Kind.NETWORK) {
                            message = getString(R.string.error_network);
                        } else if (retrofitError.getKind() == RetrofitError.Kind.HTTP) {
                            message = getString(R.string.error_network);
                        }
                    }
                    Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onNext(AppointmentInstanceList appointmentList) {
                    appointmentListAdapter = new AppointmentListAdapter(getActivity(), appointmentList.appointmentInstanceList);
                    if (appointmentListView != null && appointmentListAdapter != null)
                        appointmentListView.setAdapter(appointmentListAdapter);

                    showViewNoResults();
                }
            });

Somebody knows how to fix this?
Thanks


text:
Q: JTextArea not selectable, but still showing a "ghost" cursor I put a JTextArea in a JPanel. This JPanel has a picture on the background, and the JTextArea is translucent (translucid red) to show the background through. I don't want the user to be able to edit or select the text, I want it to act just as a JLabel (but with multiple lines and easy to word wrap and adjust to screen resize).
I tried all these options:
text.setEditable(false);
text.setFocusable(false);
text.setEnabled(false);
text.setHighlighter(null);

but still some change of color happens as the user drags the mouse over the JTextArea. Anyone knows what is going on?

A: You can't simply set the background color of a component to "transparent" and expect Swing to deal with it.  You need to flag the component as transparent (setOpaque(false)), only then will Swing's repaint manager know that it has to update the components under it.
This then leads you to the problem of how to paint the background (as Swing only has the concept of fully opaque or fully transparent).
To do this, you need to supply your own paint routines (override paintComponent, fill the background, update the component)...this is essentially what Rob Camick's solution is doing, it just provides a nice wrapper component for you...
Below is an example of using a JLabel using text wrapped in HTML and a JTextArea, both updated to  support "translucency"...
Using a JLabel

Using a JTextArea

Now, it would be a lot easier to achieve using Rob's wrapper class, but this provides you with the idea of what is going wrong and what you would need to do to fix it.
public class MultiLineLabel {

    public static void main(String[] args) {
        new MultiLineLabel();
    }

    public MultiLineLabel() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new BackgroundPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TransclucentLabel extends JLabel {

        public TransclucentLabel(String text) {
            super(text);
            setVerticalAlignment(TOP);
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            Insets insets = getInsets();
            int x = insets.left;
            int y = insets.top;
            int width = getWidth() - (insets.left + insets.right);
            int height = getHeight() - (insets.top + insets.bottom);
            g2d.setColor(new Color(255, 0, 0, 128));
            g2d.fillRect(x, y, width, height);
            super.paintComponent(g);
        }
    }

    public class TransclucentTextArea extends JTextArea {

        public TransclucentTextArea(String text) {
            super(text);
            setOpaque(false);
            setLineWrap(true);
            setWrapStyleWord(true);
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            Insets insets = getInsets();
            int x = insets.left;
            int y = insets.top;
            int width = getWidth() - (insets.left + insets.right);
            int height = getHeight() - (insets.top + insets.bottom);
            g2d.setColor(new Color(255, 0, 0, 128));
            g2d.fillRect(x, y, width, height);
            super.paintComponent(g);
        }
    }

    public class BackgroundPane extends JPanel {

        private BufferedImage background;

        public BackgroundPane() {
            setLayout(new BorderLayout());
//            addLabel();
            addTextArea();
            setBorder(new EmptyBorder(24, 24, 24, 24));

            try {
                background = ImageIO.read(new File("/path/to/your/image"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        protected void addTextArea() {
            StringBuilder sb = new StringBuilder(128);
            sb.append("I put a JTextArea in a JPanel. This JPanel has a picture on the background, and the JTextArea is translucent (translucid red) to show the background through. I don't want the user to be able to edit or select the text, I want it to act just as a JLabel (but with multiple lines and easy to word wrap and adjust to screen resize).\n\n");
            sb.append("I tried all these options:\n\n");
            sb.append("text.setEditable(false);\n");
            sb.append("text.setFocusable(false);\n");
            sb.append("text.setEnabled(false);\n");
            sb.append("text.setHighlighter(null);\n\n");
            sb.append("but still some change of color happens as the user drags the mouse over the JTextArea. Anyone knows what is going on?\n");
            add(new TransclucentTextArea(sb.toString()));
        }

        protected void addLabel() {
            StringBuilder sb = new StringBuilder(128);
            sb.append("");
            sb.append("
I put a JTextArea in a JPanel. This JPanel has a picture on the background, and the JTextArea is translucent (translucid red) to show the background through. I don't want the user to be able to edit or select the text, I want it to act just as a JLabel (but with multiple lines and easy to word wrap and adjust to screen resize).

");
            sb.append("
I tried all these options:

");
            sb.append("
text.setEditable(false);
");
            sb.append("text.setFocusable(false);
");
            sb.append("text.setEnabled(false);
");
            sb.append("text.setHighlighter(null);

");
            sb.append("
but still some change of color happens as the user drags the mouse over the JTextArea. Anyone knows what is going on?
");
            add(new TransclucentLabel(sb.toString()));

        }

        @Override
        public Dimension getPreferredSize() {
            return background == null ? super.getPreferredSize() : new Dimension(background.getWidth(), background.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (background != null) {
                int x = (getWidth() - background.getWidth()) / 2;
                int y = (getHeight() - background.getHeight()) / 2;
                g.drawImage(background, x, y, this);
            }
        }
    }
}


text:
Q: Larger packets than Ethernet frame can handle IPv4 and IPv6 allow packets of up to 65,535 bytes.  Ethernet frames supposedly only allows payloads of up to 1522 bytes.
How does this work?  There are no sequence numbers in Ethernet frames to ensure order, which makes recreating a larger IP packet from Ethernet frames difficult...

A: Several points in bullet form:

*

*IP packets can be fragmented (see IP Fragmentation): the fragmentation and reassembly of IP datagrams is specified within IP.

*The layer encapsulating IP for a given flow may not necessarily be Ethernet from end to end (or even at all, see GRE)

*Path MTU is a means of determining the Maximum Transmission Unit for a given flow.

*Within a network, Jumbo Frames may be enabled to increase the ethernet frame size to 9000.


text:
Q: Bash, need to change word order in multiple directories I have a considerable classical FLAC collection where each album is a directory. I've realized that I have used a sub-optimal structure and need to rename all the directories.
My current naming convention is:
COMPOSER (CONDUCTOR) - NAME OF PIECE
E.g.
"Bach (Celibidache) - Mass in F minor"
I want to change the naming to
COMPOSER - NAME OF PIECE (CONDUCTOR)
I.e.
"Bach - Mass in F minor (Celibidache)"
There are some possible exceptions, the (CONDUCTOR) may be (CONDUCTOR, SOLOIST)  and some directories do not have the (CONDUCTOR) part and should be left as is. The NAME OF PIECE can contain all legal letters and symbols.
All albums are located in the same parent directory, so no sub-directories.
What is the easy way to do this?

A: use perl rename (some distributions have this as rename - Ubuntu and related, some as prename - Fedora and Redhat AFAIK). Check first.
prename -n -- '-d && s/(\(.*\)) - (.*)/- \2 \1/' *

*

*-n don't rename just print the results - remove after you are ok with the results.

*-- end of the options, start of the perlexpr and files

*-d check that the file is a directory

*s/.../.../ - substitution

Example:
[test01@localhost composers]$ ls -la
total 12
drwxrwxr-x  3 test01 test01 4096 Feb 14 12:37  .
drwxrwxr-x. 7 test01 test01 4096 Feb 14 12:23  ..
drwxrwxr-x  2 test01 test01 4096 Feb 14 12:37 'Bach (Celibidache) - Mass in F minor'
-rw-rw-r--  1 test01 test01    0 Feb 14 12:27 'Bach (Celibidache) - Mass in F minor.flac'
[test01@localhost composers]$ prename -n -- '-d && s/(\(.*\)) - (.*)/- \2 \1/' *
Bach (Celibidache) - Mass in F minor -> Bach - Mass in F minor (Celibidache)
[test01@localhost composers]$ prename -- '-d && s/(\(.*\)) - (.*)/- \2 \1/' *
[test01@localhost composers]$ ls -la
total 12
drwxrwxr-x  3 test01 test01 4096 Feb 14 12:38  .
drwxrwxr-x. 7 test01 test01 4096 Feb 14 12:23  ..
-rw-rw-r--  1 test01 test01    0 Feb 14 12:27 'Bach (Celibidache) - Mass in F minor.flac'
drwxrwxr-x  2 test01 test01 4096 Feb 14 12:37 'Bach - Mass in F minor (Celibidache)'

Note that without -d both the file and the directory would have been renamed.


text:
Q: FFMPEG using wrong arguements when refering to image files I am creating a bat file that will use FFMPEG to convert Real Media files to .MP4 files. I am looping though the current folder and finding files with the .rm extension adding several pictures to the video files to create a slide show effect in the final product.
With this code here it works except it only shows one static image:
for %%a in ("*.rm") do ffmpeg -f image2 -r 1/5 -i "img00.jpg" -i "%%a" -c:v libx264 -r 30 -preset slow -crf 20 -c:a libvo_aacenc -b:a 48k -b:v 16k "newfiles\%%~na.mp4"

With this code it should show a series of photos. However it does not:
for %%a in ("*.rm") do ffmpeg -f image2 -r 1/5 -i "img%02d.jpg" -i "%%a" -c:v libx264 -r 30 -preset slow -crf 20 -c:a libvo_aacenc -b:a 48k -b:v 16k "newfiles\%%~na.mp4"

I get this error when I run the second piece of code:

Could find no file with with path 'imgC:\Data\RealtoMP\FFMPEG_JPG\ffmpegA48V16_AudOnly' and index in the range 0-4
  imgC:\Data\RealtoMP\FFMPEG_JPG\ffmpegA48V16_AudOnly: No such file or directory

It appears to me that it is somehow instead of getting the range argument like it should, it's injecting the path to the file that I am running. Any ideas of what is causing this?
EDIT:
I fixed my problem by escaping the %02 with another %. The result is %%02 for it to act correctly in the script.

A: %0 in a batch file will expand to the path to the batch file.
In your second code sample you have a "img%02d.jpg" -- that will expand to "img + the path to your batch file + 2d.jpg".
When you can't figure out what a batch file is doing (especially when you have long command lines), I find it helpful to echo the command line instead of (or as well as) calling it directly.  That makes it much easier to see the problem yourself.  For example:
for %%a in ("*.rm") do (
    echo ffmpeg -f image2 -r 1/5 -i "img%02d.jpg" -i "%%a" -c:v libx264 -preset slow -crf 20 -c:a libvo_aacenc -b:a 48k -b:v 16k "newfiles\%%~na.mp4"
)

That prints out the command line instead of calling it directly, and you would immediately see where the command line is not what you expect it to be. Tweak the code until the output looks right, then remove the echo.