text:
Q: PHP session variable within other variable I have a page (cart page in ecommerce) with some data id like to access via PHP so I can mail it.
When I print all session variables using print_r( $_SESSION ); I get the following code.
I want to echo the value of "total".
I am using $_SESSION['cart']['total']; but it doesn't work.
All other outputs like "currency" and "language" are displayed as they should be.
What am I doing wrong here?
array(22) {
  ["sessiontoken"]=>
  &string(32) "2239f469b65f039885a0c747f6595609"
  ["cart"]=>
  &object(shoppingCart)#1 (5) {
    ["contents"]=>
    array(2) {
      [216]=>
      array(1) {
        ["qty"]=>
        int(1)
      }
      [71]=>
      array(1) {
        ["qty"]=>
        int(1)
      }
    }
    ["total"]=>
    float(115.9)
    ["weight"]=>
    float(0)
    ["cartID"]=>
    &string(5) "91586"
    ["content_type"]=>
    string(8) "physical"
  }
  ["language"]=>
  &string(7) "english"
  ["languages_id"]=>
  &string(1) "1"
  ["currency"]=>
  &string(3) "USD"
  ["navigation"]=>
  &object(navigationHistory)#2 (2) {
    ["path"]=>
    array(5) {
      [0]=>
      array(4) {
        ["page"]=>
        string(9) "index.php"
        ["mode"]=>
        string(6) "NONSSL"
        ["get"]=>
        array(1) {
          ["cPath"]=>
          string(2) "50"
        }
        ["post"]=>
        array(0) {
        }
      }
      [1]=>
      array(4) {
        ["page"]=>
        string(7) "404.php"
        ["mode"]=>
        string(6) "NONSSL"
        ["get"]=>
        array(0) {
        }
        ["post"]=>
        array(0) {
        }
      }
      [2]=>
      array(4) {
        ["page"]=>
        string(21) "checkout_shipping.php"
        ["mode"]=>
        string(3) "SSL"
        ["get"]=>
        array(0) {
        }
        ["post"]=>
        array(15) {
          ["formid"]=>
          string(32) "2239f469b65f039885a0c747f6595609"
          ["action"]=>
          string(7) "process"
          ["payment"]=>
          string(5) "gspay"
          ["shipping"]=>
          string(9) "flat_flat"
          ["hd_shipping"]=>
          string(5) "12.00"
          ["hd_std_shipping"]=>
          string(5) "29.00"
          ["cust_fname"]=>
          string(1) "k"
          ["cust_lname"]=>
          string(1) "k"
          ["cust_email"]=>
          string(10) "kk@kkk.xom"
          ["cust_street"]=>
          string(3) "kkk"
          ["cust_city"]=>
          string(3) "kkk"
          ["cust_state"]=>
          string(3) "kkk"
          ["cust_zip"]=>
          string(3) "222"
          ["country"]=>
          string(2) "72"
          ["btnSubmit"]=>
          string(20) "Continue to checkout"
        }
      }
      [3]=>
      array(4) {
        ["page"]=>
        string(20) "checkout_payment.php"
        ["mode"]=>
        string(3) "SSL"
        ["get"]=>
        array(0) {
        }
        ["post"]=>
        array(0) {
        }
      }
      [4]=>
      array(4) {
        ["page"]=>
        string(25) "checkout_confirmation.php"
        ["mode"]=>
        string(3) "SSL"
        ["get"]=>
        array(0) {
        }
        ["post"]=>
        array(2) {
          ["formid"]=>
          string(32) "2239f469b65f039885a0c747f6595609"
          ["payment"]=>
          string(5) "gspay"
        }
      }
    }
    ["snapshot"]=>
    array(0) {
    }
  }
  ["user_type"]=>
  &string(5) "guest"
  ["sendto"]=>
  &NULL
  ["cartID"]=>
  &string(5) "91586"
  ["payment"]=>
  &string(5) "gspay"
  ["comments"]=>
  &NULL
  ["shipping"]=>
  &array(3) {
    ["id"]=>
    string(9) "flat_flat"
    ["title"]=>
    string(53) "Global Priority Shipping (It takes 5-7 business days)"
    ["cost"]=>
    string(5) "12.00"
  }
  ["cust_fname"]=>
  &string(1) "k"
  ["cust_lname"]=>
  &string(1) "k"
  ["cust_email"]=>
  &string(10) "kk@kkk.xom"
  ["cust_street"]=>
  &string(3) "kkk"
  ["cust_city"]=>
  &string(3) "kkk"
  ["cust_state"]=>
  &string(3) "kkk"
  ["cust_zip"]=>
  &string(3) "222"
  ["cust_country"]=>
  &string(2) "72"
  ["cust_country_title"]=>
  &string(7) "Finland"
  ["billto"]=>
  &NULL
}

A: Looks like cart is an object.
So, you should be able to access it via:
$_SESSION['cart']->total;

A: $_SESSION['cart'] is an object, then total is it's property:
$total = $_SESSION['cart']->total;

A: cart is an object so it should be something like
 $_SESSION['cart']->total;

or if total is private or the corresponding class doesn't have a magic getter __get(); that could do it (or check the Class API for the public method name that returns $this->total;):
 $_SESSION['cart']->getTotal();

A: From your output,
["cart"]=>
  &object(shoppingCart)#1 (5) {
    ...
    }
    ["total"]=>    float(115.9)

The value $_SESSION['cart'] is a PHP Object. You should access the total using:
$_SESSION['cart']->total;


text:
Q: How was MAV fuel plant able to make fuel using hydrogen so quickly in the end? In The Martian (by Andy Weir) book, MAV fuel plant was able to make fuel using Martian atmosphere, but the process was slow. From Chapter 1:

The most important piece of the advance supplies, of course, was the MAV. The Mars ascent vehicle. That was how we would get back to Hermes after surface operations were complete. The MAV was soft-landed (as opposed to the balloon bounce-fest the other supplies had). Of course, it was in constant communication with Houston, and if there had been any problem with it, we would have passed by Mars and gone home without ever landing.
The MAV is pretty cool. Turns out, through a neat set of chemical reactions with the Martian atmosphere, for every kilogram of hydrogen you bring to Mars, you can make thirteen kilograms of fuel. It's a slow process, though. It takes twenty-four months to fill the tank. That's why they sent it long before we got here.

Just before Ares 3 crew landed, Martinez remotely landed MAV to Ares 4 site. Mark Watney reached Ares 4 site after about 1.5 years (i.e. less than 24 months). It means Ares 4 MAV didn't make fuel out of even all hydrogen on-board. Yet, NASA ordered Mark Watney to give MAV more hydrogen. From Chapter 25:

[13:07] HOUSTON: Congratulations from all of us here at Mission Control! Well done! What's your status?
  [13:21] MAV: Thanks! No health or physical problems. The rover and trailer are getting pretty worn out, but still functional. Oxygenator and regulator both working fine. I didn't bring the water reclaimer. Just brought the water. Plenty of potatoes left. I'm good to last till 549.
  [13:36] HOUSTON: Glad to hear it. Hermes is still on track for a Sol 549 flyby. As you know, the MAV will need to lose some weight to make the intercept. We're going to get you those procedures within the day. How much water do you have? What did you do with urine?
  [13:50] MAV: I have 550 liters of remaining water. I've been dumping urine outside along the way.
  [14:05] HOUSTON: Preserve all water. Don't do any more urine dumps. Store it somewhere. Turn the rover's radio on and leave it on. We can contact it through the MAV.

Later in Chapter 25:

Venkat flipped through the pages. "Care to summarize?"
  "First, we're going to add fuel. The MAV makes its own fuel from the Martian atmosphere, but it's limited by how much hydrogen it has. It brought enough to make 19,397 kilograms of fuel, as it was designed to do. If we can give it more hydrogen, it can make more."
  "How much more?"
  "For every kilogram of hydrogen, it can make thirteen kilograms of fuel. Watney has five hundred and fifty liters of water. We'll have him electrolyze it to get sixty kilograms of hydrogen." Bruce reached over the desk and flipped a few pages, pointing to diagram. "The fuel plant can make seven hundred and eighty kilograms of fuel from that."

On Sol 529, Mark Watney did start the process of converting water into rocket fuel, by supplying fuel plant extra hydrogen. But, MAV took flight on Sol 549 i.e. after 20 Sols. First, MAV hadn't yet converted existing hydrogen to fuel and Mark added extra 60Kg of hydrogen. How was MAV fuel plant able to do hundreds of Sols of work within 20 Sols? Did I miss something? Or, is it a plot hole (I am less inclined to expect this because of scientific accuracies of the book)?

A: The book is inconsistent.  On page 65 we see:

It takes eighteen months for the MAV to make its fuel, so it's the first thing NASA sends along. Sending it forty-eight months early gives it plenty of extra time in case fuel reactions go slower than expected.

Here's a possible in-universe explanation:  He says 24 months on Sol 6 (in his very first log entry).  He says 18 months on Sol 63, by which time he's had a chance for a focused review of all the tech specs on his computer for all his equipment (in order to plan his survival).  So on Sol 6 Mark just misremembered it.  It's understandable, he was in pain and in shock:

I'm pretty much fucked. That's my considered opinion.  Fucked.

(Not quite as good a first line as "Call me Ishmael" but not bad either.)

A: MOAR Pirate Ninjas!
Lets recap. The MAV is sent on ahead to make rocket fuel. It does this by taking a "kilogram of hydrogen you bring to Mars, you can make thirteen kilograms of fuel." Let's dwell on that a second.
Either the MAV is directly converting energy into mass...or it is using martian chemicals to make up the other 12 kg of mass.
However we have already noted that Mars does not have a local chemist, stocked with canisters of chemicals.

Remember the MAV fuel plant? It collects CO2 from the Martian atmosphere. A 10-liter tank of compressed liquid CO2... That'll take less than a day to create.

