text:
Q: ¿Cómo pasar a setInterval() una función con parámetros? Estoy haciendo un bot con Node.js y quiero que uno de los métodos, tweetIt(), se ejecute cada X segundos, para lo que uso el método setInterval().
tweetIt() recibe un array de frases.
Al llamar al método setInterval(), que recibe la función tweetIt(), me encuentro con que me lanza un error si a tweetIt() le paso parámetros:
TypeError [ERR_INVALID_CALLBACK]: Callback must be a
function. Received undefined

Si modifico el código para no tener que pasarle la función sin parámetros, funciona.
Resumiendo, la pregunta es: ¿cómo puedo pasarle a setInterval() una función con parámetros?
Aquí está el código:
tweetIt()
function tweetIt(text){
var tweet = {
    status: text
}

T.post('statuses/update', tweet, tweeted);

function tweeted(err, data, response){
    if(err){
        console.log("Shit!!");
        console.log(err);
    }else{
        console.log("It worked!");
    }
    // console.log(data);
}
}

setInterval()
setInterval(tweetIt(addDevStatuses[randomIndex]), 1000*20);

Array de frases
var addDevStatuses = [
"Frase 1",
"Frase 2",
"Frase 3",
"Frase 4"
];

A: Opción 1, Usar una función de flecha para configurar la función de callback que requiere setInterval y dentro de la función anónima ya se puede llamar la función con parámetros.

var functionWithParams = (message) => console.log(message)

// Opción 1
// setTimeout, igual que setInterval recibe la función a ejecutar
setTimeout(() => functionWithParams("¡Hola mundo! (Función de flecha)"), 500)

// Opción 2
setTimeout(functionWithParams, 500, "¡Hola Mundo! (Func sobrecarga)")

La opción 2 es usar la sobrecarga que permite recibir los argumentos, se puede revisar mayor documentación aquí; el setInterval puede recibir más de un argumento para la función que va a ejecutar pasándolos como parámetros posterior al delay

A: La forma de usar setInterval es la siguiente:

let pID = window.setInterval(función, intervaloDeTiempo[, param1, param2, ... , paramN]);

El problema con lo que estás intentando, es que ejecutas la función que quieres pasar a setInterval y su resultado es lo que intenta ser ejecutado:

function ejecutarLuego(texto) {
  console.log(texto);
  return 1;
}

//lo siguiente no funciona

setInterval(ejecutarLuego('Hola mundo'),1000);

//porque es equivalente a

let resultado=ejecutarLuego('Hola mundo');
setInterval(resultado,1000);

//lo correcto es:

setInterval(ejecutarLuego, 1000, 'Hola, mundo');

Existe también la opción de encerrar la función que quieres ejecutar en otra:
setInterval(() => {
  ejecutarLuego('Hola mundo');
},1000);

O tener una función que genere otra, usando clausuras:
function generarFuncion(...parametros) {
   return function() {
     ejecutarLuego(...[parametros);
   }
}

setTimeout(generarFuncion('Hola, mundo'), 1000);


text:
Q: jQuery - wildcard character * - Caching Guys i am facing a problem with wildcard character in jquery. Please help if possible.
I am using jQuery like function for binding a click to an id eg. proceed_10,proceed_11. Now if i click on proceed_10 for first time everything works fine. But if i click on an image with id as proceed_10  again then it executes twice.Then if i click on some other proceed image with id proceed_5 it executes thrice. Here is a minor code snippet to review :
$("[id*='applybut_']").live('click',function(){

        var idfinder = null; var currid = null;
        idfinder = $(this).attr('id').split('_');
        currid = idfinder[1];
        $.ajax({
            url: "someurl",
            type: 'POST',
            dataType: 'json',
            data: {},
            error: function(data){ },
            success: function(data){
                if(data.success == true)
                {
                    messyhtml+= '<img src="'+proceedimgsrc+'" id="proceed_'+currid+'" style="cursor:pointer;">';
                    $("[id*='proceed_']").live('click',function(){
                        var foostr = $(this).attr('id').split('_');
                        var fooid = foostr[1];
                        var barid = $('input[name="bar_id"]:checked').val();
                            if(fooid != '' && barid != '')      //This loops executes twice,thrice, and so on...
                            {
                                $.ajax({
                                    url: "someurl",
                                    type: 'POST',
                                    dataType: 'json',
                                    data: {'fooid':fooid,'barid':barid},
                                    error: function(data){ },
                                    success: function(data){
                                        if(data.success == true) {
                                            //
                                        } else if(data.success == false) {
                                            //
                                        }
                                    }
                                });
                            }

                    });
                    $(".popcontainer").html(messyhtml);
                }
            }
        });
    });

A: This line solved my problem :
$("[id*='proceed_']").die();

A: The line which reads...
$("[id*='proceed_']").live('click',function(){

...is being executed each time a click is made as it's embedded within the event handler for...
$("[id*='applybut_']").live('click',function(){

The upshot of this is that you are subscribing multiple (identical) handlers to all proceed_* items - one each time an apply_but_* is clicked. Hence your behaviour.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which smartphone OS would you choose for your users? While we currently only use windows mobile smartphone, my boss seems less and less reluctant to try and choose a new kind of OS for our users corporate phones.
For some reasons, we can't use a Blackberry Enterprise Server, so i guess our only choice is between Iphone OS and Android (or Blackberry without BES ? I don't really know if this works fine)
We need activesync capable smartphones of course, and activesync security policies must be available (pin when using your phone for example). Centralized Phone management would be nice too :D
Any ideas on what should be the best smartphone to choose for our users ?
Edit :
My users expectations are full email, contact and calendar integration. Users can't plug anything to their computers, so everything must be done oveer the air. From our side, security matters, security policies like password protected access to the phone are almost mandatory.

A: With Exchange/ActiveSync and no Blackberry Enterprise Server, here is how I see it break down.
Windows Mobile
Pros: Full support for ActiveSync, Office apps and Office Communicator Mobile (OCS).  Full security benefits of ActiveSync.  Most likely to have third-party software available for your VPN or similar such things. Large selection of carriers.
Cons: Obviously, Windows Mobile is getting old and crusty compared to the competition.  7 will be out latter this year but software will probably need to be rewritten for managed code.  Mobile 7 may end up being great, but its hard to say at this point.  Some smaller carriers don't have a good Windows Mobile selection.
iPhone
Pros: Great ActiveSync support and good support for the security features of ActiveSync.  Multiple mailbox support coming in OS 4.  You certainly can't complain about the iPhone OS and UI.  OCS support is available with iDialog, but it is not free.
Cons: Currently locked to AT&T, and honestly, their data coverage sucks if you have a traveling workforce -This may not be an issue by the end of the year. You will probably have to support iTunes on your desktops.  Its possible the iPhone may lag behind in new Exchange features since they are not Microsoft.
Android
Pros: Good selection of carriers although some smaller carriers won't have Android phones.  UI is quick and the OS is "open".
Cons: Exchange support is currently only supported with NitroDesk TouchDown.  The software works but it does not integrate real well with the OS.  Additionally, I'm not sure if you are going to find Communicator software, and third-party VPNs probably don't have applications available yet.
BlackBerry
Pros: It's a popular phone that your business users may already be familiar with.  It has a good set of "business" apps available as that is the target market of the OS.  Good selection of phones and carriers.
Cons: ActiveSync will only work by installing an application called AstraSync. AstraSync works but it is not as good as using BES.  There is also an outside chance that RIM won't allow these guys to operate forever because it cuts in to their BES sales.
My recomendation - We use all four phones in our environment where we need ActiveSync support (no BES).  I would recommend the iPhone except for the fact that AT&T is basically your only carrier choice.  With that in mind right now, I think Windows Mobile 6.5 is the way to go.  It's going to give you the best support for Exchange and the most flexibility with carriers and coverage.  If possible though, I would get one of the few models that will be upgradeable to 7 when it comes out.
If Apple releases a CDMA version later this year (which is likely) than I would take a much closer look at that especially with the new features in the v4 OS.

A: It depends on your environment and user expectations.  Do they want full e-Mail integration?  Full contact and calendar integration?  Specifications change everything.  Manual desktop syncing can be done with any phone.
I've successfully used iPhones in a professional environment.  Believe it or not, ActiveSync over the air (OTA) and Exchange is awesome.  "Remote bricking" with OWA even works well.  I suspect PocketPC solutions are comparable but may have advantages for full AD integration.
Blackberries are the older standard, which many people still use prolifically in professional environments.  Blackberry Enterprise Server is not necessarily a requirement but is advised.  Most solutions without it are compromises and not suitable for a larger company.  For a small company, suitable compromises could be had.  I've not found any that I'd blanketly recommend.
I would like to move to Android but I've not tested it yet.  One of the main issues I see there is lack of OTA sync with Exchange and general Exchange syncing issues.

A: We are using Apple Iphones with Contacts/Calendar/Mail intégration (Exchange 2007) and it works very well, in the past we used Symbian and Mail for Exchange and the intégration went smooth also. I can't comment on Android as the tests are just about to begin.


text:
Q: How to consolidate 2 database calls I'm not experienced with WordPress so please excuse me if the question is stupid.
I have a custom template page that displays record information obtained from database. This page also call get_header() to generate the header part of the page.
I want that the page title (in HEAD HTML) will display some of the record information also.
What is the best way to do this, the "WordPress way", with 1 database query?
Currently I execute 2 identical database queries: one in add_filter('wp_title', myfunc) @ function.php and the other in my custom template PHP. This duplication looks wrong.

A: OK, figured that out... I guess I have to use global wordpress database connection ($wpdb)


text:
Q: while using substring to print a character pattern why has i been initialized to 1 instead of 0? I understand this program the only doubt is in the part where i has been initialized to 1. As strings are stored like arrays the place at 0 should have the first character of the string right ? then why is it one. i would appreciate if you could also help me with understanding how substring method works :)).
sample input: SCHOOL
sample output:
S
SC
SCH
SCHO
SCHOO
SCHOOL

 /*taking SCHOOL as example and print S SC SCH ...*/
import java.util.*;
public class substring
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("enter a string");
        String word = sc.next();

        int x= word.length();

        for( int i = 1; i<=x; i++)
        System.out.println(word.substring(0,i));
    }

}

A: In the String.substring (int begIndex, int endIndex) method, endIndex doesn't index the last character of the substring. It indexes the character after the last character of the substring.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)

Thus, the length of the substring is endIndex-beginIndex


text:
Q: IBM Bluemix Single Sign On (SSO) import metadata error FBTRBA331E We have a Single Sign On service connects to our Node.js app on IBM Bluemix. We need to use SAML Enterprise as our identify source. When I upload the SAML 2.0 Identity Provider metadata file - I get the error saying:
Error executing REST service.
FBTRBA331E The action: Import Metadata failed because the metadata file or federation role is invalid.

I also found the error code from another IBM page, but it doesn't say how to fix it.
http://www.ibm.com/support/knowledgecenter/SSELE6_8.0.1.3/com.ibm.isam.doc/messages/messages/FBTRBA331E.html

A: According to this Bluemix SSO document (scroll down to the SAML metadata files section):
https://console.ng.bluemix.net/docs/services/SingleSignOn/saml_information.html#saml_information
IdP (Identify Provider) metadata file must contain both Signing and Encryption Key sections. If the encryption certificate is missing, you see an upload error indicating that the format of the metadata file is wrong or that improper federation roles exist.
Both of the following KeyDescriptor sections are required.
<md:KeyDescriptor use="signing">
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<X509Data>
<X509Certificate>(...signing certificate...)</X509Certificate>
</X509Data>
</KeyInfo>
</md:KeyDescriptor>

<md:KeyDescriptor use="encryption">
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<X509Data>
<X509Certificate>(...encryption certificate...)</X509Certificate>
</X509Data>
</KeyInfo>
<md:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
</md:KeyDescriptor>

Please double check the metadata file you received from your Identity Provider to see if the encryption section is missing.


text:
Q: Service broker error: {"description"=>"Not permitted on a disabled service instance: 10301"} I attached a SQL DB service to a bluemix app. Later I created a new app. I then unbound the SQL DB service from first app.
When I Try to bind the service to the new app I get error -
Service broker error: {"description"=>"Not permitted on a disabled service instance: 10301"}
Anybody has any idea?

A: A service instance would normally be disabled if there was a billing issue i.e. you have a charge on the service but your credit card was declined. If you was using the Free Beta plan for SQLDB then it shouldn't be a billing issue.
The only thing you can do is to send the information about your service instance (id etc) to Bluemix Support to look at your particular service instance to find out what the problem is.


text:
Q: Two-port circuit analysis. Voltage gain

I am trying to find the general equations for the voltage gain(Not sure if it is the write word for it). My textbook offers an derived equation but not the procedure. I would appreciate it if someone could show me how this is derived.(zxx are the z-parameters of the "some circuit" circuit)
$$
Hv(j\omega )= \frac{U_{2}}{U_{0}} = \frac{z_{21}(Z_{g}+Z_{b})}{(Z_{g}+z_{11})(Z_{b}+z_{22})-z_{12}z_{21})}
$$
EDIT: The upper picture is the original circuit. To this circuit we add another circuit. The equation above gives the ratio of the new voltage on the load(U2) to the original voltage on the load(U0).

A: Here you should find your answer at the half of the page, where is an example which is identically to yours. If you solve it analytically how it is shown there with the same equations and derivate the transfer function U2/U0, then you should have your answer.
This is how you solve it:
$$
1: U_1 = Z_{11}I_1+Z_{12}I_2\\
2: U_2 = Z_{21}I_1+Z_{22}I_2
$$
with equations:
$$ 3: U_1= U_0-Z_gI_1\\4:I_2=-\frac{U_2}{Z_b}$$
Insert eq. 3 and eq. 4 to eq. 1 and eq. 2 afterwards solve eq. 1 to \$I_1\$ and insert it to eq. 2. You can now solve the transfer function \$ H= \frac{U_2}{U_1}=\dots \$
Cheers


text:
Q: Python program to check whether a list is a valley or not example of a valley:
9,6,5,4,10,13,40,55,68
The list must be strictly decreasing until one point and then after the list must be strictly increasing. Then it is considered as a valley.
constraints:
Use two pointer approach
Guys, I have come up with this code:

def isValley(n,j,n1):
    i = 0
    res = False
    while(i<j):
        if (n[i]>n[i+1]) and (n[j]>n[j-1]):
                n1.append(1)
        else:
            n1.append(0)
        res = n1.count(n1[0]) == len(n1)
        i+=1
        j-=1
    print(n1)
    if res:
        if(n1[0] == 1):
            print("Valley")
        else:
            print("Not a valley")
    else:
        print("Not a valley")

n = list(map(int,input("Enter the numbers : ").split()))
n1 = []
j = len(n)-1
print(n)
isValley(n,j,n1)

my code is working only when the no of elements on the left side of the element is equal to
the number of elements on the right side of the element.
please correct this and come up with a code that even satisfies irrespective of the number
of elements left of the element and right of the element.
hint:
I think i have issue while making comparisions
(Use Two pointer Approach only)
Please help me out guys

A: I think you can just iterate from left to right (and from right to left), while the elements are strictly decreasing (increasing). Then it's a valley if and only if the pointers end up at the same location
def isValley(array):
    N = len(array)
    front_i = 0
    back_i = N-1
    while front_i < N-1 and array[front_i] > array[front_i + 1]:
        front_i += 1
    while back_i > 0 and array[back_i] > array[back_i - 1]:
        back_i -= 1
    is_valley = (front_i == back_i)
    return is_valley

print(isValley([9,6,5,4,10,13,40,55,68])) # prints True

A: You can check that there is a strictly negative gradient followed by a strictly positive gradient. One way of doing this (using numpy) is:
import numpy as np

def isValley(array):
    d = np.diff(array)
    return (
        np.array_equal(
            np.concatenate((np.argwhere(d < 0), np.argwhere(d > 0))).flatten(),
            np.arange(len(array) - 1)
        )
    )


text:
Q: How does one deal with "bounty hunters"? I asked a question on StackOverflow recently, and got no answers. I applied a 500 point bounty to said question in an attempt to encourage answers. The only answer I have as of yet is someone obviously trying to "steal the bounty" -- i.e. the posted link is only vaguely related to the question I actually asked.
Is there a way to prevent the bounty award to that particular answer when time runs out on the bounty?

A:
..ending in 7 days

I disagree with how the system works, but the way it works your bounty will do very little to nothing during the first 6 days.
In fact, based on my personal experience and not hard data, it's unlikely to even get a single answer during the beginning of the bounty period.
But fear not! During the last day, and last hours in particular, when your question will be at the top of the Featured tab, you will get tons of good answers.
You just need to have a little patience. =)
EDIT: this also means that only in exceptional circumstances you should accept an answer before the very end of the bounty period, since it's very possible you will get an even better answer then.

A:
Is there a way to prevent the bounty award to that particular answer when time runs out on the bounty?

Self-answering and awarding the bounty to that answer (thus losing the amount) is perfectly acceptable in such cases IMO.
A downvote on the frivolous answer will help prevent the auto-accept mechanism from awarding it to it: You need at least 2 upvotes to qualify for auto-awarding.

A: That particular answer is a hidden promotion, as it seems from context. So it won't get even 2 upvotes as it's unrelated to your question. I would be more concerned about those two answers, that have got two upvotes already, while being not real answers but more of an attempt to get a bounty.


text:
Q: Remove data within html tags - Python I am trying to remove some data between Html tags like for example,
I have:

    .. balaba ..
    .. baz..

and I would like to remove all nav to get something like that  .
I tried with BeautifulSoup and regex but I can not find informations
if I want to delete all nav, whatever their parameters and keep what's left

A: >>> import re

>>> s = '  .. balaba ..   .. baz.. '

>>> re.sub('','',s)
'  '

A: @Khalil's solution --  use regex to replace everything from the first  with nothing -- is probably the simplest answer for the specific example you gave.
For the more general issue of cleanly removing some set of html tags and their contents, you can use the decompose() method in BeautifulSoup:
from bs4 import BeautifulSoup

doc = """
    .. balaba ..
   keep me here
    .. baz..
"""

soup = BeautifulSoup(doc)
for i in soup('nav'):
    i.decompose()
soup

#
#
#   keep me here
#
#

You can use this to remove any set of tags that you can select with BeautifulSoup.


text:
Q: How to write capital alpha? Unfortunately, the command \Alpha does not produce capital version of \alpha (as one might expect in analogy with how, say, \Pi produces capital \pi). It so happens that the capital alpha looks rather similar to A, but that doesn't mean that there aren't situations where I would like to use capital alpha in a formula. For instance, suppose I already have \pi which belongs to a set \Pi, and then \alpha comes along and I need a name for the set of its possible values.
What is the best way to write capital alpha?
The obvious first attempt is to just write A. But it's not right - A produces italic A, while Greek letters are by default not italic. Would \mathrm{A} do the trick, or is there some subtle issue I'm not noticing? Is there a package that will save me the work of defining all capital letters by hand?

A: I would recommend unicode-math and Sergei Golovan's solution if you are able to use it.  Fewer and fewer publishers force you to use PDFTeX.
Here is a PDFTeX-compatible solution that produces a Greek Α and Β instead of a Latin A and B:
\documentclass[varwidth]{standalone}
\usepackage[LGR, T1]{fontenc}
\usepackage[utf8]{inputenc}

\usepackage{lmodern, amsmath}

\newcommand\mupAlpha{\mathord{\text{%
\fontencoding{LGR}\upshape\selectfont \textAlpha}}}
\newcommand\mupBeta{\mathord{\text{%
\fontencoding{LGR}\upshape\selectfont \textBeta}}}

\begin{document}
\( \mupAlpha + \mupBeta = \Gamma \)
\end{document}

I chose the names \mupAlpha and \mupBeta, which are compatible with unicode-math, because they always produce a regular-weight, upright letter.  It would also be possible to define italic \mitAlpha and bold \mbfAlpha by inserting \itshape or \bfseries.  Or you could call it \Alpha.
Another alternative is to declare LGR-encoded symbol alphabets and \DeclareMathSymbol, but be careful you don't run out of math alphabets, which are a limited resource in the legacy toolchain.  There are a number of packages that define Greek math-mode fonts, including upgreek.  Both mathastext and isomath have options to load a LGR font for your Greek letters in math mode.
In theory, you could try the alphabeta package to use commands such as \Alpha in either text or math mode, and also insert the Unicode characters in math mode.  However, it produces inconsistent results: Α + Β = Γ.  In practice, if you want to mix different scripts, you're much better off with Unicode and the modern toolchain designed for that.

A: This works with the default Computer Modern fonts. A different font family should be chosen if the font is different (and it should have support for the LGR encoding).
I redefined also \Delta because the correspondence when copying maps the standard \Delta to U+2206 INCREMENT.
\documentclass{article}
\usepackage[LGR,T1]{fontenc} % or OT1

\DeclareSymbolFont{upgreek}{LGR}{cmr}{m}{n}
\SetSymbolFont{upgreek}{bold}{LGR}{cmr}{bx}{n}

\DeclareMathSymbol{\Alpha}{\mathord}{upgreek}{`A}
\DeclareMathSymbol{\Beta}{\mathord}{upgreek}{`B}
\DeclareMathSymbol{\Delta}{\mathord}{upgreek}{`D}
\DeclareMathSymbol{\Epsilon}{\mathord}{upgreek}{`E}
\DeclareMathSymbol{\Zeta}{\mathord}{upgreek}{`Z}
\DeclareMathSymbol{\Eta}{\mathord}{upgreek}{`H}
\DeclareMathSymbol{\Iota}{\mathord}{upgreek}{`I}
\DeclareMathSymbol{\Kappa}{\mathord}{upgreek}{`K}
\DeclareMathSymbol{\Mu}{\mathord}{upgreek}{`M}
\DeclareMathSymbol{\Nu}{\mathord}{upgreek}{`N}
\DeclareMathSymbol{\Omicron}{\mathord}{upgreek}{`O}
\DeclareMathSymbol{\Rho}{\mathord}{upgreek}{`R}
\DeclareMathSymbol{\Tau}{\mathord}{upgreek}{`T}
\DeclareMathSymbol{\Chi}{\mathord}{upgreek}{`Q}