However it is pretty clear without even doing simple calculations that the 0.1 Pirate-Ninjas that the MAV's original power plant (the RTG) has, is incapable of compressing that much CO2, from PURE CO2 at Standard Martian Temperature Pressure.
Therefore the main difference is that by hooking up the two Rovers worth of solar cells plus the battery plus the 2 RTGs, the MAV fuel plant would be able to get many more Pirate-Ninjas and much faster to complete its task of compressing 12kg of CO2.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Relation between EM scalar potential and EM vector potential I am doing caculation using $\phi$ and $\mathbf{A}$, however I can't find the relation between $\phi$ and $\mathbf{A}$. For E and B we have
\begin{align}
\frac{{{d^2}E\left( x \right)}}{{d{x^2}}} + \frac{{{\omega ^2}}}{{{c^2}}}E\left( x \right) &= 0\\
\frac{{{d^2}B\left( x \right)}}{{d{x^2}}} + \frac{{{\omega ^2}}}{{{c^2}}}B\left( x \right) &= 0
\end{align}
in vacuum for 1-D case. Given $E(0) = E_0$ and $E'(0) = ik E_0$, the solution for E is $E(x) = E_0 e^{ikx}$. And we can find solution for B is $B(x) = \frac{E_0}{c} e^{ikx} $ for there is $|E|=c|B|$ in SI unit.
But I can't find the realtion between $A$ and $\phi$ similar to E and B for
\begin{align}
\frac{1}{c^2}\frac{\partial^2\varphi}{\partial t^2} - \nabla^2{\varphi}  &= 0\\
\frac{1}{c^2}\frac{\partial^2\mathbf A}{\partial t^2} - \nabla^2{\mathbf A} &= 0
\end{align}
using Lorenz gauge.
What is the relation between $A$ and $\phi$ besides gauge condition?

A:
What is the relation between A and ϕ besides gauge condition?

Maxwell's equations in vacuum are, in terms of $\phi$ and $\mathbf{A}$:
$$\nabla^2\phi + \frac{\partial}{\partial t}\left(\nabla \cdot \mathbf{A}\right) = 0$$
$$\left(\nabla^2 \mathbf{A} -  \frac{1}{c^2}\frac{\partial^2\mathbf{A}}{\partial t^2}\right) - \nabla\left(\nabla \cdot \mathbf{A} +  \frac{1}{c^2}\frac{\partial\phi}{\partial t}\right) = 0 $$
Since $\frac{\partial\phi}{\partial t}$ and $\nabla \cdot \mathbf{A}$ are gauge degrees of freedom, it looks like the answer to your question is none.

A: If ${\bf A}$ satisfies a homogeneous wave equation of the form suggested, then
$${\bf A} = {\bf A_0} f({\bf k}\cdot {\bf r} - \omega t)$$
is a solution, with $\omega/k=c$.
In that case, I think that you can write
$$ \phi = \frac{c^2}{\omega} {\bf k}\cdot {\bf A} = \frac{c^2}{\omega} {\bf k}\cdot {\bf A_0}f,$$
which is also a solution to the homogeneous wave equation for $\phi$ and satisfies the Lorenz gauge. i.e.
$$\nabla \cdot {\bf A} = {\bf k}\cdot {\bf A_0} f'$$
and
$$-\frac{1}{c^2}\frac{\partial \phi}{\partial t} = -\frac{1}{c^2} \frac{c^2}{\omega}{\bf k}\cdot {\bf A_0}(-\omega f') = {\bf k}\cdot {\bf A_0}f'   $$
So your answer appears to be
$$ \phi = \frac{c^2}{\omega} {\bf k}\cdot {\bf A}$$


text:
Q: Making an android app for a website I'm trying to make an app for website that I DO NOT OWN OR HAVE ACCESS TO ITS DB.
The website is a forum community website and I wish make an app that can list the menu and the posts in a UI suited for mobile.
Also I am trying to see if I add real time notice function that will let the thread poster know when there is a new comment/post to his or her thread. (Website does not support this function)
Do you guys think I can achieve this through Jsoup or would I need other utilities too?
Also I am quite a beginner in java so the app cannot be too complicated.
Thanks.

A: It means that you want to write your own web browser! You need to call the Url get what it returns, parse it and show it... also you need to implement RSS to specific pages.. It means app need to call this url regularly and check if any changes or comments... Its do-able but wont really be efficient or bug-free... I wouldnt recommend it but as i sad do-able


text:
Q: How do I pass my object between 2 requests? Where server is stateless? How do I pass my object between 2 requests? Where server is stateless, hence session cannot be used. Request object access is not there in controller class.Left with caching or using cookies, but is that a good way? since cookies do not allow objects and i will have to copy strings individually, which can make cookies huge.
I haven't explored caching much although.
Any guidance please?
Framework : Spring 3


text:
Q: How to search for pattern in multiple lines using a regular expression Consider the pattern is:
PPP(GJ)  {
           __hj_o:
         }

What is the regular expression match the above pattern?

A: Tcl's regular expressions can contain newlines just fine, but for anything complicated it can help to put it in its own variable instead of having it as an inline literal:
set RE {PPP(GJ)  {
           __hj_o:
         }}

if {[regexp $RE $someString]} {
    # We got a match!
}

Indeed, regexp would also match the above with this:
set RE {PPP(GJ)\s+{\s+__hj_o:\s+}}

because newlines are just ordinary whitespace characters (i.e., are matched by \s and .) by default. (The above REs are probably not exactly what you want; they likely need suitable patterns for the non-whitespace portions as well.)
However, you need to ensure that the string you are matching against has the whole thing that you want to match. If you're just feeding through one line at a time, that multiline pattern will consistently fail. This sounds obvious, but it is the easiest mistake to make.


text:
Q: Force Automapper to use ConstructUsing even if nested entity is already created Please suppose my domain
public class Customer : Entity
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Image Photo { get; set;}
    public int PhotoId { get; set; }
}

public class Image : Entity
{
    public int Id { get; set; }
    public byte[] Content { get; set; }
}

Now suppose my models
public class CustomerModel : EntityModel
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ImageModel Photo { get; set;}
    public int PhotoId { get; set; }
}

public class ImageModel : EntityModel
{
    public int Id { get; set; }
    public byte[] Content { get; set; }
}

Suppose I have this customer on the database, attached to a DBContext:
customer = {
    Id : 1,
    Name : "Alexandre",
    PhotoId: 13,
    Photo : {
        Id: 13,
        Content: ABC
    }
}

and this model (posted by the user from a browser):
customerModel = {
    Id : 1,
    Name : "Alexandre",
    PhotoId: 0,
    Photo : {
        Id: 0,
        Content: XYZ
    }
}

So, how you can see, the user creates a new photo (Id == 0) that is not still saved to the database, and I will replace it on the entity.
The problem is : If I call
Mapper.Map(customerModel, customer)

AutoMapper will map customerModel.Photo from customer.Photo, instead of creates a new one, and entity framework will raise an exception because I can't change the PK of my image object.
Also, I can't just do
customer.Photo = null

before map the objects because my mapping are generics, and base classes does not knows structure of these objects. This is a very big application with many entities, I don't want execute this code for every nested property on every entity.
So I need something more genereic...
What I want: AutoMapper must to knows that these Photos are not the same (by comparing Ids) and so creates a new one instead of replace the same.
Is that possible?

A: This map forces the creation of new Image object accordingly to Id comparison:
Mapper.CreateMap<CustomerModel, Customer>()
    .BeforeMap((src, dest) =>
        dest.Photo = dest.Photo.Id != src.Photo.Id ? new Image() : dest.Photo);

EDIT: more generic approach:
Mapper.CreateMap<CustomerModel, Customer>().BeforeMap(Action);
Mapper.CreateMap<FooModel, Foo>().BeforeMap(Action);

private static void Action(EntityModel src, Entity dest)
{
    //get actual object properties via reflection, compare, re-create...
}


text:
Q: Do holomorphic bijections map contours enclosing the origin (winding number $1$) to contours enclosing the origin (with winding number $1$)? $\newcommand{\d}{\,\mathrm{d}}\newcommand{\g}{\gamma}$So I was recently reviewing the proof of Lagrange-Burmann inversion:

Consider functions of the form $f:\Bbb C\to\Bbb C,\,w\mapsto w/\psi(w)$ where $\psi:\Bbb C\to\Bbb C$ is holomorphic in a neighbourhood of the origin and of non-zero constant term. All such $f$ admit an holomorphic local inverse $g$, defined in some neighbourhood of the origin, with power series: $$[z^n]g(z)=\frac{1}{n}[w^{n-1}]\psi(w)^n,\quad n\in\Bbb N$$

The proof is delightfully short using contour integration, however I have a small quibble about the images of contours under holomorphic maps.