\begin{document}

$\Alpha\Beta\Gamma\Delta\Epsilon\Zeta\Eta\Theta\Iota\Kappa\Lambda\Mu$

$\Nu\Xi\Omicron\Pi\Rho\Sigma\Tau\Upsilon\Phi\Chi\Psi\Omega$

{\mathversion{bold}$\Alpha\Beta\Gamma\Delta$}

\end{document}

You could also avoid the dependency from LGR, but in this case you have to set up a font family in the U encoding.

Below what I get by copy-paste:
ΑΒΓΔΕΖΗΘΙΚΛΜ ΝΞΟΠΡΣΤΥΦΧΨΩ ΑΒΓΔ

If you define \Alpha as \mathrm{A} you just get the same glyph, but upon copying it would be A.

A: If you're using LuaLaTeX or XeLaTeX, you can use the unicode-math package. It defines all uppercase Greek letters:
\documentclass{article}
\usepackage{unicode-math}
\begin{document}
$\Alpha+\Beta=\Gamma$.
\end{document}

The result is:

This way has an advantage in that one can change the style of the letters by altering the unicode-math options. For example \usepackage[math-style=ISO]{unicode-math} without any other changes yields:

Also, this way alpha can be copied&pasted from the resulting PDF.

A: Screenshot from lshort.pdf (The Not So Short Introduction to LaTeX2e):

So it is simply \mathrm{A}.
\documentclass{standalone}
\newcommand\Alpha{\mathrm{A}}
\begin{document}
$\Alpha+\Pi=\Gamma$
\end{document}


text:
Q: View shopping cart function not returning proper values So my goal is to create a psuedo shopping cart with vanilla JS for a coding assignment and one of the goals is to create a viewCart() function that does not accept any arguments.
Instructions: It should loop over every item in your cart, printing out the contents as one long, coherent statement in this format: In your cart, you have bananas at $17, pancake batter at $5, and eggs at $49.
Conditions:

*

*If the cart is empty, the function should instead print out: Your
shopping cart is empty.

*1 item sample output: In your cart, you have bananas at $17.

*2 items — In your cart, you have bananas at $17 and pancake batter at
$5.

*3+ items — In your cart, you have bananas at $17, pancake batter at
$5, and eggs at $49.

So far I have successfully completed the first two conditions and have almost completed the third one. However, my function will return something like this:
In your cart, you have bananas at $17, and  pancake batter at $5eggs at $49.
Instead of:
In your cart, you have bananas at $17, pancake batter at $5, and eggs at $49.
I added some comments in the function to help you guys debug if you need it.
  var cart = [];

    function getCart() {
     return cart;
    }

    function setCart(c) {
      cart = c;
      return cart;
    }

    function addToCart(itemName) {
     var object = {[itemName]: Math.floor(Math.random(1,100) * 100)};
     cart.push(object);
     console.log(`${itemName} has been added to your cart`);
     return cart;
    }

 function viewCarted() {
  if(!cart.length) {
    console.log('Your shopping cart is empty.');
  }
  else {
    var items = [];
    // for loop to iterate over objects in cart
    for(var i=0; i < cart.length; i++) {
      // another for loop to iterate over the object's keys
      for(var item in cart[i]) {
        // adding the key and value into the items array
        items.push(item + " at $" + cart[i][item]);
      }
    }
    //  checking if items array length is equal to 2
    // if it is, then it'll add an "and" after the first comma and finish the function
    // if not then output will be: In your cart, you have banana at $77.
    if(items.length == 2) {
      return(`In your cart, you have ${items.join(" and ") + "."}`);
    }
    // otherwise if there is three or more items in the cart then these conditions will activate
    else {
      // another for loop to iterate over the cart array
      for(var x=0; x < cart.length; x++) {
        // testing to see the indexes: 0,1,2
        console.log(x)
        // condition to see if it isn't the last item in cart
        if(x+1 != cart.length) {
           console.log(`In your cart, you have ${items.join(", ") + "."}`);
        }
        // condition if it is the last item
        else {
          const mostItems = items.slice(0, -1);
          const lastItem = items.slice(-1)[ 0 ];
          console.log(`In your cart, you have ${mostItems.join(", and ")}${lastItem}.`);
        }
      }
    }
  }
}

  addToCart("banana")
  addToCart("a")
  addToCart("b")
  viewCarted();

Output:
0
In your cart, you have banana at $40, a at $62, b at $75.
1
In your cart, you have banana at $40, a at $62, b at $75.
2
In your cart, you have banana at $40, and a at $62b at $75.

A: You are joining all the items with , and ... instead of just the last one in your last conditional.
Instead, you can split them into "all - 1" and "last" like this:
    else {
       const mostItems = items.slice(0, -1);
       const lastItem = items.slice(-1)[ 0 ];
       console.log(`In your cart, you have ${mostItems.join(", and ")}${lastItem}.`);
    }

Place this in the following else:
    // condition to see if it isn't the last item in cart
    if(x+1 != cart.length) {
       console.log(`In your cart, you have ${items.join(", ") + "."}`);
    }
    // condition if it is the last item
    else {
       // new stuff goes here:

       // OLD STUFF
       // console.log(`In your cart, you have ${items.join(", and ") + "."}`);
    }


text:
Q: preg_match expression for extracting everything but "[]" <some string>[]<somestring>

example
variable[]_abc

How can I get everything except [] from the string using preg_ in php?

A: preg_replace('/\[\]/','',$string);

A: If you only want to remove [] use str_replace.
$newstring = str_replace('[]', '' $string);

There is no need for a regex to remove static characters.


text:
Q: creating groups under specific conditions I've the following table A (this is just sample) which presents the channel the customer make a reservation:
custNum  channelType  reservationNumber
 1        web           1
 2        Iphone        2
 1        Android       3
 3        web           4

and I'm trying to separate between 3 groups of customers (I'd like to get their cust numbers):
1. customers who used only the web
2. customers who used only the cellular channels
3. customers who used both
under the sample above, the results should be:
1. web only (custNum=3)
2. cellular only (custNum=2)
3. web+cellular (custNum=1)
I'd tried the following for web usesr only (but I know it's wrong):
sel custNum from A where channelType in ('web');

any help will be appreciated.

A: You need to do some conditional aggregation like this:
select custNum,
   case
      when max(case when channelType = 'web' then 1 else 2 end) = 1
        then 'web only'
      when max(case when channelType = 'web' then 2 else 1 end) = 1
        then 'celular only'
      else 'both'
   end
from tab
group by custNum


text:
Q: Custom converter Error in h:SelectOneMenu I have a problem implementing a custom converter...
my xhtml is:
...
<span class="cien">
    <h:outputLabel value="Director de Area Correspondiente:"
        styleClass="negritas" />
    <h:selectOneMenu value="#{ordenBO.director}" id="director-area"
        converter="superiorAuditoriaConverter"
        converterMessage="Error al seleccionar el Director">
        <f:selectItems value="#{ordenBO.directores}"></f:selectItems>
    </h:selectOneMenu>
    <p:message for="director-area"></p:message>
</span>
...

this is how I fill my h:SelectOneMenu:
...
this.directores = new ArrayList<SelectItem>();
for (SuperiorAuditoriaDTO sup: daoSuperiorAuditoria.getDirectoresASM())
    this.directores.add(new SelectItem(sup, sup.getProfesion() + " " +
        sup.getNombre_completo()));
...

this is my Custom converter:
....
@FacesConverter(forClass = SuperiorAuditoriaDTO.class, value =
    "superiorAuditoriaConverter")
public class SuperiorAuditoriaConverter implements Converter {

    private static SuperiorAuditoriaDAO dao = new SuperiorAuditoriaDAO();

public Object getAsObject(FacesContext arg0, UIComponent arg1, String id_persona) {
    SuperiorAuditoriaDTO s = null;
    try {
        s = dao.getSuperiorASM(Integer.parseInt(id_persona));
    } catch(Exception e) {
        e.printStackTrace();
    }
    return s;
}

public String getAsString(FacesContext arg0, UIComponent arg1, Object auditor) {
    return String.valueOf(((SuperiorAuditoriaDTO) auditor).getId_persona());
}

}

Can somebody help me?? I always got an error message saying that the value that I try to convert is not valid..
I'm using jsf 2 mojarra...
and I also have equals and hashCode method implemented...
thanks..

A:
I always got an error message saying that the value that I try to convert is not valid.

Thus, you got "Validation error: Value not valid"? That will happen when the equals() method on the selected object has not returned true for any of the available select items. In other words, the equals() method of SuperiorAuditoriaDTO is broken. Fix it accordingly.
See also:

*

*Right way to implement equals contract


text:
Q: Initializing circular data in C. Is this valid C code according to any standard? I wanted to see if I could initialize a global variable to point to itself:
#include <stdio.h>
struct foo { struct foo *a, *b; } x = { &x, &x };
int main()
{
    printf("&x = %p, x.a = %p, x.b = %p\n", &x, x.a, x.b);
    return 0;
}

This code compiles and runs as expected with gcc (all three pointers print identically).
I want to know:

*

*Is this reliable?

*Is this standard?

*Is this portable?

EDIT: Just to clarify, I am questioning the availability of the address of x in its own initializer.

A: Yes to all of the above. You have a couple of pointers that you're initializing with the same address, so they hold the same address, and that's the same as the address with which you initialized them.
Perhaps more interestingly, x.a is also guaranteed to point to itself (i.e., the first element in a struct is guaranteed to be at the very beginning of the struct, so a pointer to the struct, converted to the type of the first element, is guaranteed to point to that first element.

A: This is standard C code.
This paragraph of the mighty Standard permits it (emphasis mine):

(C99, 6.2.1p7) "Structure, union, and enumeration tags have scope that begins just after the appearance of the tag in a type specifier that declares the tag. Each enumeration constant has scope that begins just after the appearance of its defining enumerator in an enumerator list. Any other identifier has scope that begins just after the completion of its declarator."

For information, note that to illustrate the last sentence of 6.2.1p7, the book "The New C Standard" by Derek M. Jones uses an example similar to yours:
struct T {struct T *m;} x = /* declarator complete here. */ {&x};


text:
Q: Instant messaging not working in Tuleap I have recently installed Tuleap in a VPS. But when I see that when I go to instant messaging page, it opens a pop-up and says "Service unavailable".
When I go to instant messaging plugin administration, it says the following-
WARNING: If you synchronize one or several groups here, you will have to restart the Openfire server by executing "service openfire restart" as root in a shell window. This will interrupt all ongoing chat sessions!

Projects to synchronize:
All projects are synchronized with the instant messaging services.

How can I correctly configure instant messaging in my server?

A: try to connect to the service with a jabber client, to confirm that it is the jabber server which does not work or the widget in the instant messaging page.


text:
Q: Exclude current population of journey from email send audience Problem:
I'd like to exclude customers who are currently in journeys A and B from receiving newsletter send C.
Possible solution:
The only way I could come up with yet involves the following steps:

*

*Get the TriggeredSendCustomerKeys of the triggered sends for the first email send activities of journeys A and B.

*Create an Automation containing a SQL query activity that retrieves the SubscriberKey from Sent data view and filters by EventDate plus maximum journey duration greater than the current date for the TriggeredSendCustomerKeys of step 1.

*Use the created data extension as exclusion for the newsletter send.

Question:
Is there an easier and more accurate (different journey paths could have different durations) possibility to exclude contacts currently inside a specific journey or a defined set of journeys from the audience of an email send within Email Studio? Querying the current population of a journey would be a more straightforward approach, unfortunately I couldn't find any documentation on this.

A: There would be a few different approaches to applying the suppression of these subscribers to your Newsletter. I'm going with Filters, here, but you could look at Auto-Suppression Lists, Exclusion Lists at time of send or SQL. To determine whether the contact is currently in a Journey, I would propose using Update Contact Activities at the entry and all exits from your Interactions
You could consider creating a data extension like this called "JourneyStatus":

To Allow you to use this in Filters, create a new Data Relationship:
Add an Update Contact Activity to set the Contacts "InJourneyA" or "InJourneyB" field to true at the beginning of the Interaction.

Add Update Contact Activities at each exit from the Interaction. If you have many exits from your Journey use Join Activities to Join all the exits to a single path and place your Update Contact Activity on the final single joined path:

Create a Filter Activity or Filtered DE to use for sending your Newletter with "InJourneyA = False AND InJourneyB = False" as your selection criteria:


text:
Q: Installing Python sikuli package (problems installing pyjnius) Windows 7 Python 2.6 I am working on a Windows7 PC with Python 2.6.  I want to import sikuli into Python.  I have a problem installing pyjnius.  Here are some of the errors I have been encountering:
C:\Users\x\Documents\Public\pyjnius\pyjnius-master>easy_install sikuli
Searching for sikuli
Reading https://pypi.python.org/simple/sikuli/
Best match: sikuli 0.1
Downloading https://pypi.python.org/packages/source/s/sikuli/sikuli-0.1.tar.gz#md5=c83294c6860858437572e6322ea03daf
Processing sikuli-0.1.tar.gz
Writing c:\users\x\appdata\local\temp\easy_install-dbost9\sikuli-0.1\setup.cfg
Running sikuli-0.1\setup.py -q bdist_egg --dist-dir c:\users\x\appdata\local\temp\easy_install-dbost9\sikuli-0.1\egg-dist-tm
p-c7taex
Searching for jnius>=1.1-dev
Reading https://pypi.python.org/simple/jnius/
No local packages or download links found for jnius>=1.1-dev
error: Could not find suitable distribution for Requirement.parse('jnius>=1.1-dev')

and then for pyjnius I get:
C:\Users\x\Documents\Public\pyjnius\pyjnius-master>easy_install pyjnius
Searching for pyjnius
Reading https://pypi.python.org/simple/pyjnius/
Best match: pyjnius 1.3.0
Downloading https://pypi.python.org/packages/source/p/pyjnius/pyjnius-1.3.0.tar.gz#md5=a65f17fdc95e08f5d3de3188359f4104
Processing pyjnius-1.3.0.tar.gz
Writing c:\users\x\appdata\local\temp\easy_install-or9uvd\pyjnius-1.3.0\setup.cfg
Running pyjnius-1.3.0\setup.py -q bdist_egg --dist-dir c:\users\x\appdata\local\temp\easy_install-or9uvd\pyjnius-1.3.0\egg-d
ist-tmp-kujh4w
warning: no files found matching '*COPYING'
error: Setup script exited with error: None

I downloaded pyjnius and run the setup:
C:\Users\bsprott\Documents\Public\pyjnius\pyjnius-master>python setup.py install
C:\Python26\lib\distutils\dist.py:266: UserWarning: Unknown distribution option: 'install_requires'
  warnings.warn(msg)
running install
running build
running build_py
running build_ext
skipping 'jnius\jnius.c' Cython extension (up-to-date)
building 'jnius' extension
error: None

A: You did not satisfy the requirements (Python 2.7). Take a look here https://github.com/kevlened/sikuli_cpython#requirements


text:
Q: reduction of that clause "we know that they don't take excellent decisions that causes that the covid-19 ends"
"we know that they don't take excellent decisions causing the covid-19 ends"
in firs sentence, I want to reduce last "that clause" but I'm not sure whether it's correct

A: To begin with the initial sentence is not correct. You might write it that way instead.

*

*we know that they don't take the  decisions that would cause  the pandemia of covid-19 to end.

You can't use a that-clause with the verb "cause" (ref.).
.


text:
Q: How to save .wav file in MFC (use file dialog) void CRecordToMFCDlg::OnBnClickedButton7()
{
    /*TCHAR szFilter[] = _T("모든 파일(*.wav) || *.wav ||");
    CFileDialog dlg(FALSE, _T("all files"), _T("*.wav"),OFN_HIDEREADONLY| OFN_OVERWRITEPROMPT, szFilter);
    if (dlg.DoModal() == IDOK)
    {
        AfxMessageBox(dlg.GetPathName());

    }*/

    TCHAR szFilter[] = _T("wavefile(*.wav) || *.wav ||");
    CFileDialog dlgFile
    (false, _T("wavefile files"), _T("*.wav"), /*OFN_HIDEREADONLY |*/ OFN_OVERWRITEPROMPT, szFilter);

    if (IDOK == dlgFile.DoModal())
    {

        CString strPathName = dlgFile.GetPathName();

        CFile fScheduleWrite;
        if (!fScheduleWrite.Open
        (strPathName, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary))
        {
            AfxMessageBox(_T("File Write Open Error"));
            return;
        }

    }

}

This code can save file but there isn't no data, I think that this code can't save my recording file cause this can't receive record data. How can I solve this problem? Does require related wave file header or format ?? Please answer me, if necessary upload header and code. Please

A: The code you have shown obtains a target filename from the user and then creates the file, but it does not attempt to write any data to that file.
After fScheduleWrite.Open() is successful, you need to write your WAV data to the file as needed.
Nobody here can help you with that, as you did not indicate where your WAV data is coming from, or how it is being generated so you can access it for saving. There are many ways, many APIs, many libraries, that are able to produce WAV data.


text:
Q: SQL Server : How to subtract values throughout the rows by using values in another column? I have a table named stock and sales as below :
Stock Table :
+--------+----------+---------+
| Stk_ID | Stk_Name | Stk_Qty |
+--------+----------+---------+
| 1001   | A        | 20      |
| 1002   | B        | 50      |
+--------+----------+---------+

Sales Table :
+----------+------------+------------+-----------+
| Sales_ID | Sales_Date | Sales_Item | Sales_Qty |
+----------+------------+------------+-----------+
| 2001     | 2016-07-15 | A          | 5         |
| 2002     | 2016-07-20 | B          | 7         |
| 2003     | 2016-07-23 | A          | 4         |
| 2004     | 2016-07-29 | A          | 2         |
| 2005     | 2016-08-03 | B          | 15        |
| 2006     | 2016-08-07 | B          | 10        |
| 2007     | 2016-08-10 | A          | 5         |
+----------+------------+------------+-----------+

With the table above, how can I find the available stock Ava_Stk for each stock after every sales?
Ava_Stk is expected to subtract Sales_Qty from Stk_Qty after every sales.
+----------+------------+------------+-----------+---------+
| Sales_ID | Sales_Date | Sales_Item | Sales_Qty | Ava_Stk |
+----------+------------+------------+-----------+---------+
| 2001     | 2016-07-15 | A          | 5         | 15      |
| 2002     | 2016-07-20 | B          | 7         | 43      |
| 2003     | 2016-07-23 | A          | 4         | 11      |
| 2004     | 2016-07-29 | A          | 2         | 9       |
| 2005     | 2016-08-03 | B          | 15        | 28      |
| 2006     | 2016-08-07 | B          | 10        | 18      |
| 2007     | 2016-08-10 | A          | 5         | 4       |
+----------+------------+------------+-----------+---------+

Thank you!

A: You want a cumulative sum and to subtract it from the stock table.  In SQL Server 2012+:
select s.*,
       (st.stk_qty -
        sum(s.sales_qty) over (partition by s.sales_item order by sales_date)
       ) as ava_stk
from sales s join
     stock st
     on s.sales_item = st.stk_name;


text:
Q: c# manage progressive identity on domain entity in a client application i have this problem modelling one of my entities:

*

*My entity must have a mandatory ID field that user use to recognize single object

*User don't want to manual enter ID but it must be generate by Application incrementing by 1 every time

*Appllication resides only on clients machine, on server there is only the db

According to 1. I create Id field as mandatory (and not nullable), in this way it must be provided to create an instance but how can program know which ID has to use?
Ideally i have to query db to get max id, add 1 and use this value but how can do it? To mee it seem a matter of my domain object, and i want to isolate domain layer from data access layer so i cant call directly repository from by entity.
Possible solutions:

*

*I look to Interlocked.Increment but how can use it if any user can create a new instance on his client?

*Move the logic to Application Logic layer: there i can call the repository, get the ID, create the class and call repository to save class. in this way a move a domain logic (the incremental id is a specific user request) out of domain layer

*Define repository interface in Domain Layer, call the interface in constructor method of my entity. All doing with dependecy injection, but how? I use ninject in my bootstrapper and all references goes from top to down, how can i revert it for domain layer making it call a superior layer avoiding service locator antipattern (otherwise a can simply write NinjectKernel.Get() in my ctor)

*i found this article and it's interesting but he use my solution in a bad way (without interface) and don't define the field as mandatory so he can create a new instance withoud specify id

Are there a better solutions?
EDIT
some code to better explain tha case:
Public MyClass {
 public int Id{get;set;}
 .....

 public MyClass(int id){
  if(id != null)
   this.Id = id;
  else
   throw (new ArgumentException)

  .....
 }
}

So i cant do MyClass mc = new MyClass(null);
but i need to have the id before
in Data Access Layer i use NHibernate and have Uow / Repository pattern
after i can get a valid ID a can write
UnitOfWork.MyClassRepository.Add(mc);

A: There's another solution, used by some high load distributed apps. The idea is to create a separate service (web service) to get you a new ID. Inside, implementation could be as simple as:
public int GetNextId()
{
    return Interlocked.Increment(ref _lastId);
}

Although you obviously have to fetch last id from database at service start.
Then, you just make each of your client apps to call this service before creating an entity.
But honestly I'd start with database generated Id or using Guids if possible.
UPDATE:
Another option. Assign a unique id (int) to each client. Then use internal counter each time you need a new Id, but mix it with client as as ClientId * 10000 + LastId. This is similar to Hi/Lo generator.

A: In your domain model you can create repository which takes id from DB. And you must create factory of your domain objects which uses repository for generating id.


text:
Q: Javascript Array Scope Issue SOLVED - This example code worked, so I compared it to the non-working I had and found a discrepancy.
In my code, the one that did not work, when declaring the color array I forgot to add a "var" before it.
m_color = [];
m_color[0] = 255;
m_color[1] = 255;
m_color[2] = 255;
m_color[3] = 255;

instead of:
var m_color = [];
m_color[0] = 255;
m_color[1] = 255;
m_color[2] = 255;
m_color[3] = 255;

That's it. No error was generated and I guess it created it as a global array shared by all the particles.
Thanks for the answers everyone. I will use them to write better javascript code.
Old question (which is no longer relevant) is below:

I have this crazy issue with javascript arrays scope.
I have a class Particle:
function ParticleClass()
{
    var m_color = [];
    m_color[0] = 255;
    m_color[1] = 255;
    m_color[2] = 255;
    m_color[3] = 255;

    var m_red = 255;
    var m_green = 255;
    var m_blue = 255;

    this.SetRandomColorRGB = SetRandomColorRGB;
    this.SetRandomColorArray = SetRandomColorArray;
    this.DrawParticleRGB = DrawParticleRGB;
    this.DrawParticleArray = DrawParticleArray;

    function SetRandomColorRGB()
    {
        m_red = Math.floor( Math.random() * 255 );
        m_green = Math.floor( Math.random() * 255 );
        m_blue = Math.floor( Math.random() * 255 );
    }

    function SetRandomColorArray()
    {
        m_color[0] = Math.floor( Math.random() * 255 );
        m_color[1] = Math.floor( Math.random() * 255 );
        m_color[2] = Math.floor( Math.random() * 255 );
    }

    function DrawParticleRGB( ctx )
    {
        // I draw the particle using m_red, m_green and m_blue.
    }

    function DrawParticleArray( ctx )
    {
        // I draw the particle using m_color[0], m_color[1], m_color[2]
    }
}

I then create an array of ParticleClass particles and draw them.
If I create a bunch of particles and try to draw them on the screen, SetRandomColorRGB and DrawParticleRGB works great. Each particle has a different color.
If I use SetRandomColorArray and DrawParticleArray, all the particles have the same color. Each time a new particle is created, all the particles change to the last color SetRandomColorArray picked.
It looks to me that arrays share memory, whereas other variables do not. Is this true? Is this a quirk of Javascript? Is something else going on?
Thanks.

A: The variable's scope is within function ParticleClass().  So variables in functions defined in this space will share the scope with its parent..
This is why sometimes you see this pattern in Javascript -
var self = this;
$('.someClass').each(function(i) {
   // function is defined as a closure
   // but it shares its scope with its parent so it can see self and access the parent's
   // pointer to this.
});

Why don't you use prototype to define to the functions...
E.g..
var myClass = function() {
  this.stuff = 1;
}
myClass.prototype.myFunc = function() {
  // Do Something..
  this.stuff += 5;
}

// Then create instances of your class with
var i = new MyClass();

This will get you the namespace you want...
Here's an example: http://jsfiddle.net/RvCgJ/

A: There's no problem with the code you posted, but having said that, you're making life more difficult by doing it this way; it's better to make proper use of prototypes:
function ParticleClass()
{
    this.m_color = [255, 255, 255, 255];

    this.m_red = 255;
    this.m_green = 255;
    this.m_blue = 255;
}

(function(p) {

p.SetRandomColorRGB = function () {
        this.m_red = Math.floor( Math.random() * 255 );
        this.m_green = Math.floor( Math.random() * 255 );
        this.m_blue = Math.floor( Math.random() * 255 );
}

p.SetRandomColorArray = function () {
        this.m_color[0] = Math.floor( Math.random() * 255 );
        this.m_color[1] = Math.floor( Math.random() * 255 );
        this.m_color[2] = Math.floor( Math.random() * 255 );
}

p.DrawParticleRGB = function( ctx ) {
        // I draw the particle using m_red, m_green and m_blue.
}

p.DrawParticleArray = function( ctx )
{
        // I draw the particle using m_color[0], m_color[1], m_color[2]
}

}(ParticleClass.prototype);

A: here... this may help explain why it is happening :
var data             = {};               // create a  data object
data.string          = "hey society";    // Add a string value property
data.num             = 0;                // Add a integer value property
data.arr             = [0,1,2];          // Add an array property
data.date            = new Date();       // Add an object property

                     // here is where the fun starts!

// Create a var for string property

var sString          = data.string;      // sets to "hey society", as expected.. cool
data.string          = "changed"         // change the value and the compare :
data.string         == sString           // returns false, the values are different

                      // same happens for a number.

// Now lets copy this array
var oArr             = data.arr;         // (seeing the comment pattern? XD)
data.arr             .push(3);           // and modify it.
data.arr            == oArr              // should be false? Nope. returns true.
                                         // arrays are passed by reference.

var oDate            = data.date           // what about objects?
data.date            .setHours(0);         // modify the variable and
oDate.getTime()     == data.date.getTime() // it returns true, too!

                      // so, how do we fix the array problem?

// right in front of yer nose
var oArrFix          = data.arr.splice(0) // get a new array based on
data.arr             .push(4)             // an unmodified version of the original
data.arr            == oArrFix            // false.. huh..

                     // How do we use this as a fix

data.arr["changed"] == false;

oArrFix              = ChangeOriginalArray( data.arr );

// When you are expecting an array..
function ChangeOriginalArray( arr )       // pass as a parameter
{
    var aArr = arr.splice(0);             // make a copy!

    if (aArr["changed"] == false)         // check has same value!
    {
        aArr["newKey"]   = "newVal";      // add a value

        arr["changed"]   = true;          // change original value
    }

    return aArr;
}

oArrFix["newKey"]       == data.arr["newKey"] // false
oArrFix["changed"]      == true               // no, created
data.arr["changed"]     == oArrFix["changed"] // nah, passed by value, not reference


text:
Q: How do I fix the if statements to work with strings? I have to make a rock paper scissors game but it the if statements wont work when I try to convert the input into string with str(.....)
I used integers here to make sure the code works fine otherwise but it just wont work with strings.
I'm also having trouble with making the input underlined when I run this code, how does one do that?
player_1 = str(input("Enter Player 1 choice (R, P, or S): "))
player_2 = str(input("Enter Player 2 choice (R, P, or S): "))

if player_1 == S and player_2 == S:
    print("A tie!")

elif player_1 == R and player_2 == R:
    print("A tie!")

elif player_1 == P and player_2 == P:
    print("A tie!")

elif player_1 == R and player_2 == 2:
    print("Rock beats scissors! Player 1 wins.")

elif player_1 == S and player_2 == R:
    print("Rock beats scissors! Player 2 wins.")

elif player_1 == 9 and player_2 == R:
    print("Paper beats rock! Player 1 wins.")

elif player_1 == R and player_2 == P:
    print("Paper beats rock! Player 2 wins.")

elif player_1 == S and player_2 == P:
    print("Scissors beat paper! player 1 wins.")

elif player_1 == P and player_2 == S:
    print("Scissors beat paper! player 2 wins.")

I get this error every time I run the code:
Enter Player 1 choice (R, P, or S): S
Enter Player 2 choice (R, P, or S): S
Traceback (most recent call last):
  File "D:\CP 104\**********\src\t03.py", line 16, in <module>
    if player_1 == S and player_2 == S:
NameError: name 'S' is not defined

What am I doing wrong?

A: For each of your cases, you are checking the value of a variable against a string. The string for each of them can be "R", "S", or "P", and in your if statements, you should write them as such
for example
if player_1 == "S" and player_2 == "S":

and so on.
and as @jedwards said, you are using python3, and the input() returns a string, so the str() wrapper in your first and second lines are not needed
you can simply say
player_1 = input("Enter Player 1 choice (R, P, or S): ")
player_2 = input("Enter Player 1 choice (R, P, or S): ")


text:
Q: Making a new pandas dataframe with columns of the values of each id in a timeseries Let's say I have a DataFrame that looks like this:
            timestamp    id  value
0 2020-09-27 10:00:00     a     10
0 2020-09-27 10:00:00     b     13
0 2020-09-27 10:00:00     c     16
0 2020-09-27 10:01:00     a     11
0 2020-09-27 10:01:00     b     14
0 2020-09-27 10:01:00     c     17
0 2020-09-27 10:02:00     a     12
0 2020-09-27 10:02:00     b     15

I would like to create a new DataFrame with columns of the value for each id at a certain timestamp.
                            a    b    c
2020-09-27 10:00:00        10   13   16
2020-09-27 10:01:00        11   14   17
2020-09-27 10:02:00        12   15  NaN

I've tried the following:
df2 = pd.DataFrame(df['timestamp'].unique())
for unique in df['id'].unique():
    df2 = df2.join(df[df['id']==unique]['value'])
    df2.rename(columns={"value": unique})

However, I get the following error: ValueError: columns overlap but no suffix specified: Index(['value'], dtype='object')
Can someone explain me what goes wrong and/or what would be a better way to get to the results?

A: You can use df.pivot
df.pivot(index=['timestamp'], columns = ['id'], values = ['value']).reset_index()

A: You can use df.pivot_table():
In [798]: df.pivot_table(values = 'value', index='timestamp', columns = 'id').reset_index()
Out[798]:
id            timestamp     a     b     c
0   2020-09-27 10:00:00  10.0  13.0  16.0
1   2020-09-27 10:01:00  11.0  14.0  17.0
2   2020-09-27 10:02:00  12.0  15.0   NaN


text:
Q: I need help creating a shell script to tell me if a process is up and running so I can monitor that process in PRTG I'm using a monitoring system called PRTG to monitor our environment.  PRTG KB suggested using a script to monitor processes called SSH Script.  The script needs to be stored in /var/prtg/scripts.
I found a script that someone used for PRTG:
#!/bin/sh

pgrep wrapper $1  2>&1 1>/dev/null

if [ $? -ne 0 ]; then
  echo "1:$?:$1 Down"
else
  echo "0:$?:OK"
fi

However, PRTG is returning the following error code within the Web GUI:
Response not well-formed: "pgrep: only one pattern can be provided Try `pgrep --help' for more information. 1:0:Wrapper Down "
However, when I run the script on the Linux server it prints out:
0:1:OK
So my question would be what would be the best script to use to tell PRTG that a process is "Down" or "UP"?
###################
Editing for further clarification:
I changed the script up and it works awesome on the command line...but it appears that the issue is with how PRTG is reading the output.  Apparently it's not in the correct format.  So here's my script:
#!/bin/bash
SERVICE="wrapper"
if pgrep -x "$SERVICE" >/dev/null
then
    echo "$SERVICE is running"
else
    echo "$SERVICE stopped"
fi

This is what PRTG is erroring out with:
Response not well-formed: "wrapper is running "

So...PRTG is saying that the sensor I'm using wants the script output into this format:
The returned data for standard SSH Script sensors must be in the following
format:

returncode:value:message

Value has to be a 64-bit integer or float. It is used as the resulting value
for this sensor (for example, bytes, milliseconds) and stored in the
database. The message can be any string (maximum length: 2000 characters).

The SSH script returncode has to be one of the following values:

VALUE                                  DESCRIPTION

 0                                         OK
 1                                       WARNING
 2                                     System Error
 3                                    Protocol Error
 4                                     Content Error

So I guess now...the question is how do I get that script to output what PRTG wants to see?

A: From the changes you made to the script, is shall look like below, and called like this example: servicecheck.sh sshd
#!/bin/sh

pgrep -x $1  2>&1 1>/dev/null

if [ $? -ne 0 ]; then
  echo "1:$?:$1 Down"
else
  echo "0:$?:OK"
fi


text:
Q: getting last committed code from git I committed some code and pushed it to my github account.Then ,I modified the code on my machine.I did not add it to the index or commit it.Now I want to remove all those modifications and make the code on my machine the same as what I committed earlier..I am somewhat confused by the various commands -like pull,reset head etc.. (My github account contains only my code ..nobody else pushes to it)
Can someone please advise me what to do here?

A: The easiest way to throw away uncommitted work is:
git reset --hard HEAD


text:
Q: Problems playing multiple sounds with TheAmazingAudioEngine I'm implementing a low-latency drum set with TheAmazingAudioEngine framework. I have a scene with a single button and a viewController with the methods below. This code works very well if I touch the button slowly. But if I touch it many times in a short period of time --- 10 times per second, for instance ---, the sound is not played in some touches, without error messages. The audio sample is short (less than 2 seconds).
Why does it happen? What is wrong in my implementation?
I choose TheAmazingAudioEngine instead of AVAudioPlayer to get low-latency between the touch and the sound.
override func viewDidLoad() {
    super.viewDidLoad()

    // Enable multiple touch for the button
    for v in view.subviews {
        if v.isKindOfClass(UIButton) {
            v.multipleTouchEnabled = true
        }
    }

    // Init audio
    audioController = AEAudioController(audioDescription: AEAudioController.nonInterleavedFloatStereoAudioDescription())

    audioURL = NSBundle.mainBundle().URLForResource("shortSound", withExtension: "wav")!

    do {
        try audioController?.start()
    } catch {
        print("AudioController start Error")
    }

}

override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)

    audioController?.stop()
}