By the inverse function theorem is $g$ well-defined and analytic in some neighbourhood of the origin; let $\gamma$ be an anticlockwise closed contour enclosing a simply connected neighbourhood of the origin, with winding number $1$, contained within the domain of $g$. By Cauchy: $$\begin{align}[z^n]g(z)=&\frac{1}{2\pi i}\oint_{\gamma}\frac{g(z)}{z^{n+1}}\d z\\\overset{z=f(w)}{=}&\frac{1}{2\pi i}\oint_{\color{blue}{g(\gamma)}}\frac{w}{w^{n+1}}\cdot\psi(w)^{n+1}\left(\frac{1}{\psi(w)}-w\cdot\frac{\psi'(w)}{\psi(w)^2}\right)\d w\end{align}$$

And so on - the proof follows easily from there, reliant on the key assumption that: $$\frac{1}{2\pi i}\oint_{\color{blue}{g(\gamma)}}\frac{\psi(w)^n}{w^n}\d w=[w^{n-1}]\psi(w)^n$$This formula is valid if $g(\gamma)$ is a closed contour, of winding number $1$, enclosing some simply connected neighbourhood of the origin in which $\psi$ is holomorphic. $g$ must be injective, so I can assure myself that the path $g(\gamma)$ is indeed closed and does not intersect itself (although, is that sufficient to say that the winding number is $1$? My geometry is hazy) but I cannot assure myself $g(\gamma)$ encloses the origin. Yes, $\gamma$ enclosed the origin and $g(0)=0$, but $g$ mapping the neighbourhood enclosed by $\gamma$ to some other neighbourhood of the origin is not the same, I think, as the path $g(\gamma)$ enclosing the origin, or enclosing this neighbourhood.
Maybe by homotopy invariance we can argue $g(\gamma)$ is homotopic to a suitable Cauchy-formula contour, but I don't see how this can be argued. What am I missing?

A: The winding number of $\Gamma = g \circ \gamma$ with respect to the origin is
$$
I(\Gamma, 0) = \frac{1}{2 \pi i} \int_\Gamma \frac 1w \, dw
= \frac{1}{2 \pi i} \int_\gamma \frac{g'(z)}{g(z)} \, dz = \operatorname{Res}(\frac{g'}{g}, 0) = 1
$$
according to the Residue theorem, and because the only singularity of $g'/g$ is a simple pole at the origin, with residue equal to one.


text:
Q: Determining the limits of the following functions... I'm not sure about the limits of the following two functions.
For the first one, I think it doesn't have a limit. For the second one, I get the number 3.
Correct me if I'm wrong...
$$\lim_{x\rightarrow 0^+}\frac{\sin x}{|\sin x|}$$
$$\lim_{x\rightarrow \infty }\frac{\sin^2 x+3x^3}{x^2+x^3}$$
I need at least 10 reputation to post images, so please find the question by clicking the links above...Thanks!

A: the $|\sin x|$ for positive number near zero equal $\sin x$
$$\lim_{x\rightarrow 0^+}\frac{\sin x}{|\sin x|}=\lim_{x\rightarrow 0^+}\frac{\sin x}{\sin x}=1$$
$$\\lim_{x\rightarrow \infty }\frac{\sin^2 x+3x^3}{x^2+x^3}=\lim_{x\rightarrow \infty }\frac{\sin^2 x/x^3+3x^3/x^3}{x^2/x^3+x^3/x^3}=\lim_{x\rightarrow \infty }\frac{\sin^2 x/x^3+3}{1/x+1}=\lim_{x\rightarrow \infty }\frac{0+3}{0+1}$$

A: I agree with 3 for your second limit.
For the first, note that as $x\to0$ from the right, $\sin x$ is positive and approaches 0.
Thus, $|\sin x|=\sin x$, since $\sin x$ is positive.
Therefore...
$$\lim_{x\to0^+} \frac{\sin x}{|\sin x|}=\lim_{x\to0^+} \frac{\sin x}{\sin x}=1.$$


text:
Q: Insert into two tables with one table having an auto increment primary key I have 2 tables Station and Contract. Contract have a foreign key relationship with Station table IDStation auto increment . How i get IDStation number at same time i do insert statement.
cmd.CommandText = "Insert into Stations (CityID," +
                    "StartDate,Space,Owner)" +
                    "values (@CityID,@StartDate," +
                    "@Space,@Owner)" +
                    "Insert Contract (IDStation,ContractStart,ContractEnd) values (@IDStation,@ContractStart,@ContractEnd) ";

                cmd.Parameters.AddWithValue("@CityID", drpCity.Value);
                cmd.Parameters.AddWithValue("@StartDate", txtStartDate.Value);
                cmd.Parameters.AddWithValue("@Space", txtSpace.Text);
                cmd.Parameters.AddWithValue("@Owner", txtOwner.Text);
               // cmd.Parameters.AddWithValue("@IDStation",drp );
                cmd.Parameters.AddWithValue("@ContractStart", txtConStart.Value);
                cmd.Parameters.AddWithValue("@ContractEnd", txtConEnd.Value);

                cmd.ExecuteNonQuery();


text:
Q: nodejs function not setting variable, net-ping Trying to set a variable based on the result of running session.pingHost, the pingHost function works but it's not setting my variable like I expect.
import ping from 'net-ping';

let TEMPIP = '8.8.8.8';
let session = ping.createSession();
let ipset = false;

session.pingHost(TEMPIP, function(error) {
  if (error) {
    console.log('Offline');
    ipset = false;
  } else {
    console.log('Alive');
    ipset = true;
  }
});

console.log(ipset);

result:
false
"Alive"

Expected result:
"Alive"
true

Adding code for how I got it to work
function pingfunction(TEMPIP) {
  return new Promise(function(resolve, reject) {
    session.pingHost(TEMPIP, function(error) {
      if (error) {
        console.log('Offline');
        reject(false);
      } else {
        console.log('Alive');
        resolve(true);
      }
    });
  });
}
pingfunction(TEMPIP)
  .then(function(result) {
    console.log(result);
  })
  .catch(function(err) {
    console.log(err);
  });

A: You have to use = instead of ==.
== is for comparison whereas = is for assigning value to a variable.

A: The reason ipset is set to false is because the call to console.log is called before the callback for session.pingHost. You need to move the call to console.log inside the callback function for `session.pingHost' like this:
import ping from 'net-ping';

let TEMPIP = '8.8.8.8';
let session = ping.createSession();
let ipset = false;

session.pingHost(TEMPIP, function(error) {
  console.log("CALLED")

  if (error) {
    console.log('Offline');
    ipset = false;
  } else {
    console.log('Alive');
    ipset = true;
  }
  console.log(ipset);
});


text:
Q: A very strange String casting error I am creating array of views with this labels :
0.1, 0.2 , 0.3, 0.4 ...... 20

so:
        var time = 0.1
         for k in 0..<200
        {
              //........
            item.text = String(time) //*** here is the problem

            time+=0.1

When it gets to 6 I get this on the label:
5.5 , 5.6 , 5.7 , 5.8 , 5.9, 5.99999,6.099999,6.199999

back to normal on 10.1 10.2 ,etc
Whats so special about 6 ??  :)

A: You can try to cast with a finite number of decimals, declare your time as a float and add it a float too:
var time = 0.1f
...

item.text = String(format:"%.1f", time)
time += 0.1f


text:
Q: Convert List of Vectors into Data Frame of Counts I have a list of character vectors stored in a list like this:
basket1 <- c("Apple", "Orange", "Banana", "Apple", "Apple", "Grape")
basket2 <- c("Grape", "Grape", "Grape", "Grape")
basket3 <- c("Kiwi", "Apple", "Cantaloupe", "Banana")
basket4 <- c("Strawberry")
basket5 <- c("Grape", "Grape", "Grape")
FruitBasketList <- list(basket1, basket2, basket3, basket4, basket5)

And I would like to turn the FruitBasketList into a data frame with a count of each fruit in each row matching the basket it came from. The main problem I have is that there could be thousands of different "fruits" in each vector and a lot of them will appear more than once.

This is the desired data frame I would like as a result:

Basket  Apple   Orange  Banana  Grape   Kiwi    Cantaloupe  Strawberry
basket1 3       1       1       1       0       0           0
basket2 0       0       0       4       0       0           0
basket3 1       0       1       0       1       1           0
basket4 0       0       0       0       0       0           1
basket5 0       0       0       3       0       0           0

Obviously, this isn't my real data, but I thought I would simplify what the data looks like so anyone would be able to understand it.  No, this isn't homework.  Anyhow, The number of fruits in a basket can be a thousand different fruits and the lengths of each fruit vector wouldn't be the same.  There can be tens of thousands of baskets (vectors) as well.  Obviously, some fruits could be repeated many times in the same vector (basket).  I have been working on solving this, but I'm sure it is terribly over-complicated and very inefficient.  So far my solution involves combining all the vectors from all the vectors, then identifying all the unique fruit names that are possible.  That worked out fine.  Then the part I'm struggling with is creating an empty data frame from out of all of these unique column names, then for each vector counting each unique fruit and then placing that value in the correct column in a new row in the data frame along with zeros for fruits that don't exist in that particular basket.
The code I'm using to tally up individual vectors looks like this:
GetUniqueItemCount <- function(rle, value)
{
  value <- rle$lengths[rle$values == value]
  if (identical(value, integer(0)))
  {
    value <- 0
  }
  value
}

And the code to call it looks like this:
Apple <- GetUniqueItemCount(rle, "Apple")

As you can see in my current code I have to know all the possible fruits before hand and hard code the count of each fruit and then assign that to a specific column known beforehand in the data frame.  Anyhow, I realize I am going down the wrong path here, so I would appreciate any advice on getting back on track to getting my desired data frame shown above.  Please feel free to offer a completely different approach instead of trying to figure out how to make mine work if that would be the best way to solve the problem.

A: Using dplyr, i might do something like
library(dplyr)
m <- FruitBasketList %>% lapply(table) %>% lapply(as.list) %>%
    lapply(data.frame) %>% rbind_all()
m

# Source: local data frame [5 x 7]
#
#   Apple Banana Grape Orange Cantaloupe Kiwi Strawberry
# 1     3      1     1      1         NA   NA         NA
# 2    NA     NA     4     NA         NA   NA         NA
# 3     1      1    NA     NA          1    1         NA
# 4    NA     NA    NA     NA         NA   NA          1
# 5    NA     NA     3     NA         NA   NA         NA

which will leave missing values as NA. if you want to set them to 0, you can do
m[is.na(m)]<-0
m

# Source: local data frame [5 x 7]
#
#   Apple Banana Grape Orange Cantaloupe Kiwi Strawberry
# 1     3      1     1      1          0    0          0
# 2     0      0     4      0          0    0          0
# 3     1      1     0      0          1    1          0
# 4     0      0     0      0          0    0          1
# 5     0      0     3      0          0    0          0

A: I would suggest mtabulate from the "qdapTools" package.
library(qdapTools)
mtabulate(FruitBasketList)
#   Apple Banana Cantaloupe Grape Kiwi Orange Strawberry
# 1     3      1          0     1    0      1          0
# 2     0      0          0     4    0      0          0
# 3     1      1          1     0    1      0          0
# 4     0      0          0     0    0      0          1
# 5     0      0          0     3    0      0          0

The package's author even shares your avatar. Nifty.

A: you can apply function table on each row, then rbind the result using gtools::smartbind

A: You could melt the "list" and reshape from "long" to "wide" using dcast
library(reshape2)
dcast(melt(setNames(FruitBasketList, ls(pattern='^basket'))), L1~value)
#      L1   Apple Banana Grape Orange Cantaloupe Kiwi Strawberry
#1 basket1     3      1     1      1          0    0          0
#2 basket2     0      0     4      0          0    0          0
#3 basket3     1      1     0      0          1    1          0
#4 basket4     0      0     0      0          0    0          1
#5 basket5     0      0     3      0          0    0          0

Or using base R functions stack and table
df <- stack(setNames(FruitBasketList, ls(pattern='^basket')))
table(df[2:1])
#          values
#ind        Apple Banana Cantaloupe Grape Kiwi Orange Strawberry
# basket1     3      1          0     1    0      1          0
# basket2     0      0          0     4    0      0          0
# basket3     1      1          1     0    1      0          0
# basket4     0      0          0     0    0      0          1
# basket5     0      0          0     3    0      0          0


text:
Q: How to get deleted id in codeigniter? After deleting a row. how to get its id.
we can receive inserted ID from $this->db->insert_id(). Is there similar function for getting deleted records id.

A: However you will the id to delete a record.
In model, you will pass id as parameter. try below code.
public function delete_row($id)
{
  $this->db->where(array("id"=>$id));
  $this->db->delete("my_table");
  if($this->db->affected_rows()>0)
   return $id;
  else
   return false;
}

Note: If you didn't pass id. then you have to use same parameters which are used to delete to get the record before deleting the record.

A: You should first save the id you are about to delete in a variable then after passing the variable(id) to the query and the row is deleted you will be able to do whatever you want with the id that is still stored in the the variable. simple and straight forward no functions added needed.


text:
Q: How to set Sql Server Job Schedule Dynamically We have an Sql Server Job which runs for an entire season. The end date of the season may be change this year. I need to integrate this change in Job Schedule.  Is there any way to determine start-date and end-date the Job dynamically?i.e passing them as parameters to sql-server job.
How to achieve this?
thanks for the help

A: Check this out:
sp_update_schedule (Transact-SQL)
You need to run another job to update the schedule of the first Job according to your business requirements


text:
Q: Setting Your Own Key When Adding an Object to Firebase - AngularFire I can use the following to add an object to my Firebase data store:
var uniqueId = {
    name: "a name",
    location: "new york"
}
$scope.myItems.$add(uniqueId).then(function(firebaseId){
    // do something on success
}, function(){
    // do something if call fails
});

The above will add an object into my data store and if the add is successful, an ID generated by Firebase is returned.  The object I just added is saved under this key.
Is there a way for me to specify what the key name is when I add to my data store?

A: You can try it like this:
var empsRef = ref.child("employees");

empsRef.child('11111').set({
  lastname: "Lee",
  firstname: "Kang"
});

empsRef.child('22222').set({
  lastname: "Nut",
  firstname: "Dough"
});

The output should look like this:
"employees" : {
  "11111" : {
    "lastname" : "Lee",
    "firstname": "Kang"
  },
  "22222" : {
    "lastname" : "Nut",
    "firstname": "Dough"
  }
}

A: It looks like $child and $set have been removed from the AngularFire API.
Here is my workaround.

*

*Listen for $onAuth

*Create a new $firebaseObject with the ref as a child of users and the id as the uid (in this case, facebook)

*Save the user object
angular.module("app.services", []).factory("Auth", function ($firebaseAuth, $firebaseObject, FirebaseUrl) {
var auth = $firebaseAuth(new Firebase(FirebaseUrl));

auth.$onAuth(function (authData) {
    if (authData) {
        var ref = new Firebase(FirebaseUrl + "/users/" + authData.uid);
        var user = $firebaseObject(ref);
        user.name = authData.facebook.displayName;
        user.$save().then(function () {
            console.log(user);
        });
    }
});
return auth;
})

I am still struggling to make this testable though...

A: Everything in Firebase is a URL.
Take the following URL for example.
https://myapp.firebaseio.com/users/

Let's say we want to create a user with a key of 1 as a child at this location. Our URL would look like this.
https://myapp.firebaseio.com/users/1

To create a user using AngularFire we can create a reference at the users node and call $child(1) to create a reference to that location.
var usersRef = new Firebase('https://myapp.firebaseio.com/users');
var userRef = new Firebase('https://myapp.firebaseio.com/user/1');

$scope.users = $firebase(usersRef);

// these are the same
$scope.userOne = $firebase(userRef);
$scope.userOne = $scope.users.$child(1);

Then we can use $set to store the value of the user at that location.
var usersRef = new Firebase('https://myapp.firebaseio.com/users');
$scope.users = $firebase(usersRef);
$scope.users.$child(1).set({
  first: 'Vincent',
  last: 'Van Gough',
  ears: 1
});

In your case it would be:
var uniqueId = {
    id: 1,
    name: "a name",
    location: "new york"
};
$scope.myItems.$child(uniqueId.id).$set(uniqueId);

Remember that using $set will destroy any previous data at that location. To non-destructively update the values use $update.

A: .set still working in angularfire api
So, try this...
var gT = $scope.ultima[0].guia + 1;
var _db = firebase.database().ref('/guias/' + gT);
                      _db.set({
                    'artigo': _dt.artigo,
                    'inicio': $scope.ultima[0].fim + 1,
                    'guia': $scope.ultima[0].guia + 1,
                    'fim': $scope.ultima[0].fim + 1 + (1 * _dt.quantidade),
                    'quantidade': _dt.quantidade,
                });


text:
Q: What is the purpose of the second parameter to std::allocator::deallocate? In here is declaration of deallocate mem. of allocator class. My question is what for is second argument in this declaration? If this function calls operator delete(_Ptr) this argument is unused so what's for is it there?
Thanks.
Excerpt from MSDN:
Frees a specified number of objects from storage beginning at a specified position.
void deallocate(
   pointer _Ptr,
   size_type _Count
);

Parameters
_Ptr
A pointer to the first object to be deallocated from storage.
_Count
The number of objects to be deallocated from storage.

A: When you call deallocate, you must give it a pointer that you previously obtained from calling allocate and the size that you passed to allocate when you initially allocated the memory.
For example,
#include <memory>

std::allocator<int> a;
int* p = a.allocate(42);
a.deallocate(p, 42);     // the size must match the size passed to allocate

This is useful for many different types of allocators.  For example, you may have an allocator that uses different pools for blocks of different sizes; such an allocator would need to know what the size of the block being deallocated is so that it knows to which pool it needs to return the memory.

A: It's not unused.
From MSDN:

Frees a specified number of objects
  from storage beginning at a specified
  position (_Ptr in this case).

Parameters
_Ptr
    A pointer to the first object to be deallocated from storage. (start position)
_Count
    The number of objects to be deallocated from storage.
Sample code:
// allocator_allocate.cpp
// compile with: /EHsc
#include <memory>
#include <iostream>
#include <vector>

using namespace std;

int main( )
{
   allocator<int> v1Alloc;

   allocator<int>::pointer v1aPtr;

   v1aPtr = v1Alloc.allocate ( 10 );

   int i;
   for ( i = 0 ; i < 10 ; i++ )
   {
      v1aPtr[ i ] = i;
   }

   for ( i = 0 ; i < 10 ; i++ )
   {
      cout << v1aPtr[ i ] << " ";
   }
   cout << endl;

   v1Alloc.deallocate( v1aPtr, 10 );
}

A: (reference the example in the documentation for the allocator : http://msdn.microsoft.com/en-us/library/723te7k3.aspx)
I assume that the allocator does not do a new[] and does not keep the number of allocated elements so it cannot do a delete[] ?
so the user need to tell how many to allocate and how many to deallocate.
M.

A: It appears to me that it's expecting _Ptr to be a pointer into an array of objects, and that it's basically doing:
for (size_type i = 0; i<_Count; i++) {
    delete _Ptr;
    _Ptr++;
}


text:
Q: Fibonacci Sequences with same terms If we have two or more say different positive numbers k and l, .. (with k less than l...) and we add to k and l respectively a fibonacci sequence (0,1,1,2,3,5,8,13,21,....). We get therefore the sequence (k, k+1, k+1, k+2, k+3, k+5, k+8, ....) and (l, l+1, l+1, l+2, l+3, l+5, l+8, ....). Similarly we can add another constant number to the same fib sequence etc... The two (or more) generated sequences, depending on the value k nad l, can have some terms of different index of course, the same value. What is the general condition for the generated fibonacci sequences to have some terms equal, and the question also extends to how many equal terms we get, depending on the distance l-k and l,k.  Thank you very much.

A: As you say, it depends on $l−k$. If
$l−k=1$, there are five solutions $$k+1=l+0,k+1=l+0,k+2=l+1,k+2=l+1,k+3=l+2$$
If $l-k=2$, there are $l+0=k+2,l+1=k+3,l+1=k+3,l+3=k+5$
If $l−k$ equals any other Fibonacci number, there are three solutions, for example $l−k=5$ then $l+0=k+5,l+3=k+8,l+8=k+13$.
If $l-k=F_n-1$, there are two solutions from counting 1 twice.
Otherwise, there is one solution if $l−k$ is the difference of two Fibonacci numbers.
These differences are $8-2;13-3,13-2;21-5,21-3,21-2;34-8,34-5,34-3,34-2;...$


text:
Q: Best design for a "Command Executer" class Sorry for the vague title, I couldn't think of a way to condense the question.
I am building an application that will run as a background service and intermittently collect data about the system its running on. A second Android controller application will query the system over tcp/ip for statistics about the system.
Currently, the background service has a tcp listener class that reads/writes bytes from a socket. When data is received, it raises an event to notify the service. The service takes the bytes, feeds them into a command parser to figure out what is being requested, and then passes the parsed command to a command executer class. When the service receives a "query statistics" command, it should return statistics over the tcp/ip connection.
Currently, all of these classes are fully decoupled from each other. But in order for the command executer to return statistics, it will obviously need access to the socket somehow. For reasons I can't completely articulate, it feels wrong for the command executer to have a direct reference to the socket. I'm looking for strategies and/or design patterns I can use to return data over the socket while keeping the classes decoupled, if this is possible.
Hopefully this makes sense, please let me know if I can include any info that would make the question easier to understand.

A: Perhaps implementing a message queue between whatever is responsible for the TCP/IP connection & your parser class would provide a nice, clean way to fully decouple everything.
Plus, you'd have the added bonus of any network communication issues not having to be handled by your parser class. It could just add messages to the queue and forget about them - nice separation of concerns. :-)

A: Ok, so this is what I've gone with for now. Any critiques are welcome. Basically I just modified the command executer to return a response object if a response is required, else null. That way the executer does not need any knowledge of where the response is going. The service mediator that sits between the socket and the rest of the classes checks if the response is null and if not, encodes it and ships it back over the tcp/ip connection.


text:
Q: Where can I find documentation on built in read only list columns for SharePoint 2010? I know for a fact that ID is a built in read only column. I think most SP admins and developers know this. Someone is trying to convince me otherwise.
All I could find on MSDN was the following:
"in SharePoint lists, you can view the built in ID column as a permanent, unchangeable primary key; and this is the value that drives the relationship"
List Relationships in SharePoint 2010

A: You can check the SPBuiltInFieldId class for the names and Ids of built-in fields.


text:
Q: Making a big 2d array in c++ I have the following code:
#include <bits/stdc++.h>
using namespace std;

const int MAX=25;
const int TMAX=1 << MAX - 1;
double D[TMAX][MAX];

int main(){}

If I compile it I get
champ@champ-S451LN:~/code$ g++   kike2.cpp
/tmp/ccuK5NOq.o: In function `__static_initialization_and_destruction_0(int, int)':
kike2.cpp:(.text+0x717): relocation truncated to fit: R_X86_64_PC32 against `.bss'
kike2.cpp:(.text+0x72a): relocation truncated to fit: R_X86_64_PC32 against `.bss'
collect2: error: ld returned 1 exit status

If I make MAX=22 I do not get this error, I think the problem is that TMAX*MAX exceeds 2^32.
Having access to such big 2D arrays would be useful for me. Does anyone know how to make them?
Here is what I did in the end:
#include <bits/stdc++.h>
using namespace std;

double** D = new double*[TMAX];// this is the DP array (its big so we save it differently)

int main(){
    for(int i = 0; i < TMAX; ++i){// store the big array
        D[i] = new double[MAX];
    }
}

A: You cannot make them really large on the stack, as the stack is nearly always severly more limited than main meory.
Use malloc or new instead, to create the object on the heap; main memory will be the only limit, including use of swap files if you want to go on that limb.

A: You must use it in heap, rather than stack.
double* D = (double*)malloc(sizeof(double) * TMAX * MAX);
// D[d1][d2] can be accessed *(D + d1 * TMAX + d2)


text:
Q: Is the usage of 'Due to urgent personal errands' valid? I see in my company mails, there is a lot of usage of the statement Due to urgent personal errands (..I may not report to office today) which, by hunch, I guess is not a proper usage.
What is the correct way to use it,if I am right?

A:
Due to urgent personal errands, I may not report to the office today.

This is a lame excuse, and it might have gotten a person fired ten years ago, but it seems there is no problem with the grammar.
Due to is used prepositionally, validated by OED under due:

The use of due to as a prepositional phrase meaning 'because of' (as
  in he had to retire due to an injury) first appeared in print in 1897,
  and traditional grammarians have opposed this prepositional usage for
  more than a century on the grounds that it is a misuse of the
  adjectival phrase due to in the sense of 'attributable to, likely or
  expected to' ( the train is due to arrive at 11:15), or 'payable or
  owed to' ( render unto Caesar what is due to Caesar). Nevertheless,
  this prepositional usage is now widespread and common in all types of
  literature and must be regarded as standard English. The phrase due to
  the fact that is very common in speech, but it is wordy, and,
  especially in writing, one should use instead the simple word because.

Errands is the object of the preposition, and the adjectives urgent and personal modify errands, to complete the leading prepositional phrase:

Due to urgent personal errands,

I is the subject of the sentence (apparently the person with the urgent personal errands).
May is the auxiliary of the verb report, negated by not, and modified temporally by today.
To the office is a prepositional phrase modifying report locationally, and completing the meaningful sentence:

Due to urgent personal errands, I may not report to the office today.


text:
Q: libusb_interrupt_transfer LIBUSB_ERROR_TIMEOUT I have a general design question, the final software will eventually run on Linux and Windows...
I am trying to read 8 bytes on an endpoint with libusb_interrupt_transfer and LIBUSB_ERROR_TIMEOUT occurs in the middle of data being received...  Will the be data be broken up? The docs warn about specifying anything other than the actual endpoint data size for the 'length' variable of the data to be received; that it can lead to buffer overrun. Also the docs say that if a timeout occurs to check the 'transferred' variable and that not all the data may have been received. Those two things being true, How am I supposed to deal with partially received data? If LIBUSB_ERROR_TIMEOUT occurs and my packet is only 8 bytes, will all 8 bytes always be received? And I supposed to always supply an 8 byte buffer, even if I am only requesting to receive the next 2 bytes to complete a previously timed out read request? And if I do supply that 8 byte buffer, and only request 2 bytes, it is possible that I may end up with 6 bytes of the next data packet that is incoming? Even though I only requested 2 bytes? Any info is greatly appreciated.
http://libusb.sourceforge.net/api-1.0/group__syncio.html#gac412bda21b7ecf57e4c76877d78e6486
libusb docs states "Also check transferred when dealing with a timeout error code. libusb may have to split your transfer into a number of chunks to satisfy underlying O/S requirements"
http://libusb.sourceforge.net/api-1.0/packetoverflow.html
docs states: "When requesting data on a bulk endpoint, libusb requires you to supply a buffer and the maximum number of bytes of data that libusb can put in that buffer. However, the size of the buffer is not communicated to the device - the device is just asked to send any amount of data."
Then it also states: "Overflows can only happen if the final packet in an incoming data transfer is smaller than the actual packet that the device wants to transfer. Therefore, you will never see an overflow if your transfer buffer size is a multiple of the endpoint's packet size: the final packet will either fill up completely or will be only partially filled."
unsigned char data[8];
int timeout  = 250; //timeout in milliseconds
int xmtcnt = 0;
int rcvcnt = 0;

//EP OUT (Send data to USB Device)
//0x02 = Endpoint Type 0x00 + Endpoint Number 2
r = libusb_interrupt_transfer(devh,0x02, data, sizeof(data), &xmtcnt, timeout);
if(r != 0 || xmtcnt != 8){printf("XMT libusb_interrupt_transfer error %d\n",r); goto out_release;}

//EP IN (Recv data from USB device)
//0x81 = Endpoint Type 0x80 + Endpoint Number 1
//-----IS IT POSSIBLE TO RECEIVE LESS THAN 8 BYTES IF WE TIMEOUT?----
r = libusb_interrupt_transfer(devh,0x81, data, sizeof(data), &rcvcnt, timeout);
if(r != 0 || rcvcnt != 8){printf("RCV libusb_interrupt_transfer error %d\n",r); goto out_release;}

//show data received
CONSOLE("data: %d %d %d %d %d %d %d %d xmt:%d rcv:%d\n",data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],xmtcnt,rcvcnt);