@IBAction func playSound(sender: UIButton) {
    do {
        let player = try AEAudioFilePlayer(URL: audioURL)
        player.removeUponFinish = true
        audioController?.addChannels([player])
    } catch {
        print("Player start Error")
    }
}


text:
Q: How to ensure uniqueness in Labeled index in neo4j How can I ensure the put if absent /create unique functionality while creating nodes using labeled indexes in Core Java API? Earlier I would get an Index from Index Manager and just fire putIfAbsent. But now after I create a label and index it, lets say a User label with userId as indexed property, I cannot get the index like I used to. The method graphDb.index().existsForNodes("User") always returns false.

A: This looks like merge in Cypher which is not exposed in the JAVA API, AFAIK
http://docs.neo4j.org/chunked/snapshot/query-merge.html#merge-merge-single-node-with-properties
If you need one please open an issue on Github
https://github.com/neo4j/neo4j/issues

A: Thanks! I posted the same question on neo4j disqus forum. I am told that uniqueness is supposed to be enforced by the uniqueness constraint. However it is not available in current milestone.


text:
Q: Data visualisation: selectively animate shape but not the text in group of svg
I  am working over the following layout (Use Chrome to see correctly) to represent some data. I want an svg-sphere will be "breathing" but every svg-text connected to mentioned sphere will be not animated.
For now both: spheres and text are "breathing":
<svg height="100px" width="100px">
<defs>
<radialGradient id="grad1" cx="50%" cy="50%"
r="50%" fx="50%" fy="50%">
  <stop offset="0%" style="stop-
 color:rgb(0,0,0);stop-opacity:1"/>
  <stop offset="100%" style="stop-
 color:rgb(255,255,255);stop-opacity:1"/>
 </radialGradient>
 </defs>
 <g>
 <ellipse stroke="rgb(0,{% include
 indexmod.html %},0)" stroke-opacity="{%
 include indexmod.html %}" stroke-width="{%
 include stroke.html %}" cx="50" cy="50"
 rx="10" ry="10" fill="url(#grad1)"/>
 <text x="50%" y="70%" fill="green" text-
 anchor="middle">{% include age.html %}</text>
 <text x="50%" y="80%" fill="black" text-
 anchor="middle">{{page.shortname}}</text>
 </g>
 <animateTransform attributeName="transform"
 type="scale" additive="sum" from="1 1" to="2
 2" begin="0s" dur="5s" rotate="auto-reverse"
 repeatCount="indefinite"></animateTransform>
 <animateTransform attributeName="transform"
 type="scale" additive="sum" from="2 2" to="1
 1" begin="5s" dur="5s"
 repeatCount="indefinite"></animateTransform>
 </svg>