text:
Q: Is there a way for me to schedule a 302 redirect in IIS or web.config? I have some websites that need to be set to 302 redirect at midnight of a specific date. I understand that I can setup the redirects through IIS or through web.config for the site, but both of those would require me to make the change by hand at midnight as I understand it. Is there any way for me to setup ahead of time for the redirect to begin at a future date?

A: You could do a redirect in the global.asax file.
protected void Application_Start(Object sender, EventArgs e) {
    DateTime dateToRedirect = new DateTime(2015, 4, 1);
    HttpContext context = HttpContext.Current;

    if(DateTime.Now > dateToRedirect)
    {
        if(...) // Conditional code for setting which pages get redirected
        {
            string newUrl = "http://www.example.com";
            context.Response.Redirect(newUrl);
        }
    }
}


text: Q: Chapter names in headers I am using the book class to typeset a course I am currently taking. However, a chapter has a long name, and it causes the header to look terrible (the name of the chapter crosses the margins of the paper). Any ideas on how to change the chapter name in the header only, so it would look proper?


text:
Q: white box appears when scrolling Over the last couple of weeks whenever I go to scroll up or down a page half of the page suddenly goes white and I can often see like a grey checked pattern (I'm sorry if that doesn't make sense, not quite sure how to explain this) that will suddenly appear and then disappear and the page is back to normal, I was told to try and clear my cache and cookies and I did, but it's still doing it, it only happens for a second or two before going back to normal, and it's not usually all the page, just half of it. But it's really annoying and I don't know why it's doing that and what to do to fix  it.
Hopefully someone knows what I'm talking about lol.


text:
Q: Creating reusable array definitions in swagger I'm working on a definition/documentation-first specification of an API using Swagger 2.0. I've managed to break-out most reusable components into a definitions section however I am having trouble figuring out how to create reusable definitions for arrays of constants.
For example, I have a few paths that will return images, like this one:
paths:
  /resource/{imageId}:
    get:
      produces:
        - image/jpeg
        - image/png
        - image/gif
      parameters:
        - in: path
          name: imageId
          type: string
          required: true
      responses:
        200:
          description: Success
          schema:
            type: file

Which works just fine, but I would like to be able to define a reusable array of the values for the "produces" element so that I can reuse the same list for any path that will produce an image.
The following seemed like the intuitive approach, but swagger reports that the definition for imageMimeTypes is not valid:
paths:
  /resource/{imageId}:
    get:
      produces:
        $ref: "#/definitions/imageMimeTypes"
      parameters:
        - in: path
          name: imageId
          type: string
          required: true
      responses:
        200:
          description: Success
          schema:
            type: file
definitions:
  imageMimeTypes:
    - image/jpeg
    - image/png
    - image/gif

Is it possible to create a definition for an array like this? If so, what syntax should be used?

A: First of all, if these produces values are used in most operations, you can define them as global produces and override where needed.
produces:
  - image/jpeg
  - image/png
  - image/gif

paths:
  /resource/{imageId}:
    get:
      # Inherits global "produces"
      ...
  /something:
    get:
      # Overrides global "produces"
      produces:
        - application/json
      ...

Your second example is not valid, because produces cannot have a $ref value. But you can use YAML anchors to achieve a similar effect. Note that an anchor must be defined before it is used, so you need to put the list above the path definition.
x-types:
  imageMimeTypes: &IMAGE-MIME-TYPES
    - image/jpeg
    - image/png
    - image/gif

paths:
  /resource/{imageId}:
    get:
      produces: *IMAGE-MIME-TYPES
      parameters:
        - in: path
          name: imageId
          type: string
          required: true
      responses:
        200:
          description: Success
          schema:
            type: file

I put the list under an extension key x-types instead of definitions 1) because definitions is intended for input and output models and not random lists, and 2) to prevent the "unused definition" warning in the Swagger Editor.
This works in (at least) Swagger Editor and Swagger UI.


text:
Q: Get the length of a string containing Null terminated string I'm using the XOR encryption so when I'm going to decrypt my string I need to get the length of that string.
I tried in this way:
string to_decode = "abcd\0lom";
int size = to_decode.size();

or in this way:

string to_decode = "abcd\0lom";
int size = to_decode.lenght();

Both are wrong because the string contain \0.
So how can I have the right length of my string?

A: When you initialize the std::string, with a \0 in the middle, you loose all data ahead of it. If you think about it, a std::string is just a wrapper for a char*, and that gets terminated by a null termination \0. If the \0, doesn't have any meaning in the string, then you could escape it, like this:
string to_decode = "abcd\\0lom";

and the size would be 9. Otherwise, you could a container (eg: std::vector), of char's for the data storage

A: The problem is with the initialisation, not with the size. If you use the constructor taking a const char *, it interprets that argument as a NUL-terminated string. So your std::string is only initialised with the string abcd.
You need to use a range-based constructor:
const char data[] = "abcd\0lom";
std::string to_decode(data, data + (sizeof data) - 1);  // -1 to not include terminating NUL

[Live example]
However, be careful with such strings. While std::string can deal with embedded NULs perfectly fine, the result of c_str() will behave as "truncated" as far as all NUL-terminated APIs are concerned.

A: As others have said, the problem is that the code uses the constructor that takes const char*, and that only copies up to the \0. But, by a very strange coincidence, std::string has a constructor that can handle that case:
const char text[] = "abcd\0lom";
std::string to_decode(text, sizeof(text) - 1);
int size = to_decode.size();

The constructor will copy as many characters as you tell it to.


text:
Q: Why do my carousel slides just display one under the other? When I hit run or preview in a browser, I am using Chrome, a static view of all three slides stacked 1-3 is displayed.  So they do not toggle through each one.
This is only not working on codeply which I use often.  It does work on codepen and it does work once I add it to my html and CSS files through atom code editor.  Its only codeply that it will not run and I have javascript and bootstrap packages installed in codeply.