text:
Q: BlueMix service error with Android app - 'Unknown pattern character 'X'' I'm developing an android application and am attempting to integrate the Bluemix service - Personality Insights. However, due to a conflict with dates (Bluemix service is assuming a Java SimpleDateFormat which includes the symbol 'X', while Android's SimpleDateFormat does not include this symbol) causing an error (Log below). My question is this, is there a way to brute force the app to use the Java SimpleDateFormat version as opposed the Android version? other than that I don't see how I can use the service without Bluemix switching to accomodate the 'X' character in dates. Any enlightening on this topic would be appreciated!
Log:
Caused by: java.lang.IllegalArgumentException: Unknown pattern character 'X'
            at java.text.SimpleDateFormat.validatePatternCharacter(SimpleDateFormat.java:314)
            at java.text.SimpleDateFormat.validatePattern(SimpleDateFormat.java:303)
            at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:356)
            at com.google.gson.DefaultDateTypeAdapter.<init>(DefaultDateTypeAdapter.java:49)
            at com.google.gson.GsonBuilder.addTypeAdaptersForDate(GsonBuilder.java:555)
            at com.google.gson.GsonBuilder.create(GsonBuilder.java:543)
            at com.ibm.watson.developer_cloud.util.GsonSingleton.createGson(GsonSingleton.java:53)
            at com.ibm.watson.developer_cloud.util.GsonSingleton.getGson(GsonSingleton.java:38)
            at com.ibm.watson.developer_cloud.concept_expansion.v1.ConceptExpansion.createJob(ConceptExpansion.java:147)
            at intercept.notification.notify.MainActivity$PlaceholderFragment$Persona.doInBackground(MainActivity.java:106)
            at intercept.notification.notify.MainActivity$PlaceholderFragment$Persona.doInBackground(MainActivity.java:84)