.carousel-item {
  height: 150px;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

A: Disregard this question.  I wasn't saving my selected framework which was latest bootstrap version in codeply.  It works fine.


text:
Q: Pubnub + React native - No banner notification on iOS real device I have integrated Pubnub Javascript sdk-v4 with my react native project.
And have used https://github.com/zo0r/react-native-push-notification for react native push notification. In both simulators (android and iOS),  the notification banner is shown when the app is running in the background (even if the app is closed). However, the notification banner isn't displayed when tested on a real device. The notification is only shown in the notification bar (when scrolled from the top of the screen). Any suggestion?
Code segment likes follows.
.
.
var PushNotification = require('react-native-push-notification');
var serviceCall = require('../../actions/serviceCall');
import PushController from '../../actions/pushController'
var PubNub = require('pubnub');
.
.

class SearchBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            ...
            ...

        };
        this.constructor.childContextTypes = {
            theme: React.PropTypes.object,
        }

    }
componentDidMount(){

    var pubnub = new PubNub({
        publishKey : 'pub-c-xxxxxx',

        subscribeKey : 'sub-c-xxxxxx'

      })
      var notifyListener ={
        message: function(message) {

            console.warn(JSON.stringify(message));
            PushNotification.localNotification({

                message: message.message.text, // (required)

            });

        }
      }
    pubnub.addListener(notifyListener);

    pubnub.subscribe({
        channels: ['Channel-xxxxxxx']
        });
    }

return (
            <Container>
                    <View theme={theme}>
                    <PushController/>
                    .
                    .
                    .
                    </View>
            </Container>
        )
}

A: I had to change the method of integration and this link was success.
Link: https://www.pubnub.com/docs/react-native-javascript/mobile-gateway


text:
Q: Recreating Twitter's slide in/out activity animation Twitter uses the following slide in/out animation when switching between activities:
https://gfycat.com/BountifulPoisedAyeaye
Notice that the previous activity moves back and fades, and then the next activity slides in from the right.
How can this animation be recreated?
Here is the code that I have that starts the next activity:
public void startSecondActivity() {
    Intent intent = new Intent(this, SecondActivity.class);
    startActivity(intent);
}

A: I found the answer. Github link here:
https://gist.github.com/kwent/5875749

A: You have to give animation to open and close Activity. add following two files inside res>anim folder.
enter.xml:
<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <translate
        android:duration="500"
        android:fromXDelta="100%"
        android:fromYDelta="0%"
        android:toXDelta="0%"
        android:toYDelta="0%" />
</set>

exit.xml:
<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <translate
        android:duration="500"
        android:fromXDelta="0%"
        android:fromYDelta="0%"
        android:toXDelta="-100%"
        android:toYDelta="0%" />
</set>

then now you have to just do the following when you open Activity .
public void startSecondActivity() {
    Intent intent = new Intent(this, SecondActivity.class);
    startActivity(intent);
    overridePendingTransition(R.anim.enter, R.anim.exit);
}


text:
Q: Is a proper morphism between projective schemes projective morphism? That is if $f :P^n_ {X} \rightarrow P^m_{Y}$ is a proper morphism, then it is a projective morphism.
Projective morphism means that it factors through projective scheme of last term and the first component is a closed immersion.

A: Let $f:X\to Y$ be a (not necessarily proper) morphism of projective schemes over a field $k$ (the same works over a scheme $S$). Then $f$ is projective.
Proof: $X\subseteq \mathbb{P}^n_k$ (closed immersion) for some $n$. Then consider the closed immersion $X\subseteq X\times_k Y$ in the graph, which is a closed subscheme of $\mathbb{P}^n_k\times_kY=\mathbb{P}^n_Y$ (here I am using that projective morphisms are proper, which is a standard application of the valuative criterion for properness). This gives the required factorization $X\to \mathbb{P}^n_Y\to Y$.


text:
Q: How to parse nested arrays using Json on android I'm trying for now to get only the "dados" > "nome" and its "contatos"> "nome" but the way I'm parsing I'm getting the following results:
07-25 16:58:38.637    1041-1041/com.javatechig.feedreader I/System.out﹕ ClientesContatosModel{id=0, nome='Bill Gates', telefone=[], email=[]}
07-25 16:58:38.637    1041-1041/com.javatechig.feedreader I/System.out﹕ ClientesContatosModel{id=0, nome='Linus Torvalds', telefone=[], email=[]}
07-25 16:58:38.637    1041-1041/com.javatechig.feedreader I/System.out﹕ ClientesContatosModel{id=0, nome='Bill Gates', telefone=[], email=[]}
07-25 16:58:38.637    1041-1041/com.javatechig.feedreader I/System.out﹕ ClientesContatosModel{id=0, nome='Linus Torvalds', telefone=[], email=[]}
07-25 16:58:38.637    1041-1041/com.javatechig.feedreader I/System.out﹕ ClientesContatosModel{id=0, nome='Bill Gates', telefone=[], email=[]}
07-25 16:58:38.637    1041-1041/com.javatechig.feedreader I/System.out﹕ ClientesContatosModel{id=0, nome='Linus Torvalds', telefone=[], email=[]}
07-25 16:58:38.637    1041-1041/com.javatechig.feedreader I/System.out﹕ ClientesContatosModel{id=0, nome='Steve Jobs', telefone=[], email=[]}