I've debugged this quite a bit but don't know how to brute force use of the Java version of SimpleDataFormat as opposed the Android version. Differences between the two can be seen here:
Java (which includes symbol 'X' as required by Bluemix service - http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Android (which doesn't include it) - http://developer.android.com/reference/java/text/SimpleDateFormat.html

A: The problem
We were using 'X' which is not supported by the jdk 1.6 in Android.
That problem was fixed in v1.1.1.
Updating the Dependency

*

*Maven:
<dependency>
    <groupId>com.ibm.watson.developer_cloud</groupId>
    <artifactId>java-wrapper</artifactId>
    <version>1.1.1</version>
</dependency>

*Gradle:
'com.ibm.watson.developer_cloud:java-wrapper:1.1.1'

*Downloading the jar-with-dependencies from github.


text:
Q: Any intuition or insight into why these programs run differently on Windows vs Linux? I have a small program that implements three sorting algorithms and runs a time-analysis (using the C time library and calling clock()) of the execution time for each. The program reads in 9999, 19999, and 29999 integers before sorting the arrays. Upon completion, the median of the newly sorted data is found as a testament to the proper sorting of the data.
The problem was that on my personal Windows 7 machine I could not find the median of data sorted via the quicksort algorithm despite having a properly sorted set. However, when ran on the Linux machine all works fine but the timing runs awry from what is expected.
The quicksort algorithm is nlog(n) average case. So, we would expect the time of execution to increase with larger data sets (which is does on my personal machine). However, when ran on the linux machine I get a 0 execution time for the smallest set of data and equivalent time for the following two.
I could understand the 0 resultant of the calculations associated with the time taken for execution (due to truncation of integer arithmetic), but my personal machine runs much quicker on every other algorithm. The lagging noted for this particular instance has driven me to inquire about the differences.
If you think that the reason behind the discrepancy might be do to the implementation of how I went about reading/sorting then comment as such. However, I am more interested in the differences between how the system time is handled between the two systems and various other things that may be the culprit.

And also, sometimes when the program was run on the linux machine the output execution time would actually be something like 10 0 10, so naturally it has me interested.

A: i'm not sure what you're looking for here apart from the obvious, but...

*

*you have a bug in your windows code, hence the bad median

*on the unix machine the resolution of the timing information is low so you only see multiples of 10.  so any process that lasts between 0 and 10 (whatever the units are) could display either 0 or 10, depending on exactly when it starts and stops.  that's consistent with the times you'd expect by scaling the window's results according to the other runs.


text:
Q: Power-Law PDFs and Expectations A random variable $X$ follows the distribution:
$$f_X(x)=\begin{cases}
  Cx^2 & -1\le x\le 2,\\
  0 & \text{otherwise},
  \end{cases}$$
and $Y=X^2$. Calculate

*

*$C$

*$P(X\ge0)$

*$E[Y]$

*$V(Y)$
I know that I need to utilize the Power-law of PDFs but as soon as this went to integrals and derivatives I am lost and don't understand how these equations simplify.  This is my first time looking at derivatives and without explaining each step of them I'm lost immediately.
Any help would be appreciated.  Does it have to do with the equations below:
$$\int_0^1(a+1)x^adx=x^{a+1}|_0^x=1$$

*

*I am at a loss for how to find the $C$ (I assume this means the $constant$.)
But if we take the $\frac{d}{dx}x^2$ that should be $2x^{2-1}=2x$. So the $C=2$?

*Does this follow the formula: $$P(X\ge a)=P(X\gt a)=1-F(a)$$
If this is the case than:
$$
\begin{aligned}
F(a)&=\int_{-\infty}^af(a)du=0 \\
F(0)&=\int_{0}^{\infty}f(0^2)dx  \\
&=1-0=1
\end{aligned}
$$
So then $P(X\ge0)=1$?

*To find the expected value for x: $$E(X)=\int xf(x)dx$$ correct?

A: In order to find $C$, we need to utilize this fact:

The integral of the probability distribution function (pdf) over its domain is equal to 1.

Therefore, in mathematical notation, we have-
$$\int_{-\infty}^{\infty} f(x)dx = 1. $$
Now, the function $f$ that we are dealing with has non-zero output (function value) only in the interval $[-1,2]$. Therefore, we split up the integral as follows:
$$ \begin{align}1 &= \int_{-\infty}^{\infty} f(x)dx = \int_{-\infty}^{-1} f(x)dx + \int_{-1}^{2} f(x)dx + \int_{2}^{\infty} f(x)dx\\ &=  \int_{-\infty}^{-1} 0\ dx + \int_{-1}^{2} Cx^2 dx + \int_{2}^{\infty} 0 \ dx \\ &=  0+ C\int_{-1}^{2} x^2 dx + 0 \textrm{, as constants are not affected by integrals}\\&= C\frac{x^3}{3}\bigg|^2_{-1} \textrm{, since the power law says:} \int x^n dx = \frac{x^{n+1}}{n+1} \textrm{ for } n \geq 0 \\&= C \left(\frac{2^3}{3} - \frac{(-1)^3}{3}\right) \\ &= C\left( \frac{8}{3} - \frac{-1}{3} \right)\\ &= C\left( \frac{9}{3}\right) = 3C \end{align}$$
Thus, $3C = 1$, and hence, $C = \frac{1}{3}$.
For the second question, you can use this fact-

$ P(a \leq X \leq b) = \int_a^b f(x) dx$, for every random variable $X$ with pdf $f$.

Here, $P(X\geq 0) = P(0 \leq X \leq \infty)$. Therefore, $ P(X\geq 0) = \int_0^{\infty} f(x) dx.$ So then, we have -
$$ \begin{align} P(X\geq 0) &= \int_0^{\infty} f(x) dx\\ &=\int_0^{2} f(x) dx + \int_2^{\infty} f(x) dx \\&= \int_0^{2} \frac{1}{3}x^2 dx + \int_2^{\infty} 0\ dx.\end{align} $$
I hope you can solve it further using the power law as we did in question 1.


text:
Q: Table of Contents (TOC) missing after using CGContextDrawPDFPage i am cocoa programer and using Quartz to draw pdf files, the original pdf has table of contents (TOC), but the result pdf lost TOC  after using following functions.
for(int i = 1; i <= pageCount; i++)
{
   page = CGPDFDocumentGetPage (document, i);
   CGContextDrawPDFPage (myContext, page);
}

Am I doing wrong or how to keep TOC with Quartz? Any help would be appreciated. (english is not my native language, hope you can understand what i am asking...)

A: Your code takes the pages content from the source file and draws them on a new document. This is the only content you can transfer from one document to another. The bookmarks (TOC), form fields, annotations, links in the source file cannot be copied to the new document. It is a limitation of the CoreGraphics API.
So if you need to modify an existing PDF file you're out of luck.


text:
Q: Cakephp enum list with pre-selected drop-down box I have this enum select list pre-selected with values then this is put into Form helper and select function like below:
$enumList = enum('Uusi hakija', 'Jatkohakemus', '40+', '60+','Työyhteisöhanke','Mieshanke','Urheiluseurahanke');
        $vars = explode('.', $enumList);
        echo $this->Form->select('Model.project_type', $vars);

My question is how can you set it so you define "selected" value with session value like below?
$saved = $this->Session->read('form');
echo $this->Form->input('amount_accepted',array('value' => $saved['amount_accepted'] ));

A: do it in the controller and pass it along to the view
if (!empty($this->data)) {
 ...
} else {
 # now comes your part
 $this->data['Model']['amount_accepted'] = $this->Session->read('Model.amount_accepted');
}

PS: why so complicated with the options?
$this->Form->input('amount_accepted', array('options'=>array('Uusi hakija', 'Jatkohakemus', '40+', '60+','Työyhteisöhanke','Mieshanke','Urheiluseurahanke')));


text:
Q: Singularities and their Residues i have the function $$f(z)= \frac{\sin(z)}{(z-1)(\sinh(z))}$$
and i need to find the residue for the singularities.
I have found the two singularities to be $z=1$, and $z=0$
I found the residue for $z=1$ as $\frac{\sin(1)}{\sinh(1)}$
I wanted to clarify if $z=0$ is an actual singularity, and if so how would i find the residue??

A: since
$$
\sin x = x + ... \\
\sinh x = x + ...
$$
the function has a removable 'singularity' and can be treated by defining a function $g(x)$ which is $\frac{\sin(z)}{(z-1)(\sinh(z))}$ if $z \ne 0$, and takes the value $-1$ at $x=0$.
this function has no singularity, and no residue need be computed

A: Your calculations for the singularity at $z=1$ seem correct to me. The singularity at $z=0$ is removable because $\displaystyle\lim_{z\to 0} z f(z)=0.$and therefore has residue $0$.


text:
Q: NHibernate nested class mapping issue I have below classes. How can I write mapping document for MainBranch.Id column. I have no branch table in database, just want to use branchId for MAINBRANCHCODE. Any Idea?
public class Bundle
        {
            public virtual Decimal Id { get; set; }
            public virtual BundleEntranceInformation Information { get; set; }
        }
    public class BundleEntranceInformation
        {
            public virtual Branch MainBranch { get; set; }
        }
    public class Branch
        {
            public virtual short Id { get; set; }
        }

My mapping document:
<class name="PromissoryNotes.Server.Data.Bundle, PromissoryNotes.Server.Data" table="BUNDLE" lazy="true">
    <id name="Id" column="ID" type="Decimal">
      <generator class="increment" />
    </id>
    <property name="Information.MainBranch.Id" column="MAINBRANCHCODE" type="short"></property>

  </class>

A: Use a component mapping
<class name="BundleEntranceInformation">
  <component name="MainBranch">
    <property name="Id" column="MAINBRANCHCODE"/>
  </component>
</class>

A: Here is the answer :)
<component name="Information">
   <component name="MainBranch">
     <property name="Id" column="MAINBRANCHCODE"/>
   </component>
</component  >

A: public class MainClass
{
  public virtual long MainKey {get; set;}
  public virtual SubClass SubInstance {get; set;}

  public class SubClass
  {
    public virtual long SubKey {get;set;}
  }
}

can be mapped as:
<class name="MainClass" table="Main">
  <id name="MainKey" column="MainId" type="Int64">
    <generator class="identity" />
  </id>
  <many-to-one name="SubInstance" class="MainClass+SubClass" Column="SubId"/>
</class>

<class name="MainClass+SubClass" table="Sub">
  <id name="SubKey" column="SubId" type="Int64">
    <generator class="identity" />
  </id>
</class>

So the plus sign is key
(I believe that java-hibernate uses the dollar sign $ for this)


text:
Q: JMS manifest file, does the order in which jars are specifid matter In a manifest of a jar file, does the order in which the jars are listed matter.
Will the former jars be able to access the later jars.  Will the later jars be able to access the former jars
To clarify, I mean two jar files referenced with in the Rsrc-Class-Path: of the manifest
Thanks

A: Yes, it matters, but not in the way you suggest.
The Oracle TechNote Setting the class path says (right at the bottom):

Specification order
The order in which you specify multiple class path entries is
  important. The Java interpreter will look for classes in the
  directories in the order they appear in the class path variable.
   In the example above,

(where they set the classpath to C:\java\MyClasses;C:\java\OtherClasses)

the Java interpreter will first look for a needed class in the directory C:\java\MyClasses. Only if it doesn't find a class with the proper name in that directory will the interpreter look in the C:\java\OtherClasses directory.

A: So to expand on my comment, the answer is still No. The reason being, is because, with the exception of class path hackery (which I have done myself a time or two) Jar and class files are loaded by each ClassLoader before your code runs. The classes are only initialized when meaningful use is made in the application (like you access a static field, or create an instance). The point is, the ClassLoader uses the entries in its classpath to determine where to look when it loads up classes. When you try to use said classes, the ClassLoader already has a list of classes it can provide you with.
See the link I provided in my comment for more info on class loading.


text:
Q: Having xticks to display Months in a Seaborn regplot with Pandas I can not figure how to make the xticks to display Months.
For a reproducible example, my data is:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

json = '{"index":{"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16},"Date":{"0":1516147200000,"1":1516752000000,"2":1517788800000,"3":1520208000000,"4":1520985600000,"5":1522281600000,"6":1522886400000,"7":1523404800000,"8":1523491200000,"9":1524096000000,"10":1525305600000,"11":1525737600000,"12":1526428800000,"13":1527811200000,"14":1533686400000,"15":1534377600000,"16":1534809600000},"FB":{"0":0.978943931,"1":1.0282769543,"2":0.999118052,"3":0.994377665,"4":1.0152684601,"5":0.880773866,"6":0.8782934503,"7":0.91676777,"8":0.9032631287,"9":0.9265792518,"10":0.959210704,"11":0.9862198213,"12":1.0098114818,"13":1.0692867773,"14":1.0207253613,"15":0.962958874,"16":0.9514937543},"month":{"0":1,"1":1,"2":2,"3":3,"4":3,"5":3,"6":4,"7":4,"8":4,"9":4,"10":5,"11":5,"12":5,"13":6,"14":8,"15":8,"16":8}}'

toy_data = pd.read_json(json)

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('Share Price Facebook, Google and the SP500')
sns.regplot( x = 'index', y = 'FB', data = toy_data , label = 'FB', fit_reg = True)

plt.show()

I would like to ammend the code so that in the x axis appear the Months of the Range of Observations. That is the tick labels 0 and 1 would be replaced with 'Jan' (appearing once), the tick label 2 would be replaced with 'Feb', the tick labels 3, 4, 5 with 'March' (appearing once), etc.

A: You can convert your dates to numbers and use those numbers as the x input for the regplot. Then you can format your ticklabels as dates.
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns

json = '{"index":{"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16},"Date":{"0":1516147200000,"1":1516752000000,"2":1517788800000,"3":1520208000000,"4":1520985600000,"5":1522281600000,"6":1522886400000,"7":1523404800000,"8":1523491200000,"9":1524096000000,"10":1525305600000,"11":1525737600000,"12":1526428800000,"13":1527811200000,"14":1533686400000,"15":1534377600000,"16":1534809600000},"FB":{"0":0.978943931,"1":1.0282769543,"2":0.999118052,"3":0.994377665,"4":1.0152684601,"5":0.880773866,"6":0.8782934503,"7":0.91676777,"8":0.9032631287,"9":0.9265792518,"10":0.959210704,"11":0.9862198213,"12":1.0098114818,"13":1.0692867773,"14":1.0207253613,"15":0.962958874,"16":0.9514937543}}'
df = pd.read_json(json)
df["Date2"] = mdates.date2num(pd.to_datetime(df["Date"]))

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('Share Price Facebook, Google and the SP500')
sns.regplot( x = 'Date2', y = 'FB', data = df , label = 'FB', fit_reg = True, ax=ax)

loc = mdates.AutoDateLocator()
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(loc))
plt.show()


text:
Q: The reason why the member variable of the node to be deleted from the doubly linked list should be initialized to null public class Node<E> {
    E data;
    Node<E> left;
    Node<E> right;
}

The code below deletes a node at a specific index from a doubly linked list. At the end of the code, left, right, and data of the node to be deleted must all be initialized to null. Is this a necessary process? What can happen if you don't initialize to null
public void remove(int index) {

    Node foundNode = findNode(index);
    Node leftNode = foundNode.left;
    Node rightNode = foundNode.right;

    leftNode.right = rightNode;
    rightNode.left = leftNode;

    foundNode.left = null;
    foundNode.right = null;
    foundNode.data = null;

    --size;
}

A: To be entirely clear: new Node() would initialize the node fields left and right with null.
That remove sets all fields of the removed foundNode to null is a misguided attempt to optimize garbage collection.
You do not create lingering objects (other removed nodes), no memory leak. As a garbage collector can deal with collections of unreachable objects.
Mind: for other languages this might not hold.

A: In "normal" circumstances the three last assignments with null are not needed. When the function completes, its local variables are deallocated, and so there will usually not be any reference to the node that was referenced by foundNode.
However, it could be that in other code -- not part of this function -- there is still a variable that references that node, and then it is not that bad to indicate that this node is no longer part of a (longer) list. By setting left and right to null, the following invariant is maintained for every node:

*

*Either node.left == null, or

*node.left.right == node
...and similarly:

*

*Either node.right == null, or

*node.right.left == node
If we do not set foundNode.left = null, then the above invariant is not restored, and this could be an issue if there is still a reference to foundNode outside of the function's execution context.
As to foundNode.data = null: that should not really be necessary. If the node referenced by foundNode is not referenced elsewhere, then foundNode can be garbage collected. And if there is also no other reference to its data, then also that data can be garbage collected. Setting this property to null does not really change that process. Secondly, if we consider the case where there still might be a reference to this node, then null might be data that is actually meaningful in the overall algorithm, so setting it to null is not guaranteed to mark it in an unambiguous way as a "deleted" node.


text:
Q: How can I import product image from an external URL in magento 1.9 $simpleProduct = Mage::getModel('catalog/product');
$simpleProduct->setMediaGallery (array('images'=>array (), 'values'=>array ()));

Please help me.

A: Suppose say we have a csv with an extra field: external_image_url for product import.
1> Copy app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php to the local code pool so that new path looks like:
app/code/local/Mage/Catalog/Model/Convert/Adapter/Product.php
2> Open the Product.php from local code pool and search for the following code within saveRow() function:
foreach ($imageData as $file => $fields) {
    try {
        $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . trim($file), $fields);
    }
    catch (Exception $e) {}
}

Add the following code just below it:
/** EXTERNAL IMAGE IMPORT - START **/
$image_url  = $importData['external_image_url']; //get external image url from csv
$image_type = substr(strrchr($image_url,"."),1); //find the image extension
$filename   = md5($image_url . $importData['sku']).'.'.$image_type; //give a new name, you can modify as per your requirement
$filepath   = Mage::getBaseDir('media') . DS . 'import'. DS . $filename; //path for temp storage folder: ./media/import/
file_put_contents($filepath, file_get_contents(trim($image_url))); //store the image from external url to the temp storage folder
$mediaAttribute = array (
        'thumbnail',
        'small_image',
        'image'
);
/**
 * Add image to media gallery
 *
 * @param string        $file              file path of image in file system
 * @param string|array  $mediaAttribute    code of attribute with type 'media_image',
 *                                         leave blank if image should be only in gallery
 * @param boolean       $move              if true, it will move source file
 * @param boolean       $exclude           mark image as disabled in product page view
 */
$product->addImageToMediaGallery($filepath, $mediaAttribute, false, false);
/** EXTERNAL IMAGE IMPORT - END **/

more info here


text:
Q: Record program end time at beginning of XML I'm working on a plugin between Autodesk Revit and another platform which needs a XML file exported out of Revit and this XML needs the start and end time recorded at the beginning of it.
Recording the start time is easy but how can I record the end time at the start of my XML? Brief example below.
// Some blocks of code here...
string startDateTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK");
xmlWriter.WriteAttributeString("StartDateTime", startDateTime);
xmlWriter.WriteAttributeString("EndDateTime", endDateTime);  //this obviously causes an error as the variable either not defined, initiated or doesn't have the information yet.
// Some more blocks of code here...
string endDateTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK");


text:
Q: How do I get public IP address similar to what google returns in NGINX? My NGINX configuration is as follows:
server {
    listen       80;
    server_name  localhost;

    location /test {
        return 200 $remote_addr;
    }
}

When I google my public IP, google returns something like 167.124.xxx.xxx. But nginx's $remote_addr returns something like 192.168.xx.xx. Why is the IP returned by Google different than what NGINX returns?

A: 192.168.xx.xx is your server's IP within your network, and 167.124.xx.xx is your network's public address. This has nothing to do with NGINX specifically. More info here.


text:
Q: How to filter different input combinations when creating a dynamic input in R shiny I am stuck when I try to create a dynamic panel in shiny, using the outputUI/renderUI combination.
I am beginning in R shiny and have been using functions as filters to disjoin different input cases in "if" statements until now.

library(shiny)

 ui<- fluidPage(
    sidebarLayout(sidebarPanel(radioButtons("sim","Type de simulation:",
                                            list("Simulation d'un nombre de mélanges déterminés aux paramètres aléatoires" = "alea",
                                                 "Simulation de deux mélanges aux paramètres choisis" = "escogido")),
                               radioButtons("dist", "Distribution type:",list("Normal" = "norm","Poisson" = "poiss")),
                               uiOutput('InputUser'),
                               sliderInput("N","Nombre d'observations:", value = 100,min = 50, max = 1000),
                               uiOutput('InputUser2'),
                               actionButton("goButton","Allons-y")) ,
    mainPanel(
      uiOutput('Tables')
    )
  ))

  server <- function(input, output, session){
      filtre_A<-function(sim,dist) {return(sim=="alea"&dist=="norm")}
      filtre_B<-function(sim,dist) {return(sim=="alea"&dist=="poiss")}
      filtre_C<-function(sim,dist) {return(sim=="escogido"&dist=="norm")}
      filtre_D<-function(sim,dist) {return(sim=="escogido"&dist=="poiss")}

      filtre_Z<-function(dim) {return(dim==1)}

      filtre_1<-function(sim,dist,dim) {return(sim=="alea"&dist=="norm"&dim>1)}
      filtre_2<-function(sim,dist,dim) {return(sim=="alea"&dist=="norm"&dim==1)}
      filtre_3<-function(sim,dist,dim) {return(sim=="escogido"&dist=="norm")}
      filtre_4<-function(sim,dist,dim) {return(sim=="alea"&dist=="poiss")}
      filtre_5<-function(sim,dist,dim) {return(sim=="escogido"&dist=="poiss")}
      filtre_6<-function(sim,dist,dim) {return(dist=="norm"&dim==2)}
      filtre_7<-function(sim,dist,dim) {return(dist=="norm"&dim==3)}

      output$InputUser<- renderUI({
        if (filtre_A(input$sim,input$dist)) {
          list(numericInput("dim","Dimension du mélange Gaussien",min=1,max=10,value=1),
          numericInput("npar","Nombre de lois mélangées",min=2,max=20,value=2))
        }
        if (filtre_B(input$sim,input$dist)) {
           numericInput("npar","Nombre de lois mélangées",min=2,max=20,value=2)
        }
        if (filtre_C(input$sim,input$dist)) {
          list(sliderInput("pi1","π1",min=0.1,max=1.0,step=0.1,value=0.5),
          sliderInput("mu1","µ1",min=-10,max=10,step=0.1,value=-5),
          sliderInput("sig1","σ1",min=0.1,max=1.0,step=0.01,value=.2),
          sliderInput("mu2","µ2",min=-10,max=10,step=0.1,value=5),
          sliderInput("sig2","σ2",min=0.1,max=1.0,step=0.01,value=.8))
          }
        if (filtre_D(input$sim,input$dist)) {
         list(sliderInput("pi1","π1",min=0.1,max=1.0,step=0.1,value=.5),
         sliderInput("lambda1","λ1",min=0.1,max=10,step=0.1,value=1),
         sliderInput("lambda2","λ2",min=0.1,max=10,step=0.1,value=9))
        }
      })

      output$InputUser2 <-renderUI({
        if (filtre_Z(input$dim)) {
           list(radioButtons("EM", "Implémentation de l'algorithme EM ?",list("Oui" = "Y","Non" = "N")),
          conditionalPanel(condition = "input.EM=='Y' & input.dim==1",sliderInput("nmax2","Nombre d'itérations maximum algorithme EM",value=100,min=1000,max=100000)))
        }
      })

      output$Tables <- renderUI({

        if ((filtre_2(input$sim,input$dist,input$dim)|
             filtre_3(input$sim,input$dist,input$dim)|
             filtre_4(input$sim,input$dist,input$dim)|
             filtre_5(input$sim,input$dist,input$dim))&(
               filtre_8(input$EM,input$dist,input$dim)|
               filtre_9(input$EM,input$dist,input$dim))) {
          fun<-function(l) {do.call(tabPanel,l)}
          myTabs1<-list(list("Figure", plotOutput("figure")),
                        list("Groupement",plotOutput("clusters")),
                        list("Paramètres empiriques",plotOutput("esti")),
                        list("Données",plotOutput("donnes")),
                        list("Paramètres des lois",plotOutput("parameter")))
          myTabs2<-lapply(myTabs1,fun)
          do.call(tabsetPanel,myTabs2)
        }

        if ((filtre_2(input$sim,input$dist,input$dim)|
             filtre_3(input$sim,input$dist,input$dim)|
             filtre_4(input$sim,input$dist,input$dim)|
             filtre_5(input$sim,input$dist,input$dim))&(!(
               filtre_8(input$EM,input$dist,input$dim)|
               filtre_9(input$EM,input$dist,input$dim)))) {
          fun<-function(l) {do.call(tabPanel,l)}
          myTabs1<-list(list("Figure", plotOutput("figure")),
                        list("Groupement",plotOutput("clusters")),
                        list("Données",plotOutput("donnes")),
                        list("Paramètres des lois",plotOutput("parameter")))
          myTabs2<-lapply(myTabs1,fun)
          do.call(tabsetPanel,myTabs2)
        }

        if (filtre_6(input$sim,input$dist,input$dim)) {
          fun<-function(l) {do.call(tabPanel,l)}
          myTabs1<-list(list("Groupement",plotOutput("clusters")),
                        list("Données",plotOutput("donnes")),
                        list("Paramètres des lois",plotOutput("parameter")))
          myTabs2<-lapply(myTabs1,fun)
          do.call(tabsetPanel,myTabs2)

        }
        if (filtre_7(input$sim,input$dist,input$dim)) {
          fun<-function(l) {do.call(tabPanel,l)}
          myTabs1<-list(list("Figure", plotOutput("figure")),

                        list("Données",plotOutput("donnes")),
                        list("Paramètres des lois",plotOutput("parameter")))
          myTabs2<-lapply(myTabs1,fun)
          do.call(tabsetPanel,myTabs2)

        }
        if (filtre_1(input$sim,input$dist,input$dim)&(!(filtre_7(input$sim,input$dist,input$dim)|filtre_6(input$sim,input$dist,input$dim)))) {
          fun<-function(l) {do.call(tabPanel,l)}
          myTabs1<-list( list("Données",plotOutput("donnes")),
                         list("Paramètres des lois",plotOutput("parameter")))
          myTabs2<-lapply(myTabs1,fun)
          do.call(tabsetPanel,myTabs2)
        }
      })
  }

  shinyApp(ui = ui, server = server)

It seemed to work as long as I used  renderPlot/outputPlot renderDataTable etc. but with outputUI/renderUI it appears that only the last if statement got compiled.
Should somebody explained me a way much efficient to organize my code and do what I want, I would be very thankful.