The "contatos" names is repeating until the last name "Steve Jobs".
Why is it doing that, and How can I solve it?
Here is my complete Json:
{
    "total": 4,
    "dados": [
        {
            "id": "9",
            "id_rm_empresa": "2",
            "id_rm_tipo_cliente": "1",
            "tipo_pessoa": "PJ",
            "cpf": null,
            "nome": "Microsoft",
            "cnpj": null,
            "ie": null,
            "suframa": null,
            "ramo_de_atividade": null,
            "ano_de_fundacao": null,
            "informacoes_adicionais": "informação do clientes",
            "enderecos": [
                {
                    "id_rm_endereco": "1",
                    "endereco": "Rua Rudolph Diesel",
                    "numero": "174",
                    "complemento": "",
                    "bairro": "Industrial",
                    "cep": "86063-330",
                    "cidade": "Londrina",
                    "estado": "Paraná",
                    "tipo_endereco": "Residencial"
                }
            ],
            "contatos": [
                {
                    "id_rm_cliente": "10",
                    "id_rm_contato": "1",
                    "id_rm_empresa": "2",
                    "nome": "Bill Gates",
                    "cargo": "Diretor",
                    "telefones": [
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_telefone": "4",
                            "id_rm_empresa": "2",
                            "tipo": "Trabalho",
                            "numero": "(22) 2222-2222",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        },
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_telefone": "9",
                            "id_rm_empresa": "2",
                            "tipo": "Celular",
                            "numero": "(44) 4444-4444",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        }
                    ],
                    "emails": [
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_email": "5",
                            "id_rm_empresa": "2",
                            "tipo": "Trabalho",
                            "email": "steve@apple-teste.com",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        }
                    ],
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                },
                {
                    "id_rm_cliente": "10",
                    "id_rm_contato": "7",
                    "id_rm_empresa": "2",
                    "nome": "Linus Torvalds",
                    "cargo": "Diretor",
                    "telefones": [
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_telefone": "4",
                            "id_rm_empresa": "2",
                            "tipo": "Trabalho",
                            "numero": "(22) 2222-2222",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        }
                    ],
                    "emails": [
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_email": "5",
                            "id_rm_empresa": "2",
                            "tipo": "Trabalho",
                            "email": "steve@apple-teste.com",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        }
                    ],
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                }
            ],
            "telefones": [
                {
                    "id_rm_empresa": "2",
                    "id_rm_cliente": "10",
                    "id_rm_telefone": "1",
                    "numero": "(43)3025-1355",
                    "tipo": "Casa",
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                },
                {
                    "id_rm_empresa": "2",
                    "id_rm_cliente": "10",
                    "id_rm_telefone": "2",
                    "numero": "(43)3000-6562",
                    "tipo": "Trabalho",
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                }
            ],
            "emails": [],
            "criado": "2013-09-01 07:00:00",
            "modificado": "2012-09-04 18:30:34",
            "status": "A"
        },
        {
            "id": "8",
            "id_rm_empresa": "2",
            "id_rm_tipo_cliente": "1",
            "tipo_pessoa": "PJ",
            "cpf": null,
            "nome": "Linux",
            "cnpj": null,
            "ie": null,
            "suframa": null,
            "ramo_de_atividade": null,
            "ano_de_fundacao": null,
            "informacoes_adicionais": "informação do clientes",
            "enderecos": [
                {
                    "id_rm_endereco": "1",
                    "endereco": "Rua Rudolph Diesel",
                    "numero": "174",
                    "complemento": "",
                    "bairro": "Industrial",
                    "cep": "86063-330",
                    "cidade": "Londrina",
                    "estado": "Paraná",
                    "tipo_endereco": "Residencial"
                }
            ],
            "contatos": [
                {
                    "id_rm_cliente": "10",
                    "id_rm_contato": "1",
                    "id_rm_empresa": "2",
                    "nome": "Bill Gates",
                    "cargo": "Diretor",
                    "telefones": [
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_telefone": "4",
                            "id_rm_empresa": "2",
                            "tipo": "Trabalho",
                            "numero": "(22) 2222-2222",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        },
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_telefone": "9",
                            "id_rm_empresa": "2",
                            "tipo": "Celular",
                            "numero": "(44) 4444-4444",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        }
                    ],
                    "emails": [
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_email": "5",
                            "id_rm_empresa": "2",
                            "tipo": "Trabalho",
                            "email": "steve@apple-teste.com",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        }
                    ],
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                },
                {
                    "id_rm_cliente": "10",
                    "id_rm_contato": "7",
                    "id_rm_empresa": "2",
                    "nome": "Linus Torvalds",
                    "cargo": "Diretor",
                    "telefones": [
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_telefone": "4",
                            "id_rm_empresa": "2",
                            "tipo": "Trabalho",
                            "numero": "(22) 2222-2222",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        }
                    ],
                    "emails": [
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_email": "5",
                            "id_rm_empresa": "2",
                            "tipo": "Trabalho",
                            "email": "steve@apple-teste.com",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        }
                    ],
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                }
            ],
            "telefones": [
                {
                    "id_rm_empresa": "2",
                    "id_rm_cliente": "10",
                    "id_rm_telefone": "1",
                    "numero": "(43)3025-1355",
                    "tipo": "Casa",
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                },
                {
                    "id_rm_empresa": "2",
                    "id_rm_cliente": "10",
                    "id_rm_telefone": "2",
                    "numero": "(43)3000-6562",
                    "tipo": "Trabalho",
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                }
            ],
            "emails": [],
            "criado": "2013-09-01 07:00:00",
            "modificado": "2012-09-04 18:30:34",
            "status": "A"
        },
        {
            "id": "19",
            "id_rm_empresa": "2",
            "id_rm_tipo_cliente": "1",
            "tipo_pessoa": "PJ",
            "cpf": null,
            "nome": "Apple",
            "cnpj": null,
            "ie": null,
            "suframa": null,
            "ramo_de_atividade": null,
            "ano_de_fundacao": null,
            "informacoes_adicionais": "informação do clientes",
            "enderecos": [
                {
                    "id_rm_endereco": "1",
                    "endereco": "Rua Rudolph Diesel",
                    "numero": "174",
                    "complemento": "",
                    "bairro": "Industrial",
                    "cep": "86063-330",
                    "cidade": "Londrina",
                    "estado": "Paraná",
                    "tipo_endereco": "Residencial"
                }
            ],
            "contatos": [
                {
                    "id_rm_cliente": "10",
                    "id_rm_contato": "1",
                    "id_rm_empresa": "2",
                    "nome": "Bill Gates",
                    "cargo": "Diretor",
                    "telefones": [
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_telefone": "4",
                            "id_rm_empresa": "2",
                            "tipo": "Trabalho",
                            "numero": "(22) 2222-2222",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        },
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_telefone": "9",
                            "id_rm_empresa": "2",
                            "tipo": "Celular",
                            "numero": "(44) 4444-4444",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        }
                    ],
                    "emails": [
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_email": "5",
                            "id_rm_empresa": "2",
                            "tipo": "Trabalho",
                            "email": "steve@apple-teste.com",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        }
                    ],
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                },
                {
                    "id_rm_cliente": "10",
                    "id_rm_contato": "7",
                    "id_rm_empresa": "2",
                    "nome": "Linus Torvalds",
                    "cargo": "Diretor",
                    "telefones": [
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_telefone": "4",
                            "id_rm_empresa": "2",
                            "tipo": "Trabalho",
                            "numero": "(22) 2222-2222",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        }
                    ],
                    "emails": [
                        {
                            "id_rm_cliente": "10",
                            "id_rm_contato": "1",
                            "id_rm_email": "5",
                            "id_rm_empresa": "2",
                            "tipo": "Trabalho",
                            "email": "steve@apple-teste.com",
                            "criado": "2013-09-01 07:00:00",
                            "modificado": "2013-09-03 18:30:30",
                            "status": "A"
                        }
                    ],
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                }
            ],
            "telefones": [
                {
                    "id_rm_empresa": "2",
                    "id_rm_cliente": "10",
                    "id_rm_telefone": "1",
                    "numero": "(43)3025-1355",
                    "tipo": "Casa",
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                },
                {
                    "id_rm_empresa": "2",
                    "id_rm_cliente": "10",
                    "id_rm_telefone": "2",
                    "numero": "(43)3000-6562",
                    "tipo": "Trabalho",
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                }
            ],
            "emails": [],
            "criado": "2013-09-01 07:00:00",
            "modificado": "2012-09-04 18:30:34",
            "status": "A"
        },
        {
            "id": "10",
            "id_rm_empresa": "2",
            "id_rm_tipo_cliente": "1",
            "tipo_pessoa": "PJ",
            "cpf": null,
            "nome": "Webee",
            "cnpj": null,
            "ie": null,
            "suframa": null,
            "ramo_de_atividade": null,
            "ano_de_fundacao": null,
            "informacoes_adicionais": "informação do clientes",
            "enderecos": [
                {
                    "id_rm_endereco": "1",
                    "endereco": "Rua Rudolph Diesel",
                    "numero": "174",
                    "complemento": "",
                    "bairro": "Industrial",
                    "cep": "86063-330",
                    "cidade": "Londrina",
                    "estado": "Paraná",
                    "tipo_endereco": "Residencial"
                }
            ],
            "contatos": [
                {
                    "id_rm_cliente": "10",
                    "id_rm_contato": "1",
                    "id_rm_empresa": "2",
                    "nome": "Steve Jobs",
                    "cargo": "Diretor",
                    "telefones": {
                        "total": 1,
                        "dados": [
                            {
                                "id_rm_cliente": "10",
                                "id_rm_contato": "1",
                                "id_rm_telefone": "4",
                                "id_rm_empresa": "2",
                                "tipo": "Trabalho",
                                "numero": "(22) 2222-2222",
                                "criado": "2013-09-01 07:00:00",
                                "modificado": "2013-09-03 18:30:30",
                                "status": "A"
                            }
                        ]
                    },
                    "emails": {
                        "total": 1,
                        "dados": [
                            {
                                "id_rm_cliente": "10",
                                "id_rm_contato": "1",
                                "id_rm_email": "5",
                                "id_rm_empresa": "2",
                                "tipo": "Trabalho",
                                "email": "steve@apple-teste.com",
                                "criado": "2013-09-01 07:00:00",
                                "modificado": "2013-09-03 18:30:30",
                                "status": "A"
                            }
                        ]
                    },
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                }
            ],
            "telefones": [
                {
                    "id_rm_empresa": "2",
                    "id_rm_cliente": "10",
                    "id_rm_telefone": "1",
                    "numero": "(43)3025-1355",
                    "tipo": "Casa",
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                },
                {
                    "id_rm_empresa": "2",
                    "id_rm_cliente": "10",
                    "id_rm_telefone": "2",
                    "numero": "(43)3000-6562",
                    "tipo": "Trabalho",
                    "criado": "2013-09-01 07:00:00",
                    "modificado": "2013-09-03 18:30:30",
                    "status": "A"
                }
            ],
            "emails": [],
            "criado": "2013-09-01 07:00:00",
            "modificado": "2013-09-03 18:30:30",
            "status": "A"
        }
    ]
}

Here is what I tried so far:
contatoList = new ArrayList<ClientesContatosModel>();
    JSONArray dados = json.getJSONArray("dados");
    feedList = new ArrayList<ClientesModel>();

    // parsing json object
    for (int i = 0; i < dados.length(); i++) {

        JSONObject item = dados.getJSONObject(i);

        ClientesModel mClientesModel = new ClientesModel();

        /* cadastra os dados necessários no objeto no modelo */

        mClientesModel.setNome(item.optString("nome"));
        mClientesModel.setTipo_pessoa(item.optString("tipo_pessoa"));
        mClientesModel.setInformacoes_adicionais(item.optString("informacoes_adicionais"));
        mClientesModel.setCpf(item.optString("cpf"));
        mClientesModel.setCnpj(item.optString("cnpj"));
        JSONArray contatos = item.getJSONArray("contatos");

            for (int j = 0; j < contatos.length(); j++) {

                ClientesContatosModel mClientesContatoModel = new ClientesContatosModel();

                JSONObject data = contatos.getJSONObject(j);

                mClientesContatoModel.setNome(data.optString("nome"));

                mClientesContatoModel.setCargo(data.optString("cargo"));

                contatoList.add(mClientesContatoModel);

            }

            feedList.add(mClientesModel);

            System.out.println(contatoList);

    }

A: Move
ClientesContatosModel mClientesContatoModel = new ClientesContatosModel();

and
contatoList.add(mClientesContatoModel);

inside
for (int j = 0; j < contatos.length(); j++) {

example:
for (int j = 0; j < contatos.length(); j++) {
 ClientesContatosModel mClientesContatoModel = new ClientesContatosModel();
 contatoList.add(mClientesContatoModel);

A: This line of code:
ClientesContatosModel mClientesContatoModel = new ClientesContatosModel();

should be inside the FOR it belongs to.
for (int j = 0; j < contatos.length(); j++) {
                // HERE
                ClientesContatosModel mClientesContatoModel = new ClientesContatosModel();
                JSONObject data = contatos.getJSONObject(j);
                mClientesContatoModel.setNome(data.optString("nome"));
                mClientesContatoModel.setCargo(data.optString("cargo"));
            }


text:
Q: Invalid time formatted value from CF proc results I am in the process of upgrading from CF 9 to CF 2016, and seeing some odd behavior in the data returned from a StoredProc call (cfscript).
The data type in the database is time(7). The database value I'm seeing the issue with is: 00:00:00.0000000.
I am dumping the results directly after the execute().getProcResultSets().results line.

*

*In CF 9, the value in the cfdump is 00:00:00.0000000 which is correct.

*In CF 2016, the value in the cfdump is 1970-01-01 00:00:00.0
This difference is causing an "invalid datetime error" in my code:
CreateODBCDateTime("#end_date# #end_time#")

I fixed this by using a TimeFormat() function call, but I'd like to know if there is another option for fixing this so the data returned by CF's StoredProc is correct, to eliminate any possible confusion.
UPDATE: I am using the default driver provided by Adobe.


text:
Q: What is the 'Groups' in the Case Related List? I just noticed that in the Case related list, there is a section called 'Groups'.
It looks like a standard object, however I do not know how to use it and where it comes from.
This 'Groups' is also not listed in the help.
Case Feed and Related Lists

A: This case has been shared with groups.  For example, if you mention @experts on the case feed, the experts group would be in that related list.  And if you went to the group, you'd see all the records associated with that group.
This related list can be on lots of objects now.


text:
Q: Finding the last element of a list given a condition I'm trying to write a function that finds the last element of a list of Ints given that all the Ints are greater than 100. This is the code I have written so far:
isLeast100All :: [Int] -> [Int]
isLeast100All list = filter (>100) list

lastList :: [Integer] -> Integer
lastList list' = case list' of
  isLeast100All list
    | list == []   -> 0
    | list == [x]  -> x
    | list == [x:xs] -> lastList xs

which gives me the error: "Parse error in pattern: isLeast100All"
I feel like there's something simple that I'm missing here but I'm not sure what it is. I'm basing my lastList function off the following definition:
lastList :: [Integer] -> Integer
lastList x = case x of
  [] -> 0
  [x] -> x
  x:xs -> lastList xs

A: You need to fix your types and use filter instead of map for isLeast100All:
isLeast100All :: [Integer] -> [Integer]
isLeast100All = filter (> 100)

lastList :: [Integer] -> Integer
lastList list' = case isLeast100All list' of
    []   -> 0
    xs  -> last xs

Or just:
lastList :: [Integer] -> Integer
lastList l = last $ 0 : filter (> 100) l

A: There are a couple of problems with your definition of lastList. You have confused list and list', [x:xs] should be (x:xs), and you're mixing predicate guards and case ... of expression.
Here's one way you can define it using predicate guards:
lastList :: [Integer] -> Integer
lastList list' = myLast $ isLeast100All list'

myLast :: [Integer] -> Integer
myLast list
    | list == [] = 0
    | tail list == [] = head list
    | otherwise = myLast $ tail list

Here's another using case ... of:
lastList :: [Integer] -> Integer
astList list' = case isLeast100All list' of
    [] -> 0
    [x] -> x
    (x:xs) -> lastList xs

This latter one is needlessly inefficient because the filtering function isLeast100All is applied to the entire remaining list at every level of recursion but I aimed to make these as similar to your code as possible.
The answer by Guru Stron gives simpler alternatives.


text:
Q: Closest values within common index In this dataset df:
data = ['dog', 'cat', 'rabbit', 'elephant']
i = data*3
base = pd.DataFrame(np.random.randn(12, 2), index=i, columns=list('AB'))
marker = pd.DataFrame(np.random.randn(4,1), index=data, columns=['marker'])

df = base.join(marker)

How to get the rows of column df['A'] with the closest value to its marker?
Went through this link but could not manage to extract rows per unique index.

A: Use:
np.random.seed(123)

data = ['dog', 'cat', 'rabbit', 'elephant']
i = data*3
base = pd.DataFrame(np.random.randn(12, 2), index=i, columns=list('AB'))
marker = pd.DataFrame(np.random.randn(4,1), index=data, columns=['marker'])

print (base)
                 A         B
dog      -1.085631  0.997345
cat       0.282978 -1.506295
rabbit   -0.578600  1.651437
elephant -2.426679 -0.428913
dog       1.265936 -0.866740
cat      -0.678886 -0.094709
rabbit    1.491390 -0.638902
elephant -0.443982 -0.434351
dog       2.205930  2.186786
cat       1.004054  0.386186
rabbit    0.737369  1.490732
elephant -0.935834  1.175829

print (marker)
            marker
dog      -1.253881
cat      -0.637752
rabbit    0.907105
elephant -1.428681

Sorting index by DataFrame.sort_index - reason is avoid ValueError: cannot reindex from a duplicate axis in last filtering:
base = base.sort_index()
print (base)
                 A         B
cat       0.282978 -1.506295
cat      -0.678886 -0.094709
cat       1.004054  0.386186
dog      -1.085631  0.997345
dog       1.265936 -0.866740
dog       2.205930  2.186786
elephant -2.426679 -0.428913
elephant -0.443982 -0.434351
elephant -0.935834  1.175829
rabbit   -0.578600  1.651437
rabbit    1.491390 -0.638902
rabbit    0.737369  1.490732

Subtract columns by Series.sub and get absolute values, last filtering by GroupBy.transform with min and boolean indexing:
s = base['A'].sub(marker['marker']).abs()
s2 = base.loc[s.groupby(level=0).transform('min').eq(s), 'A']
print (s2)
cat        -0.678886
dog        -1.085631
elephant   -0.935834
rabbit      0.737369
Name: A, dtype: float64

EDIT:
df = base.join(marker)
df['marker'] = df['A'].sub(df['marker']).abs()
s2 = df.loc[df.groupby(level=0)['marker'].transform('min').eq(df['marker']) , 'A']
print (s2)
cat        -0.678886
dog        -1.085631
elephant   -0.935834
rabbit      0.737369
Name: A, dtype: float64

A: for the dataframe:
                 A         B    marker
cat      -1.364769 -0.723230  0.069315
cat      -1.141256 -0.124800  0.069315
cat      -1.658259 -0.881559  0.069315
dog      -0.277469 -0.621357 -1.389664
dog      -0.854505  0.282091 -1.389664
dog      -1.000602  0.171808 -1.389664
elephant -0.673019  0.202090 -0.735848
elephant  1.729002 -0.052014 -0.735848
elephant  3.083791  0.623577 -0.735848
rabbit   -0.946095  0.536181 -2.455088
rabbit    0.644441 -1.476657 -2.455088
rabbit    1.614225 -0.806389 -2.455088

...single-line solution with the code...
df.iloc[df.reset_index().groupby('index').apply(lambda g: abs(g.A - g.marker).idxmin())]

...gives...
                 A         B    marker
cat      -1.141256 -0.124800  0.069315
dog      -1.000602  0.171808 -1.389664
elephant -0.673019  0.202090 -0.735848
rabbit   -0.946095  0.536181 -2.455088


text:
Q: Node js sql data not being shown on handlebars when passed I hava a button response on my express-handlebars, when clicked it should execute an sql query and store selected data to an array, the problem is that when I pass the data to the other page handlebars doesn't the data.
app.post('/smo_assessment', urlencodedParser, function(req, res){

    connection.query('SELECT * FROM requests WHERE id=?', req.body.requestID, function(err, rows, fields){

        if(err){
            throw err;
        }
        else {
            selectedRequest = rows;
            res.render('smo_assessment', {assessmentType, data: selectedRequest});
            console.log(selectedRequest);
        }
    });
});

But console.log(selectedRequest) works and logs the entire row, and when rendering the response 'smo_assessment' handle bars doesn't show the data from selectedRequest.
This is my handlebars.

            Date Requested:
            {{data.date_requested}}
            Date Needed:
            {{data.date_needed}}

            Division:
            {{data.division}}
            Community:
            {{data.community}}

</table


text:
Q: Casting vs Specifying type in C# I've been looking around for ways to parse a JSON string and I've come across these two methods.
class Test {

      String test;

      String getTest() { return test; }
      String setTest(String test) { test = test; }

  }

var ser = new JavaScriptSerializer();
Test abc = (Test)ser.DeserializeObject("{ \"test\":\"some data\" }");

and
var ser = new JavaScriptSerializer();
Test abc = ser.Deserialize<Test>("{ \"test\":\"some data\" }");

The first one is casting an object to a type and the second one is specifying the type? Any real differences between them? Is one method more preferable?

A: No, the only purpose of the first one is to allow you to perform the deserialization even if you are unsure of the resultant type.  (the second one performs the cast automatically for you)  But there is no substantive difference.  (literally, the only difference is that the latter auto-casts the result of the former)

A: The second option (using the generic Deserialize<T> method) is preferable for your particular example since you expect a specific type.
Both produce a slightly different outcome when the input doesn't represent an object of the type you expect. In the first case, you get an InvalidCastException in your cast, and in the second case the Deserialize method throws an InvalidOperationException. But other than that, there is no difference in terms of performance etc. In fact the documentation for Deserialize<T> states this:

The Deserialize method is equivalent to first using the DeserializeObject method to obtain an object graph and then trying to cast the result to type T.


text:
Q: convert a pinescript v2 script to pinescript v5 I can't convert this script to v5, do you have any ideas on how I can do it?
//@version=2
strategy("Fractal Breakout Strategy (by ChartArt)", shorttitle="CA_-_Fractal_Breakout_Strat", overlay=true)

// input
n_time = input(title='Always exit each trade after this amount of bars later (Most important strategy setting)', defval=3, type=integer)
price = input(hl2,title='Price type to determine the last fractal top and the fractal breakout, the default is (high+low)/2')

// fractal calculation
fractal_top = high[2] > high[3] and high[2] > high[4] and high[2] > high[1] and high[2] > high[0]
fractal_price = valuewhen(fractal_top, price, 1)
use_longer_average = input(true,title='Use Fractal price average of the last 3 fractals instead of the last 2 fractals?')
fractal_average = use_longer_average?(fractal_price[1] + fractal_price[2] + fractal_price[3] ) / 3 : (fractal_price[1] + fractal_price[2]) / 2
fractal_trend = fractal_average[0] > fractal_average[1]
no_repainting = input(true,title='Use the price of the last bar to prevent repainting?')
fractal_breakout = no_repainting?price[1] > fractal_price[0]:price[0] > fractal_price[0]

// highlight fractal tops
show_highlight = input(true,title='Highlight fractal tops in blue and color all other bars in gray?')
highlight = fractal_top?blue:silver
barcolor(show_highlight?highlight:na,offset=-2)
show_fractal_top_line = input(true,title='Draw a colored line based on the fractal tops?')
fractal_top_line = change(fractal_top) != 0 ? price : na
fractal_top_line_color = change(fractal_price) > 0 and fractal_breakout == true ? green : change(fractal_price) < 0 and fractal_breakout == false ? red : blue
plot(show_fractal_top_line?fractal_top_line:na,offset=-2,color=fractal_top_line_color,linewidth=4)

// strategy
trade_entry = fractal_trend and fractal_breakout
trade_exit = fractal_trend[n_time] and fractal_trend == false

if (trade_entry)
    strategy.entry('Long', strategy.long)

if (trade_exit)
    strategy.close('Long')

I tried to convert it to v3 and then go through the trading view converter but I can't find the same results!


text:
Q: Multi line plot and re-label legend 1) Why are lines so dense?
In the dataset the time is by hour, if time was by day would it make a difference. I would like to see a line chart for each host.
2) How can I re-label the legend from count to host?
fig, ax = plt.subplots(figsize=(15,7))
df.groupby('host').plot(x='time', y='count',ax=ax, legend=True)

A: *

*You are plotting hourly data of more than 6 months. That's ~4k data points, of course it is dense. Daily data would be better, although it's still going to be dense.

*There are a couple of options:
You could either use seaborn
import seaborn as sns
fig, ax = plt.subplots(figsize=(15,7))
sns.lineplot(x='time', y='count', ax=ax, hue='host')

Or do a loop on groupby:
fig, ax = plt.subplots(figsize=(15,7))
for h, d in df.groupby('host'):
    d.plot(x='time', y='count', ax=ax, label=h)

A: Ad 2) just add label='name' as parameter, i.e:
fig, ax = plt.subplots(figsize=(15,7))
df.groupby('host').plot(x='time', y='count',ax=ax, legend=True, label='host')


text:
Q: Setting up a LibGDX project in Intellij Idea I'm developing an Android game in Java, using the LibGDX framework.
I really want to use the Idea IDE, so I've followed the official tutorial on setting up the project.
At first, there doesn't not seem to be a problem. When I make an output artifacts, the executable .jar file runs flawlessly on my desktop. The problems emerge with the Android .apk file. When I try to run it in emulator, it crashes with the error: "unfortunately "AppName" has stopped working".

*

*I don't think the problem is in my code, since I didn't write any. I only have the starter classes and they are just copied from the tutorial above.

*I'm not sure if it works outside the emulator, since I don't currently have a real android device to test it on.

Do you have any idea what might be the cause of this strange behavior?