Find the sum of series

Question: Does there exist an explicit formula for the sum of the series
$$
\sum_{n=1}^\infty \frac{1}{n^2-z^2}?
$$
Comment: Yes (the question is often asked here). See for example [this](http://math.stackexchange.com/questions/110494/possibility-to-simplify-sum-limits-k-infty-infty-frac-left/110495#110495).
Comment: That's very nice, many thanks! (The answer is accepted, so I hope it contains a correct proof.)
Comment: Thanks, of course Eric's answer is correct?  Another [link](http://math.stackexchange.com/questions/3525/a-series-expansion-of-cot-pi-z) with links...
Answer: Equation $(18)$ on this page states that $$\pi \cot(\pi z)=\frac{1}{z}+2z\sum_{n=1}^\infty \frac{1}{z^2-n^2}.$$
Answer: This answer handles precisely this question by showing that the Cauchy Principal Value of
$$
\sum_{k\in\mathbb{Z}}\frac1{k+z}=\pi\cot(\pi z)
$$
and derives an explicit value for $\displaystyle\sum_{k=1}^\infty\frac{1}{k^2-z^2}$ in $(9)$.
Answer: Yes, there does.  Of course the sum is not defined if $z$ is a nonzero integer.

Find the sum of series


Não consigo resolver um exercício de javascript

Question: Estou fazendo um exercício e não consigo resolve-lo:
As instruções são:
Escreva a função eNumeroDaSorte que, recebendo um número, diz se é um número da sorte. Lembre-se de que o número deve obedecer às três condições mencionadas. Seu desafio adicional será: NÃO use o if.
Podemos dizer que é um número da sorte se o número:
é positivo
é um múltiplo de 2 ou 3
não é 15
A minha resposta foi:

function eNumeroDaSorte (numero) {

  return numero > 0 && 15%3==0 || 10%2==0 && numero != 15;

}

Mas o site da errado com os seguintes problemas:
eNumeroDaSorte é falso e multiplo de 2 ou de 3
eNumeroDaSorte(7) é falso
eNumeroDaSorte(15) é falso
Agradeço por qualquer ajuda!
Comment: Bom dia, embora você tenha dado informação suficiente pra darmos uma resposta, ao menos coloque um título na sua pergunta que se relacione ao seu problema. E sim, pensar em QUAL é o título da sua pergunta vai te tornar um melhor programador pois te levará ao processo de análise.
Comment: Ok, agradeço o comentário e vou tentar melhorar nas próximas.
Answer: Bom, alterei um pouco o código mas creio que eNumeroDaSorte(15) deve ser falso, de acordo com o que você descreveu, pois ele não é 15, mesmo sendo múltiplo de 3, e eNumeroDaSorte(7) também é falso pois não é múltiplo de 2 ou 3.

function eNumeroDaSorte (numero) {
  return (numero >= 0) && ((numero % 3 === 0) || (numero % 2 === 0)) && (numero !== 15);
}

// é positivo
// é um múltiplo de 2 ou 3
// não é 15

console.log(eNumeroDaSorte(15))

Espero ter ajudado.
Comment: Oi, ajudou sim, muito obrigado. Acho que o prolema estava na parte da %, que eu tinha posto um 15%3 e 10%2. Agradeço pela ajuda!
Answer: Minha resposta é:
function eNumeroDaSorte (numero) {
  return (numero > 0) && ((numero % 3 == 0) || (numero % 2 == 0)) && (numero !== 15);
}

numero não pode ser >= 0 pois 0 não é múltiplo de 2 e 3
Espero ter ajudado.
Answer: function eNumeroDaSorte (numero){
    return(numero > 0) && ((numero % 4 === 0) || (numero % 2 === 0))  &&  (numero  !== 15);
}
console.log(eNumeroDaSorte(15))
//Eu fiz assim e deu certo!espero ter ajudado!


How to use adapter.notifyDataSetChanged(); where i have to use these line for my error

Question: ItemListBaseAdapter.java
public class ItemListBaseAdapter extends BaseAdapter {
private static ArrayList<Recipedetails> itemDetailsrrayList;

private Integer[] imgid = {
        R.drawable.vegeterian,
        R.drawable.nonveg,
        R.drawable.pickels,
        R.drawable.soup,
        R.drawable.sweets,
        R.drawable.cakes,
        R.drawable.icecreams,
        R.drawable.chinesevegdishes,
        R.drawable.chinesenonveg,
        R.drawable.chinesenoodles,
        R.drawable.chinesesoup,
        R.drawable.godhumaivegadai,
        R.drawable.soyamorekoozh,
        R.drawable.tomatokulambu,
        R.drawable.tomatoupma,
        R.drawable.vadanavratrispecial,
        R.drawable.eggkurma,
        R.drawable.milagu,
        R.drawable.rasam,
        R.drawable.vegetablekootu,
        R.drawable.avial,
        R.drawable.kothavarangaicurry,
        R.drawable.allepeyfishcurry,
        R.drawable.spicymadraschicken,
        R.drawable.prawns,
        R.drawable.keralachickenstew,
        R.drawable.nilgirichickenkorma,
        R.drawable.pepperchickencurry,
        R.drawable.chettiandchicken,
        R.drawable.prawnmasala,
        R.drawable.beeffry,
        R.drawable.crispyfish,
        R.drawable.amlapickle,
        R.drawable.avakaipickle,
        R.drawable.capsicumpickle,
        R.drawable.lemonpickle,
        R.drawable.onionpickle,
        R.drawable.mangopickle,
        R.drawable.tendermangopickle,
        R.drawable.tomatopickle,
        R.drawable.chillipickles,
        R.drawable.gingerpickle,
        R.drawable.garlicsoup,
        R.drawable.mixedvegsoup,
        R.drawable.chickenmanchowsoup,
        R.drawable.cleartomatosoup,
        R.drawable.sweetcornvegetablesoup,
        R.drawable.prawnandnoodlesoup,
        R.drawable.beetrootsoup,
        R.drawable.capsicumsoup,
        R.drawable.muttonsoup,
        R.drawable.spinachsoup,
        R.drawable.vegcurry,
        R.drawable.mushroommutter,
        R.drawable.alooparatha,
        R.drawable.daltadka,
        R.drawable.aloomethi,
        R.drawable.rajma,
        R.drawable.paneerbhujri,
        R.drawable.alooghobi,
        R.drawable.aloosabzi,
        R.drawable.kadhaipaneer,
        R.drawable.chickenwithbellpeppers,
        R.drawable.butterchicken,
        R.drawable.fishkorma,
        R.drawable.prawnfry,
        R.drawable.tandoorichicken,
        R.drawable.maccherjholfish,
        R.drawable.shamikabab,
        R.drawable.saagmeat,
        R.drawable.sindhichickenbiryani,
        R.drawable.punjabichickencurry,
        R.drawable.gulabjamun,
        R.drawable.basundi,
        R.drawable.peda,
        R.drawable.badhamhalwa,
        R.drawable.coconutburfi,
        R.drawable.kulfi,
        R.drawable.ladoo,
        R.drawable.mysorepak,
        R.drawable.ricekheer,
        R.drawable.badam,
        R.drawable.cauliflowersoup,
        R.drawable.cucumbersoup,
        R.drawable.tomatosoup,
        R.drawable.mulligatawnysoup,
        R.drawable.greenpeassoup,
        R.drawable.northindianmuttonsoup,
        R.drawable.chickennoodlesoup,
        R.drawable.spicybeansoup,
        R.drawable.eggdropsoup,
        R.drawable.springvegsoup,
        R.drawable.mushroomandseitan,
        R.drawable.tofuwith3spices,
        R.drawable.creamyvegpie,
        R.drawable.grilledvegmedley,
        R.drawable.bakedsquash,
        R.drawable.africanchickenstew,
        R.drawable.westafricanchicken,
        R.drawable.africanyamsoup,
        R.drawable.chickenchilliroast,
        R.drawable.chilliblackbeans,
        R.drawable.williecake,
        R.drawable.pumpkingingercupcakes,
        R.drawable.doublelayerpumpkincheesecake,
        R.drawable.carrotcake,
        R.drawable.sexcake,
        R.drawable.chocolatechipicecream,
        R.drawable.cookieicecream,
        R.drawable.cinnamonicecream,
        R.drawable.appleicecream,
        R.drawable.walnut,
        R.drawable.chineseaubergins,
        R.drawable.spicycucumber,
        R.drawable.chinesemushrooms,
        R.drawable.chinesegobi,
        R.drawable.spicytofu,
        R.drawable.chinesetilchicken,
        R.drawable.chickenmoongali,
        R.drawable.sweetsourchicken,
        R.drawable.cherrychicken,
        R.drawable.mymasalachicken,
        R.drawable.coldseasamenoodles,
        R.drawable.sobanoodles,
        R.drawable.noodleswithtofu,
        R.drawable.chinesevegandbeef,
        R.drawable.noodleswithpepper,
        R.drawable.jhingasoup,
        R.drawable.masalachickensoup,
        R.drawable.cabbagesoup,
        R.drawable.chinesepumpkinsoup,
        R.drawable.baconsoup,

        };

private LayoutInflater l_Inflater;

public ItemListBaseAdapter(Context context, ArrayList<Recipedetails> results) {
    itemDetailsrrayList = results;
    l_Inflater = LayoutInflater.from(context);
}

public int getCount() {
    return itemDetailsrrayList.size();
}

public Object getItem(int position) {
    return itemDetailsrrayList.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = l_Inflater.inflate(R.layout.item_details_view, null);
        holder = new ViewHolder();
        holder.txt_itemName = (TextView) convertView.findViewById(R.id.name);
        holder.txt_itemDescription = (TextView) convertView.findViewById(R.id.itemDescription);
        holder.itemImage = (ImageView) convertView.findViewById(R.id.photo);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.txt_itemName.setText(itemDetailsrrayList.get(position).getName());
    holder.txt_itemDescription.setText(itemDetailsrrayList.get(position).getItemDescription());
    holder.itemImage.setImageResource(imgid[itemDetailsrrayList.get(position).getImageNumber() - 1]);
    return convertView;
}
public synchronized   void refreshAdapter(ArrayList<Recipedetails> items) {
    itemDetailsrrayList.clear();
    itemDetailsrrayList.addAll(items);
    notifyDataSetChanged();
}

static class ViewHolder {
    TextView txt_itemName;
    TextView txt_itemDescription;
    ImageView itemImage;
}

}

Recipedetails.java
public class Recipedetails {

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getItemDescription() {
    return itemDescription;
}
public void setItemDescription(String itemDescription) {
    this.itemDescription = itemDescription;
}

public int getImageNumber() {
    return imageNumber;
}
public void setImageNumber(int imageNumber) {
    this.imageNumber = imageNumber;
}

private String name ;
private String itemDescription;
private int imageNumber;
}

Listview.java
public class SouthIndian  extends Activity {
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final ArrayList<Recipedetails> image_details = GetSearchResults();

        final ListView lv1 = (ListView) findViewById(R.id.listV_main);
        lv1.setAdapter(new ItemListBaseAdapter(this, image_details));

        lv1.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                Object o = lv1.getItemAtPosition(position);
                Recipedetails obj_itemDetails = (Recipedetails)o;
                Toast.makeText(SouthIndian.this, "You have chosen : " + " " + obj_itemDetails.getName(), Toast.LENGTH_LONG).show();

                 //final ArrayList<Recipedetails> act = GetSearchResults();
                //if (act != null)

                switch(obj_itemDetails.getImageNumber())
                {
                    case 1:
                         Intent newActivity = new Intent(SouthIndian.this,
                                 AndroidTabLayoutActivity.class);
                         startActivity(newActivity);
                        break;

                    case 2:
                        Intent new1Activity = new Intent(SouthIndian.this,
                                AndroidTabLayoutActivity1.class);
                        startActivity(new1Activity);
                        break;

                    case 3:
                        Intent new2Activity = new Intent(SouthIndian.this,
                                AndroidTabLayoutActivity2.class);
                        startActivity(new2Activity);
                        break;

                    case 4:
                        Intent new3Activity = new Intent(SouthIndian.this,
                                AndroidTabLayoutActivity3.class);
                        startActivity(new3Activity);
                        break;

                   default:
                       Toast.makeText(SouthIndian.this, "Wrong Input", Toast.LENGTH_LONG).show();
                }

            }
        });
        runOnUiThread(new Runnable() {
                public void run() {

                    ItemListBaseAdapter.refreshAdapter(item);
                    //ItemListBaseAdapter.notifyDataSetChanged();
                }
            });

    }

    private ArrayList<Recipedetails> GetSearchResults(){
        ArrayList<Recipedetails> results = new ArrayList<Recipedetails>();

        Recipedetails item_details = new Recipedetails();
        item_details.setName("Vegterian");
        item_details.setItemDescription("Recipes made by raw materials");
        item_details.setImageNumber(1);
        results.add(item_details);

        item_details = new Recipedetails();
        item_details.setName("Non-Vegterian");
        item_details.setItemDescription("Flesh of sweet animals");
        item_details.setImageNumber(2);
        results.add(item_details);

        item_details = new Recipedetails();
        item_details.setName("Pickels");
        item_details.setItemDescription("Touchable dish  by Homemade");
        item_details.setImageNumber(3);
        results.add(item_details);

        item_details = new Recipedetails();
        item_details.setName("Soups");
        item_details.setItemDescription("Startup for our food");
        item_details.setImageNumber(4);
        results.add(item_details);

        return results;
    }
}

and my log cat error is
03-19 05:04:35.103: E/AndroidRuntime(1110): FATAL EXCEPTION: main
03-19 05:04:35.103: E/AndroidRuntime(1110): java.lang.IllegalStateException: The content of the adapter has changed
but ListView did not receive a notification. Make sure the content of your adapter is not modified from a
background thread, but only from the UI thread. [in ListView(2131165193, class android.widget.ListView)
with Adapter(class com.example.recipestutors.ItemListBaseAdapter)]

03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.widget.ListView.layoutChildren(ListView.java:1544)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.widget.AbsListView.onTouchEvent(AbsListView.java:3403)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.View.dispatchTouchEvent(View.java:7239)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2168)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1903)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1953)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1405)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.app.Activity.dispatchTouchEvent(Activity.java:2410)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1901)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.View.dispatchPointerEvent(View.java:7419)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3220)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3165)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:4292)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:4271)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:4363)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:179)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.os.MessageQueue.nativePollOnce(Native Method)
03-19 05:04:35.103: E/AndroidRuntime(1110):     at android.os.MessageQueue.next(MessageQueue.java:125)

In my code, how and where to use adapter.notifyDataSetChanged()
clicking the second item in the listview,application has stopped and showing error like this as i mention in logcat
Answer: Add this method to your adapter
public synchronized void refresAdapter(ArrayList<Recipedetails> items) {
    itemDetailsrrayList.clear();
    itemDetailsrrayList.addAll(items);
    notifyDataSetChanged();
}

and then make this call from where you want to refresh your adapter
final Activity act = getActivity(); //only neccessary if you use fragments
if (act != null)
    act.runOnUiThread(new Runnable() {
        public void run() {
            yourAdapter.refreshAdapter(item);
        }
    });

this should solve your problem
Comment: ,i am having lots of list view,i have to add in all list view.?
Comment: http://pastebin.com/HmWkA2f2 can you look at my code in this link,and tell me where i want to add the second code you mention above
Comment: sorry here not coming this issue,in southindia.java only if i click the first item in an listview it will works again if i return and i click the anotheritem in that listview,activity has satopped.  http://pastebin.com/CxTZHjED  see this code
Comment: where i have to use the second code as i mention before http://pastebin.com/CxTZHjED
Comment: You will have to give your adapter global scope for your activities and then where you want the data of the adapter to update call youradapter.refresh(with your new list as parameter); as I showed above
Comment: ,i cant understand correctly,can you edit my code and tell me,how do that one,i am new to android
Comment: the problem showing in listadapter and soutindian.java http://pastebin.com/CxTZHjED,can you look at my code and tell me
Comment: Here is a new version that I changed. I did not test it just have a look at what I did and use that as reference http://pastebin.com/u7dny5Dn please try out the rest yourself
Comment: ,you gave two code in an above,first code i put in my Itemlistadapter,i want where to put the second code in southindia.java,final Activity act = getActivity(); these code
Comment: I see I did not add my second part of the code, the runOnUiThread method. Try adding that.
Comment: I can't do your code for you! Here on this line in the change I made, refreshYourAdapter(getSearchResults()); add the runOnUiThread around it.
Comment: both should be come only in soutindian.java or first part  comes in Itemlistbaseadapter?
Comment: The first part comes in your adapter and the second part in your activity. Look at the variables defined in the code I posted in the answer.
Comment: act.runOnUiThread(new Runnable()  it showing error in this line and the last line of item error showing is The method runOnUiThread(new Runnable(){}) is undefined for the type
  ArrayList
Comment: please update your code in the question so that we can see what you did
Comment: i update my code,can you see above of my question,i also added what you put your answer code
Comment: its showing error in ItemListBaseAdapter.refreshAdapter(item); item has problem
Comment: The error tells you what the problem is... Are you using this runOnUiThread?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/26450/discussion-between-neil-and-kkarthickk)
Comment: ,can you see that,whats the problem behind that one
Answer: Don't have itemDetailsrrayList as static.
Comment: I dont get it fully from you,can you tell,what i want to do
Comment: Currently every time you create a new Adapter you're replacing the content of every instance. Remove the static keyword to stop the instances from sharing one list.
Comment: http://pastebin.com/CxTZHjED this java file and listadapter showing problem,how to do


Recursion in PHP

Question: I have a function like this:
function test($T0){
  $T01 = $T0-$T0/2;
  $T02 = $T0+$T0/2;
  if($T01<$T0){
    test($T01);
  } else if($T02<$T0){
    test($T02);
  } else {}
  $result = array($T01,$T02);
    return $result;
  }

  $T0 = 50;
  $result = test($T0);
  echo $result[0];

Why this function is not recursion?
Comment: Your function is recursive.  What are you getting and what are you expecting that makes you think that it is not?
Comment: This line else {} won't help much. It should be else {
Comment: Duplicate of https://stackoverflow.com/q/31624313/9473764
Answer:
To understand recursion you must understand recursion

You forget to return values in your ifs.
Proper code:
<?php
 function test($T0){
   $T01 = $T0-$T0/2;
   $T02 = $T0+$T0/2;
   if($T01 < $T0) return test($T01);
   else if($T02 < $T0) return test($T02);
   else return array($T01,$T02);
 }

 $T0 = 50;
 $result = test($T0);
 echo $result[0];
 ?>

Comment: You're welcome. Always remember to check every condition that may appear. Don't do else {} cause it can make infinite loop.
Answer: You are missing the return on your recursive calls:
return test($T01);

and
return test($T02);

In addition, you seem to have strange placement of braces on your else clause.  Most likely it should be:
else {
    $result = array($T01,$T02);
    return $result;
}

Finally, it's worth noting that this function will (theoretically) cause your code to recurse indefinitely, as you're just dividing a positive number in 2 all the time until it reaches 0.  In theory this never happens.  In practice, you'll recurse to some very-very small number at which the difference with 0 will be below the floating point precision.  In my test this number was 4.9406564584125E-324 (i.e. about 0.0....0494 with ... being 322 zeros).
Answer: You are not writing return at the end of your function call, so it is going into an infinite loop
Answer: As I debug the code:

In your first condition the $T01 will become the zero each time. And
  then it will reach in first condition and call to again to function
  and you are passing the zero value that time. So the value of $T01 and
  $T02 becomes zero in second time and it will go in else condition. So
  This function will not recursion no more again.
Answer: Your code is recursive only but the value of t01 is always less than t02, so its going into an infinite loop

Recursion in PHP


Selecting row from a Pandas DataFrame based on constraints

Question: I have several datasets that I import as csv files and display them in a DataFrame in Pandas. The csv files are info about Covid updates.
The datasets has several columns relating to this, for example "country_region", "last_update" & "confirmed".
Let's say I wanted to look up the confirmed cases of Covid for Germany.
I'm trying to write a function that will return a slice of the DataFrame that corresponds to those constraints to be able to display the match I'm looking for.
I need to do this in some generic way so I can provide any value from any column.
I wish I had some code to include but I'm stuck on how to even proceed.
Everything I find online only specifies for looking up values relating to a pre-defined value.
Comment: Could you include a couple of rows of sample data?
Comment: Also, are the filter conditions from user input or dynamically generated from your code?
Comment: https://stackoverflow.com/help/minimal-reproducible-example
Answer: Something like this?
<code>def filter(county_region_val, last_update_val, confirmed_val, df):
    df = df.loc[((df['county_region'] == county_region_val) & (df['last_update'] == last_update_val) & (df[''confirmed'] == confirmed_val)).reset_index(drop=True)
    return df
</code>


Fazer com que o PHP leia as pastas do servidor

Question: Colegas.
Peguei agora um projeto aqui no trabalho, onde lá nos primórdios esse projeto foi desenvolvido. Funciona da seguinte forma:
Foi criado na página index.php algumas pastas com jpg, onde direciona para os respectivos links. Porém os arquivos (PDF) são enviados enviados via FTP, onde o setor aqui do trabalho cria pastas e subpastas e coloca esses arquivos PDF.
A pessoa que fez esse "projeto" alterava apenas o link da imagem jpg na página inicial. Pensei em refazer esse projeto, só que já existe dezenas de pastas e subpastas com esses arquivos pdf.
Quando clicamos no link das pastas, aparece a página index/of e o nome do arquivo:

O que pensei em fazer, criar um arquivo em html ou PHP, personalizar e ver se com o PHP, JQuery, Ajax, não sei ao certo, lia nos nomes das pastas/subpastas do servidor e criar algo mais personalizado com imagem ao lado do nome do arquivo ou algo nesse sentido.
Comment: "*são enviados **viados** via FTP*" - kkkkkkk
Comment: Filipe, exatamente isso. A pessoa abre o FTP, cria as pastas e joga o PDF dentro. Em muitos casos, cria-se também subpastas.
Comment: @Fox.11 é isso http://pt.stackoverflow.com/q/108662/3635?
Comment: O que você já tentou fazer? Qual a sua dúvida?
Comment: Penso que ele quer listar todos os PDF's que estão nas respectivas pastas dinâmicamente, sem ter que adicionar o link manualmente no ficheiro `index`. Pelo que percebi, haverá um problema, as imagens na lista atual é associada manualmente ao PDF (não está dentro da mesma que o respectivo PDF), ou está? Só ele pode responder.
Comment: Olá Guilherme. O arquivo PHP estará dentro do servidor, mas fora das pastas e subpastas, na pasta raiz.
Answer: Desta forma?
Nesse caso ele seleciona a pasta e retorna as sub-pastas existentes nela.
Se for, estude um pouco sobre. DirectoryIterator
<?php
    // atribuição a variável $dir
    $dir = new DirectoryIterator( './pasta/' );

    // atribui o valor de $dir para $file em loop
    foreach($dir as $file ) {
        // verifica se o valor de $file é diferente de '.' ou '..'
        // e é um diretório (isDir)
        if (!$file->isDot() && $file->isDir()) {
            // atribuição a variável $dname
            $dname = $file->getFilename();

            // imprime o nome do diretório
            echo $dname."
";
        }
    }
?>

Comment: Sério, seria muito bom para a comunidade e interessante para todos se pudessem realmente marcar a pergunta como dup, ao invés de ficarem gerando respostas repetitivas de algo que já foi perguntando dezenas de vezes, isso traria um enorme beneficio para toda comunidade: http://pt.stackoverflow.com/search?q=%5Bphp%5D+Listar+arquivos
Comment: +1 Não conhecia essa daí não. Valeu, @PedroQuezado!!!
Answer: Eu testei esse código daqui e serviu perfeitamente.
<?php

function listFolderFiles($dir)
{
    $ffs = scandir($dir);
    echo '
';
    foreach ($ffs as $ff) {
        if ($ff != '.' && $ff != '..') {
            echo '
'.$ff;
            if (is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
            echo '
';
        }
    }
    echo '
';
}
listFolderFiles('/websites/');

Comment: Sério, seria muito bom para a comunidade e interessante para todos se pudessem realmente marcar a pergunta como dup, ao invés de ficarem gerando respostas repetitivas de algo que já foi perguntando dezenas de vezes, isso traria um enorme beneficio para toda comunidade: http://pt.stackoverflow.com/search?q=%5Bphp%5D+Listar+arquivos
Comment: *Let's do this*


If $A$ is unitarily equivalent to a shift $B$, is it then true, that $A^n x \perp A^m x \Rightarrow B^n x \perp B^m x$?

Question: I don't think so, as we have:
$$A U = U B$$
$$A = U B U^{-1}$$
$$A^n x \perp A^m x$$
$$U^n B^n U^{-n} x \perp U^m B^m U^{-m} x$$
$$U^{n-m} B^n x \perp B^m U^{n-m} x$$
So it's only true if $n = m$ here.

Basically what I'm trying to achieve is to show, that every isometric $A$ in $\mathcal{H}$ is unitarily equivalent to a shift $B$ $\Leftrightarrow$ as to the existence of such a subspace $H$ for which $$x \in H \quad A^n x \perp A^m x$$ $$\mathcal{H} = H \oplus AH \oplus A^2 H \oplus \ldots$$
Comment: Does this answer your question? [Show an isometry is unitarily equivalent to a shift (Wold decomposition).](https://math.stackexchange.com/questions/4048131/show-an-isometry-is-unitarily-equivalent-to-a-shift-wold-decomposition) (I mean: does it help you to answer the end of your post? The answer to your initial question being obviously "no")
Comment: @AnneBauval No, because it's still not clear for me. I would understand, why $B^n x \perp B^m x$ as $B$ is the shift. Then it's clear that it's $\perp$ and the second condition too (if we take $\mathcal{H} = \ell^2_H (\mathbb{Z}_+)$, where $H$ is a Hilbert space). What's not clear is why $A^n x \perp A^m x$, as $A$ is just an isometric operator and not a shift?
Comment: The line $U^{n-m} B^n x \perp B^m U^{n-m} x$ of your post cannot be derived from the previous one $U^n B^n U^{-n} x \perp U^m B^m U^{-m} x,$ which implies $U^{n-m} B^n y \perp B^m U^{n-m}y$ for $y=U^{-n}x,$ not $y=x.$
Answer: What is true (if $m\ne n$ and $AU=UB$ for some unitary $U$) is not $A^nx\perp A^mx\implies B^nx\perp B^mx$ but:
$$A^nK\perp A^mK\iff B^nH\perp B^mH,$$
if $K=UH.$
Proof:

$\Leftarrow:$ if $B^nH\perp B^mH$ then, forall $y=Ux,y'=Ux'\in K,$
$$\begin{align}\langle A^ny,A^my'\rangle&=\langle UB^nx,UB^mx'\rangle\\&=\langle B^nx,B^mx'\rangle\\&=0
\end{align}$$
$\Rightarrow:$ same proof, exchanging $A$ with $B,$ $H$ with $K,$ and $U$ with $U^{-1}.$
Comment: Thanks. What about this one: $$\mathcal{K} = K \oplus A K \oplus A^2 K \oplus \ldots \Leftrightarrow \mathcal{H} = H \oplus BH \oplus B^2 H \oplus \ldots$$ where $\mathcal{K}$ is the space $A$ is from, and $\mathcal{H}$ is the space $B$ is from
Comment: Excuse me, I don't understand. Are you asking a new question? I so, can you formulate it with more detail in a new post?
Answer: The answer to the question is the title is "no". Take $H$ a separable Hilbert space with a fixed orthonormal basis $\{e_n\}$. Let $A$ be the unilateral shift, and $B$ the unilateral shift for an orthonormal basis that begins with $(e_1+e_2)/\sqrt2$, $(e_1-e_2)/\sqrt2,e_3$. Put $x=e_1$. Then $A$ and $B$ are unitarily equivalent, and
$$
A^0e_1=e_1\perp e_2=Ae_2,
$$
while
$$
B^0e_1=e_1\not\perp Be_1
$$
since
$$
Be_1=\frac1{\sqrt2}\,B\big[\frac{(e_1+e_2)}{\sqrt2}+\frac{(e_1-e_2)}{\sqrt2}\big]
=\frac1{2}\,({e_1-e_2}+e_3).
$$
In general it is not true that any isometry is unitarily equivalent to a shift, because that fails obviously for the identity operator. What is true is the Wold Decomposition, which says that any isometry is a direct sum of a unitary plus a direct sum of unilateral shifts.
Comment: "In general it is not true that any isometry is unitarily equivalent to a shift, because that fails obviously for the identity operator. What is true is the Wold Decomposition, which says that any isometry is a direct sum of a unitary plus a direct sum of unilateral shifts." But that's what I'm telling right now, that it's true, if there is such a space $H$ for which $B^m H \perp B^n H$. I just don't get why it is like that
Comment: I don't really understand what you want. But, since $B$ is an isometry, $B^mH\perp B^nH$ is the same as $B^{m-n}H\perp H$ if $n<m$. If $B$ is the shift for the orthonormal basis $\{e_n\}$, take
$$
H=\overline{\operatorname{span}}\{e_{mk}:\ k\in\mathbb N\}.
$$
Then $B^{m-n}e_{mk}=e_{mk+m-n}\not\in H$, so $B^{m-n}H\perp H$.
Comment: Ok, that makes sense, but why is it true, that $A^m H \perp A^n H$? That's what I don't get
Comment: If $A=UBU^*$, then $$\langle A^mx,A^nx\rangle=\langle UB^mU^*x,UB^nU^*x \rangle=\langle B^mU^*x,B^nU^*x\rangle=0.$$
Comment: But why do you take $U B^m U^*$, and not $U^m B^m U^{-m}$?
Comment: And why does the second last equality hold i.e. $\langle U B^m U^* x, ... \rangle = \langle B^m U^* x, ... \rangle$?
Comment: First, $$(UBU^*)^m=UB^mU^*.$$ Second, because $U$ is a unitary (in particular, it is an isometry).


method for calculating portfolio volatility

Question: I am trying to figure out the method for calculating the portfolio volatility using matrices.  I have read online the following definition for calculating the portfolio volatility using matrix algebra
The variance of a portfolio of correlated assets can be written as WTvW, where W is a column vector (ie a matrix with a single column) containing the weights of different assets in the portfolio.  V is the covariance matrix, and WT is the transpose of the matrix W.
I have tried to calculate this on a spreadsheet, but am not sure if i have done it correctly.  More specifically, im not sure if i am multiplying the vectors with the covariance matrix correctly.
Can someone please confirm my calculation
I have used commas below to separate the different values in the vector and matrix
assuming my weights vector is 0.89, 0.11
my covariance matrix is a 2x2 matrix = 1       ,    0.674571
                                       0.674571,    1
to calculate the result i first multiply my weights vector with the covariance matrix
i.e      0.89*1 + 0.11*0.674571
and      0.89*0.674571 + 0.11*1
which gives the following vector A    0.964202851
                                      0.710368523
I then multiply vector A with the weights vector, i.e
0.964202851    *   0.89
0.710368523        0.11     = 0.964202851*0.89+0.710368523 *0.11  = 0.936281075
Is this correct, or do i have an error in my calculation
Answer: Your calculation is correct. By the way, there are free software packages available that make it easier to do these kinds of calculations. For example, using Octave, you simply type
V=[1, .674571; .674571, 1]
W=[.89;.11]
W'*V*W

and it will give you the answer:
ans =  0.93628

Answer: Let $R \in \mathbb{R}^d$ and $w \in \mathbb{R}^d$ denote the asset returns and portfolio allocation, respectively. Assuming that $w$ is deterministic, then the portfolio return is given by $r_p = R^\prime w$, such that
\begin{equation}
Var(r_p) = Var(R^\prime w) =  w^\prime Var(R)w =  w^\prime \Sigma w
\end{equation}
where $\Sigma = Var(R)$ is the covariance matrix of asset returns.
You can calculate the same without matrix notation, which is less tractable, nonetheless:
\begin{equation}
r_p = \sum_{i=1}^d w_i \times R_i
\end{equation}
such that
\begin{equation}
Var(r_p) = Var(\sum_{i=1}^d w_i \times R_i) = \sum_{i=1}^d w_i^2 Var(r_i) + \sum_{i \neq j}^d w_i w_j Cov(r_i,r_j)
\end{equation}


Existing connexion on Apache and mod_proxy_balancer don't fail over second JBoss node

Question: I have a Jboss farm, load balanced by Apache HTTP + mod_proxy_balancer and mod_proxy_ajp, with the following configuration :
<code><VirtualHost *:80>

    ServerName web-gui-acceptance.myorg.com
    ServerAlias web-gui-acceptance

    ProxyRequests Off
    ProxyPass /web-gui balancer://jbosscluster/web-gui stickysession=JSESSIONID nofailover=On
    ProxyPassReverse /web-gui http://srvlnx01.myorg.com:8080/web-gui
    ProxyPassReverse /web-gui http://srvlnx02.myorg.com:8080/web-gui

    <Proxy *>
      AuthType Kerberos
      [...]
    </Proxy>

    <Proxy balancer://jbosscluster>
        BalancerMember ajp://srvlnx01.myorg.com:8009 route=SRVLNX01_node1
        BalancerMember ajp://srvlnx01.myorg.com:8009 route=SRVLNX02_node1
        ProxySet lbmethod=byrequests
    </Proxy>

</VirtualHost>
</code>
When the first JBoss node fail (the hosting VM is down), my existing connexions don't fail over the second node ... the fist route is keeped (in table / .shm ?) and that provide me 503 errors.
Can someone tell me what I missed ?
Answer: I may have found a workaround, that also deal with deployement / undeployement : http://www.jboss.org/mod_cluster
Advantages

mod_cluster boasts the following advantages over other httpd-based load balancers:
Dynamic configuration of httpd workers
Traditional httpd-based load balancers require explicit configuration of the workers available to a proxy. In mod_cluster, the bulk of the proxy's configuration resides on the application servers. The set of proxies to which an application server will communicate is determined either by a static list or using dynamic discovery via the advertise mechanism. The application server relays lifecycle events (e.g. server startup/shutdown) to the proxies allowing them to effectively auto-configure themselves. Notably, the graceful shutdown of a server will not result in a failover response by a proxy, as is the case with traditional httpd-based load balancers.
Server-side load balance factor calculation
In contrast with traditional httpd-based load balancers, mod_cluster uses load balance factors calculated and provided by the application servers, rather than computing these in the proxy. Consequently, mod_cluster offers a more robust and accurate set of load metrics than is available from the proxy. (see Load Metrics for more)
Fine grained web-app lifecycle control
Traditional httpd-based load balancers do not handle web application undeployments particularly well. From the proxy's perspective requests to an undeployed web application are indistinguishable from a request for an non-existent resource, and will result in 404 errors. In mod_cluster, each server forwards any web application context lifecycle events (e.g. web-app deploy/undeploy) to the proxy informing it to start/stop routing requests for a given context to that server.
AJP is optional
Unlike mod_jk, mod_cluster does not require AJP. httpd connections to application server nodes can use HTTP, HTTPS, or AJP.
The original concepts are described in a wiki.

I hope that will help.


Showing dependency relationships in Docker Registry

Question: Summary
How can we graph or otherwise get an overview of Docker image dependency relationships in the Docker registry?
Details
We're using a private docker registry instance to locally host some Docker images. We have images depending on other images (via FROM) for example:
sun-java8-build -> tomcat -> our_app

which is quite simple but it is easy for images to quickly depend on quite a few underlying "base images". How can we get an overview of which images are used to build up further images? This will help understand the impact of changes to various base images.
Answer: In my opinion dependencies should be defined using docker-compose rather than wrapping an image in an image in an image and so on.

Compose is a tool for defining and running multi-container Docker
  applications.


Is there any JS library where I can adjust the column widths in a table like excel?

Question: I need to be able to drag a "slider" to change the size of the columns like you can re-size columns in Excel. Any advice appreciated.
Answer: Check out this one
http://dobtco.github.io/jquery-resizable-columns/
It also allows to save the position of columns in the local storage.


Conditional Distributions and Rationals

Question: If $U$ is uniformly distributed on $[0, 1]$, what is the conditional distribution of $U$ given that $U$ is rational? Intuitively, it would be uniform, but we cannot have a uniform distribution over a countable set.
Comment: "$U$ is rational" is a measure zero event, so the sigma algebra generated by $U$ has only events of measure zero or one. Therefore, the conditional expectation is just the constant random variable given by the expectation of $U$, which is half. (If you are speaking of conditional expectation over a sigma algebra as a random variable).
Answer: The rationals form a null set, i.e. a set of probability $0$, and conditional probabilities given a null set are not defined.
Comment: Why are there cases where we do such conditioning? For example, say $(X_n)$ is a Poisson process - then, for a fixed $n$, we can talk about the joint conditional distribution of $X_1, \dots, X_n$ given $X_{n+1} = x$, even if the event that $X_{n+1} = x$ has measure zero.
Comment: @KurtlandChua : What do you mean by "$(X_n)$ is a Poisson process"? Poisson processes $N(t)$ take integer values and $P[N(t)=k]>0$ for all $k$. You might want another example like "what if $X$ is uniform over $[0,1]$" for which things like $E[Y|X=x]$ or $E[Y|\sigma(X)]$ make sense. (I would be interested if Robert has any insight/discussion of the distinctions.)
Comment: @Michael Oh, I guess going off of your definition, what I had in mind was $X_n = \sup_{t > 0, N(t) < n} t$ (i.e. when the arrivals happen)
Comment: There is an exception for conditioning with respect to the value of a continuous random variable.  So you can talk about conditional probabilities given $U = u$ for $u \in [0,1]$.  But not conditional probabilities given $U \in\ $ some set.

Conditional Distributions and Rationals


How do I improve my picking and fretting speed?

Question: I've seen people like John Petrucci playing incredibly fast with their right and left hands, but I can't seem to get any faster than I am now (which is speedy, but not near as fast as John).
Is there a technique I can use to increase my alternate picking speed? What about my fretting speed?
Edit: I have heard of "circular picking" and picking with just your thumb and index finger. Are either of these better for playing with speed?
Answer: Invest in a metronome. Start the metronome at a speed you can comfortably play at, then gradually increase it. Focus on playing accurately and properly, don't rush to a higher speed if you're sacrificing quality.
Speed will come from your muscle memory strengthening.
Answer: The advice is: Do not focus on playing fast. Focus on playing expressive!
Joe Satriani said (I can't find the exact quote, this is how I remember it):

There are very many players that have
  a good technique. They play very fast,
  their fingers stretch very good. But
  very few of them know how to be
  expressive - and that is the most
  important thing.

But, if you still want to play very fast (shred), you should checkout Michel Angelo's DVD "Speed Kills": I think this is the best material there is.
Comment: Oh, I can play expressively. It's my favorite way of playing, but I still want to learn how to bust out a shred when the mood hits me. I'll have to check out that DVD.
Comment: He is asking how to play fast, which is a different style than expressive. You wouldn't say "play blues instead - it's easier" to a person who asks you how to play classical music better.
Comment: @Mike Webb I agree. there is nothing like having a good set of tools at your hand :)
Answer: Speaking of a certain solo you want to speed up;
Do not use metronome until it %100 gets into your muscle memory and you can play perfectly and expressively in slow tempo(or No-Tempo) Until then just play slow and

"FOCUS" on your right and left hands watch if there is any uneconomic excessive movements, the angle you hold the pick, how much of the pick is flapping outside..etc. The more you focus on anything the more experience will be permanent.
While focusing, spot and constantly eliminate any muscle tension in your arms and hands(this is HUGE) Your goal is to have an incredible lightness in your fingers. If you feel exhaustment or pain in your fingers after a small solo, chances are you are playing against a lot of muscle tension, which can lead to injury and limit your speed. (don't confuse this with the mellow tiredness of a muscle group after a workout)
"Listen" the sound you create, make it sound flowing and "BEAUTIFUL" in any speed, as if even with that speed it would play on radio and people would love it. Every note should have a definition.

When it starts to sound "beautiful" and correct, then preferably with a metronome little by little increase the speed without compromising that beauty and quality. But speed should come to you as a result of excellent conditions, and not you are trying so hard for it. All of a sudden you will feel like you can play a little faster with any extra efforts and tensions. Then you never have fear of playing the solo right or wrong for that speed, it will always be right. it will not be one big moment in the song that you feel the fear before solo if your gonna pull it correctly now or not.
Then you will get stuck on certain parts of solo, analyze them whats going on(which picking mechanics you use(up/down), are you changing strings with an up or down stroke ..etc) and isolate and only work on that 2-3 note spots maybe 1000 times(this is called efficient practising) then slowly incorporate everything together by the time.
After a while you will be saying to yourself "It's so easy, how come I couldn't play like this on the first time"
Comment: +1 on "Do not use metronome until it %100 gets into your muscle memory". Practice makes permanent; Perfect practice makes perfect.
Comment: @Spring Just a head's up, when you reach ten edits on your post, it will automatically become community wiki. You will no longer receive reputation from it. Make your edits count.
Answer: Play with a metronome, while you are practicing drills. It's nice to be fast but it's really important to play in time. Once you get a speed in beats per minute where you are comfortable and are playing smoothly and cleanly then you you start bumping up the speed on the metronome a little at a time each time practicing until you are clean and smooth at the speed. In my opinion and if you watch a video of John Petrucci playing it's really apparent, how cleanly and smoothly you you learn to play at lower speeds will determine how fast you are at higher speeds. It's all about efficient movements of your hands.
It also helps to video tape your hands while playing and watch for wasted movements, the less you have to move you fingers/hands the faster you will play.
Comment: The "less movement" makes sense. I've noticed that I can go faster with a hard pick, and a buddy of mine said that it was because less bend in the pick allows for tighter alternate picking (i.e. less right-hand movement).
Answer: There is this pc program that helps you do just that check it out:
http://www.guitarspeed.com/
note: I am not spaming in any way nor affiliated to this site.
Comment: Self-contained answers are generally best.  At minimum, you should have a description of how the program works.
Comment: I looked at the link, and found a quick guide to the main consepts, which looked useful, even without having the program - just read the tips and techniques on this page: http://www.guitarspeed.com/gst/method.asp. Instead of using the program, I would say you would get far by following this guide, and use a metronome to help pick up speed.
Answer: There is no magic pill, no specific technique is the "speed technique", though many people sell books and instructional videos based on this idea.
Speed comes naturally when you have the movements in your muscle memory.  The key to effortless speed is to practice basic movements every single day at a slow to moderate tempo where your whole body is relaxed.
One good method book that goes into this (and it's not a trick like "circular picking" and other ideas) is Speed Mechanics for Lead Guitar.  The exercises are great but more important is the front matter where he goes through the art and science of practicing.


What's the simplest test that I can do to check if my cron jobs are working?

Question: What's the simplest test that I can do to check if my cron jobs are working?
Comment: Do you want a simple or reliable check?
Comment: Simple check will do, like Andy's answer. A more complicated check might also prove useful in the future.
Answer: Set up a test cron:

*/5 * * * *  echo "test" >
  /tmp/crontest.txt

This will write "test" to the file /tmp/crontest.txt every 5 minutes
Ensure the cron daemon crond is running using

[andy@server]# ps aux | grep cron
root      4321  0.0  0.0  76543  3211
  ?        Ss   Jul31   0:07 crond

Check the logs using

tail /var/log/cron

Try date to ensure you are in the correct timezone
Comment: I had to make the first parameter to 0-59/5 to make it work.
Comment: Apologies it should have read */5, have amended answer
Answer: Simply change their execution time and see the result ! :)
If you have cron that will run on

12 24 * * *

change it to

mm hh * * *

where hh and mm is an hour and minute very near to the actual time.
Once verified the execution restore the correct timing
Comment: +1 for tip on changing the execution time
Answer: /2**** touch cronrunning >/root/Desktop
it will show u file coming to desktop
Comment: Downvoted: Bad practice, invalid syntax, bad spelling.


Undefined Symbol: _ZN3a13A when importing pybind11 bindings

Question: I'm trying to create pybind11 bindings for an existing cmake project. The CMakeLists.txt file looks like the one in the tutorial. The project builds without errors, however, when trying to import the module in ipython, the following error comes up:
~/workspace/a/build/pya.cpython-35m-x86_64-linux-gnu.so: undefined symbol: _ZN3a13FooC1ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Trying to solve it: It seems related to the toolchain (this issue looks similar). I've gcc 6.5.0 and cmake 3.12.0 installed.
Comment: It seems that you didn't properly link something. Unfortunately the names in C++ are sometimes nog very descriptive, but sometimes you recognise part of the name to give you a hint what you did not link. To be able to help you we need a minimal reproducible example here.
Comment: It seems you did not put the cpp file of the `_ZN3a13FooC1ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE` function to the compile command.
Comment: Additionally, check closely that the function signature in your .h file matches the one in your .cpp file.
Answer: This is harder to answer than necessary, the linker error message is obfuscated.  Use an online demangler to see the plaintext symbol name that the linker cannot find.  Be sure to copy/paste the real mangled symbol.
A valid mangled name that somewhat resembles the error message would be _ZN1a3FooC1ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE.  Which demangles to a::Foo::Foo(const std::string&).
In other words, you declared a constructor for the Foo class but forgot to write it.  Pretty standard mistake. More about these linker errors in this Q+A.


i need to test an html page i made by a mobile connected through verizon

Question: i have this page
http://m.bsmitho.com/
and i need someone who's connected through a verizon mobile (mobile connection not wifi) to test my page and tell me if the verizon mobile logo appears ?
the code i have used :
<code>     <script type="text/javascript">
     $(document).ready(function() {
         $.get("http://ipinfo.io", function (response) {
             if (response.org == "AS6541 Verizon Online LLC") {
             document.getElementById("verizon").style.display = "block";
                 }
          }, "jsonp");
     });

     </script>
</code>
please i need your help, soon.
thank you
Comment: I'm voting to close this question as off-topic because Stack Overflow is not a user testing website.
Answer: Yes this works
<code><script type="text/javascript">
 $(document).ready(function() {
     $.get("http://ipinfo.io", function (response) {
         if (response.org == "AS6541 Verizon Online LLC") {
         document.getElementById("verizon").style.display = "block";
             }
      }, "jsonp");
 });

 </script>
</code>


Print key value as a class along with the label for a list field?

Question: I have a node with a field which is a List (integer). I can print the value in node tpl with the following:
<code><?php print render($content['field_name']);  ?>
</code>
However I also need to style each result differently. For instance one of the options is 'large' and I want to add a background image to every 'large' result.
How can I do this? I was thinking if I could print the key value as a class along with the label the I could easily do the rest with CSS.
Answer: You should not actually want to do this in your node.tpl file. Drupal uses a system of (pre)processors to alter variables before they get rendered. That is where the logic should go.
Have a look at this topic that has a lot of explanation and references https://stackoverflow.com/questions/2383865/how-do-i-use-theme-preprocessor-functions-for-my-own-templates
Once you have your output ready you should be able to do the styling with CSS.


Suggestion for FB meta tags using jquery and php

Question: here is my problem:
i have FB app, where i am getting data from json and using that data for making list of items in my main window, i can click on every item, and after i click it opens in new ajax window where i get more info about that item
problem is about meta tags for FB, cos i have LIKE button for every item, so when i click on it, i can post that item on FB wall with infomations like title, picture and description
i have this situation:
when i click on item in my main window, it opens in new ajax window, and i manually add item it to the URL like this:
<code>window.location.href=window.location.href + "?id=" + ID + "#id=" + ID;
</code>
and php code is this:
<code>    <?php

    if(isset($_GET['id'])){

    $json = file_get_contents("http:....." . $_GET['id'] . "&...");
    $json_array = json_decode($json);
    print '<meta property="og:title"       content="' . $json_array->title . '" /> ';
    }
?>
</code>
it all work all right, but i get problem with refreshing page, cos every time i click on item in my main window it open new window cos i add GET parameter in url
so how can i avoid refreshing page and still have functionality for describe like option on FB wall
Answer: If you have a like button for every item in a list, this means you also have a corresponding page for each item too, right? If so, cant you have he meta tags predefined on each lf those pages?
Facebooks likes are designed to like pages so other friends can click through and see the page that the users liked.
Comment: no, it is all the same page, just ajax function shows other content depends on item click, cannot predefine it cos FB caches meta tags, so i can put just static meta tags so for every like it would be the same
Comment: like i wrote in my first post it works dynamically, but problem is when i add GET parameter in URL it refresh my page, and just wanna avoid it


Falha no uso de JSON no INTEL XDK

Question: Estou fazendo uma aplicação no INTEL XDK, na qual preciso conectar com o Banco de dados. Criei o PHP para retornar com JSON e no Intel, fiz a função pra retornar tais dados. Porém a aplicação não está retornando nada, e como nunca fiz nada nessa área, decidi vir aqui pedir ajuda.
Códigos :
JSON.PHP
<?php
    header("Access-Control-Allow-Origin: *");
    header("Content-type: application/json; charset=UTF-8");

    $conecta = pg_connect("host=localhost port=5432 dbname=**** user=****** password=******");
    $sql = "select * from oi";
    $resultado= pg_query($conecta, $sql);

echo '{"produto":}';
$saida = "[";

while($r = pg_fetch_array($resultado))
{
    if($saida != "["){$saida.= ", ";}
    $saida.= '{"Produto":"'.$r["nomeprod"].'"}';

}
$saida.="}}";
echo $saida;

        ?>

App.js
$(document).ready(function(){
$.ajax({
    type:"GET",
    url:"http://22.214.171.124/bruno_pereira/TCC/json.php",
    dataType:"json"
}).done(function(data){
        var mostra = "";
        $.each(data.produto, function(i,x){
            mostra+= "
"+x.Produto+"
";
        });
$("#result").html(mostra);
            });
});

Comment: olá! Primeiro, você está executando a página a partir do _localhost_ ? Do contrário não irá mostrar nada mesmo. Também não sei se é o caso, mas para transformar o array em JSON, você poderia usar a função [json_encode](http://php.net/manual/pt_BR/function.json-encode.php) .
Comment: Então, eu utilizo o WinSCP para hostear tudo em uma máquina do meu colégio.. No caso esta máquina (18.104.22.168
Answer: Olá,
Tente alterar o php para chamar a função json_encode para fazer a codificação automaticamente, assim você não precisa montar o JSON manualmente:
PHP
$conecta = pg_connect("host=localhost port=5432 dbname=**** user=****** password=******");
$sql = "select * from oi";
$resultado= pg_query($conecta, $sql);

$r['dados'] = $resultado;
echo json_encode($resultado);

    ?>

E mostrando caso a requisição tenha sucesso:
JS
$(document).ready(function(){
$.ajax({
  type:"GET",
  url:"http://18.104.22.168/bruno_pereira/TCC/json.php",
  dataType:"json"
    }).done(function(data){
         var mostra = "";
         for (i=0; i< data.dados.length;i++){
           mostra+= "
"+data.dados[i].nome_do_campo_desejado+"
";
           /* esse nome do campo desejado deve ser o nome de algum campo desejado que tenha
              sido pesquisado no SELECT do PHP */
         }

$("#result").html(mostra);
        });
});

Falha no uso de JSON no INTEL XDK


Is it safe to `.Select` an `out` parameter that was set in a preceding `.Where` clause (with `TryParse`)?

Question: I have some code that I'm shortening from a loop to a Linq statement, but it feels dangerous to do so.
Is it safe to .Select an out parameter value that was set in the preceding .Where clause (with TryParse) within the same statement? The main reason I ask is that I got a compile error in the Select statement that "local variable val may not be initialized before accessing", even though it should be guaranteed in the Where clause, so I had to assign val a "dummy" value to get this to compile.
var items = new List<string>();

// out parameters don't have to be assigned first, but the compiler forced me to.
int val = 0;

var result = items
    .Where(item => int.TryParse(item, out val))
    .Select(i => val)
    .ToList();

In my limited testing it seems to produce the correct results, even if I remove the .ToList and change the value of val.
Are there any "gotchas" here?
Comment: That seems like a Bad Idea(tm). I would rather do something like `items.Select(i => new { gotIt: dict.TryGetValue(i, out string val), gotWhat: val }).Where(i => i.gotIt).Select(i => i.gotWhat).ToList()`; just to be sure
Comment: `This example is actually from another question here, but I'm mostly asking about the pattern of passing an out parameter in the Where and then using it in the Select.` Will it work? Generally yes (as long as it is all LINQ to Objects and you are reading it _immediately_ after so sorting etc can't mess you up - it clearly won't work in EF for example). Is it a good idea? I'd avoid it if an alternative is available.
Comment: `AsParallel` is an example of something that could likely cause havoc with your current approach @RufusL.
Comment: I wouldn't do this. The fact you have to ask the question here demonstrates it's not immediately clear how it would behave. Honestly, I see nothing wrong with using a `foreach` instead. LINQ isn't always better.
Comment: `even though it should be guaranteed in the Where clause` The compiler is not smart enough to realise that the code in `Where` will definitely happen - hence the warning.
Comment: It is weird, since it is taking this variable outside of the LINQ expression and making it quite central to the correct operation of the LINQ. Hence why I would do it the tuple way (my suggestion is basically the same as Heretic's). In other words, have the LINQ self contained.
Comment: The code you posted is awful, for the very reason that it's obfuscated. There are many different alternatives that would work instead and which would be _clearly_ correct, rather than making the reader of the code scratch their head (my preferred would be to use an intermediate anonymous-typed object to capture both parts of the `TryParse()` result...i.e. `.Select(...).Where(...).Select(...)` or the query expression equivalent. First projection sets up the data, while the `Where()` and second projection make use of that.
Comment: @mjwills That's a good point. This example is actually from another question here, but I'm mostly asking about the pattern of passing an `out` parameter in the `Where` and then using it in the `Select`.
Comment: @JohnH - It's quite possible to make malformed `foreach` statements. What do you see as the benefit of using `foreach` over LINQ?
Comment: @Enigmativity I see your point, but it's possible to write all sorts of malformed statements. The difference with the foreach is it is much simpler because there is no having to guess about the implementation of LINQ itself, and the suggestion of writing extension methods and such to handle something like this, in my view, is over-engineering. KISS.
Comment: @JohnH - I'm going to continue to play Devil's Advocate, if that's OK. Can you tell me when you have to "guess about the implementation of LINQ itself"?
Answer: That probably works, but not safe. Here's a safer alternative.
/// A generic delegate for <see cref="selectWhere{TSource, TResult}(IEnumerable{TSource}, pfnSelectWhere{TSource, TResult})" />
public delegate bool pfnSelectWhere<TSource, TResult>( TSource source, out TResult result );

/// Combined Where + Select extension method for lazily-evaluated sequences
public static IEnumerable<TResult> selectWhere<TSource, TResult>( this IEnumerable<TSource> source,
        pfnSelectWhere<TSource, TResult> selector )
{
    foreach( var i in source )
        if( selector( i, out var r ) )
            yield return r;
}

// Usage example
static void Main( string[] args )
{
    var items = new List<string>();
    List<int> result = items
        .selectWhere( ( string s, out int v ) => int.TryParse( s, out v ) )
        .ToList();
}

Answer: It feels unsafe, but I struggled to make a situation where it failed using a single thread.
If we go multi-threaded then all bets are off anyway.
The fact that the Select immediately follows the Where and there is no intermediate manipulation of the val variable makes this safe in this particular example.
However, this kind of thing can easily go wrong, and, as a good coder, we know to avoid external state on LINQ expressions.
Fortunately there are a number of ways around this. My favourite is this:
var result =
    items
        .SelectMany(item =>
            int.TryParse(item, out int val)
            ? new[] { val }
            : Enumerable.Empty<int>())
        .ToList();

Or even:
var result =
    items
        .Select(item =>
            int.TryParse(item, out int val)
            ? (int?)val
            : (int?)null)
        .Where(val => val.HasValue)
        .Select(val => val.Value)
        .ToList();

If you want to use the original code, but make sure it is safe then here's a simple extension method to do so:
public static IEnumerable<R> Capture<T, R>(
    this IEnumerable<T> source,
    Func<IEnumerable<T>, IEnumerable<R>> transform)
{
    foreach (var r in transform(source))
    {
        yield return r;
    }
}

This can be used like this:
var result =
    items
        .Capture(xs =>
        {
            int val = 0;
            return
                xs
                    .Where(item => int.TryParse(item, out val))
                    .Select(i => val);
        });

Comment: @mjwills - Yes, well, that's true. I was just trying to say that I considered the multi-threaded case, but wasn't going to go into it any further.
Comment: `If we go multi-threaded then all bets are off anyway.` To be fair, that is only because of the use of the shared state (i.e. a good argument for not using the shared state). Without the variable outside of the LINQ statement parallel is generally very safe...


Lydian Guitar Voicing (Maj7 #4 Chord)

Question: From the fourth mode (Lydian) of the major scale (in C) we get F G A B C D E F. In jazz, it appears the fifth is often omitted and the #4 takes over in place of it. This results in F A B E, the root, maj 3rd, tritone, and the seventh.
I have found one voicing on guitar so far that sounds good for this:
e -> 0
B -> 0
G -> 2
D -> 3
A -> x
E -> x
Are there any with the root on the A or Low E?
Answer: Yes, if you allow the upper notes to scramble, other voicings appear. For example, a few of them are:

R-7M-3-♯11.

GMaj7(♯11) = 3x442x
CMaj7(♯11) = x3x452

R-♯11-7M-3

CMaj7(♯11) = x3445x

R-3-♯11-7M (your example, which is almost impossible to play in upper strings as you noticed)

GMaj7(♯11) = xx5422
(Although I called the interval a ♯11 and not ♯4, since there are no 9ths and 5ths in my examples, in practice they are the same thing as the Maj7(♯4) chords you describe)
Comment: I don't get the reasoning in your comment, but the notation Cmaj7(♯11) implies: R 3 5 7M 9 ♯11. However, it's customary (but not required) to omit certain notes in these extended chords. The 5 and the 9 would be the first options (the 3, 7 and the extensions you really want and write, in this case ♯11, can't be excluded). If I see a  Cmaj7(4) I would believe it's a misspelled Cmaj7(sus4). I believe Cmaj7(♯4) would be seen as a misspelled Cmaj7(♯11), although the logic makes me see a Cmaj7(sus♯4). People might have different meanings to certain notations apart from the "correct standard".
Comment: Yeah, I use #4 and #11 interchangeably, but not sure if I should. Also, really like `CMaj7(♯11) = x3445x`. Sounds sooo Diablo I
Comment: Yeah, because the tritone is evident in two adjacent voices and they are in the low register. Not very jazzy :) When dealing with a chord, you want a ♯11 and not a ♯4. A 4 replaces the 3, unless you write "add4". 11 is probably what you want, but it comes with the possibility of a 9.
Comment: so this chord should omit the 3 and 5 and be root 4 7 11 13?

Lydian Guitar Voicing (Maj7 #4 Chord)


Contar valores se os valores em duas colunas da mesma linha forem especificados

Question: Tenho duas tabelas no excel, Fornecedores e Histórico:

Preciso fazer uma contagem de quantas vezes o fornecedor A cometeu o erro A, o fornecedor A cometeu o erro B... e assim por diante, pensei em montar algo com CONT.SES, mas o valor de FornecedorA e ErroA deveria bater em duas colunas da mesma linha, não estou conseguindo pensar em uma maneira de fazer isso...
Preferia não usar Macro.
Tentei algo assim:
=CONT.SES(
  Historico!B:C,
  Fornecedores!B1=Historico!B:B,
  Historico!B:C,
  Fornecedores!A2=Historico!C:C
)

Alguma ideia de como posso montar isso?
Answer: Em sua Planilha de resultado coloque da seguinte maneira em B2:
=CONT.SES(Historico!B:B;$A1;Historico!C:C;B$1)

Arraste para de B2 para D2e veja se funciona, depois arraste para os outros fornecedores adaptando a fórmula.


SharePoint 2016 Custom Timer Job Not Showing in Job Definition

Question: I am stuck into something really strange behavior of SharePoint.
I have a SharePoint 2016 farm solution. which contains 5 timer jobs classes.
When I change something in any job class. all of the sudden any one of these 5 jobs stop showing in job definition. and after 1 month it again start to show up in the definition.
Moreover, if I create a new solution and create any job in it and deploy, it also doesn't show up in the job definition.
List of jobs

Job definition
Answer: Are you using Feature EventReviever to add and configure the Job in Job Definitions?

This will add the job in Jobs Definition Section and Deactivating Feature will Remove the Job if you activate the Feature.
<code>public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        try
        {
            SPSecurity.RunWithElevatedPrivileges(delegate ()
            {
                SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
                DeleteExistingJob(JobName, parentWebApp);
                CreateJob(parentWebApp);
            });
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
    {
        lock (this)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate ()
                {
                    SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
                    DeleteExistingJob(JobName, parentWebApp);
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
</code>
If this is not the issue and you have a Feature Event Reciever then share the cs file here.


Write db2 table data to flat file

Question: I have doubt may be it look like basic ,I need to copy data from db2 table to flat file in cobol .1)Can I use just select query to get data and write( or )use cursor and then write.
2)can i use select/ cursor without where clause.can you pls clarify my doubts
I have used select query to get data without cursor.
Comment: I'd suggest using a cursor so your program code can process one row at a time.  Your SELECT statement doesn't need a WHERE clause.
Answer: You must use a cursor if you want to fetch multiple rows from a DB2 table in COBOL. Your SQL SELECT does not have to have a WHERE clause. If no WHERE clause is specified the entire table will be accessed via the cursor. For each row accessed you can format and move the data to the output file record and write it. At the end, close the cursor and the file.
You can order the retrieval of the rows using SQL ORDER BY.
Note that you have to allocate enough space for the file.
The task requires familiarity with DB2, JCL and COBOL.
Example

Write db2 table data to flat file


Changing tool executable name in Xcode 4.6

Question: I've found several answers here which would seem to answer this question, none of them have worked.
I'm making a command line tool with Xcode 4.6.2, under Mac OS X 10.8.5. The tool started as a copy of the "USBNotificationExample". I can not find out how to change the product name, whatever I do its stubbornly "USBNotificationExample".
If I click on the product name in the project, the right pane has an edit box with the name "USBNotificationExample", but this is greyed out and can not be edited.
I have changed every other editable field I can find. The project name has been edited.
I have edited the build settings in the Packaging section. "Product Name" has been changed. (Initially this was blank, which seemed strange.)
I even tried directly editing the project.pbxproj inside the project package, that didn't work either.
Answer: I am using Xcode 5, however I am certain this has not changed since Xcode 4.
What you want is Packaging > Product Name (filter on "name").
Below is an example of a product that started as "TestProject" but I renamed to "MyNewName"
Comment: As I mentioned, I already tried Packaging > Product Name and that didn't work.
Comment: @Barry That's the way it's done, unless you've messed-up the `Info.plist` file.
Comment: Agree to Droppy's answer. Note that in your 'Info.plist', as mentioned before, there are variables like ${EXECUTABLE_NAME} and ${PRODUCT_NAME} ... if you have changed any of these from the vanilla settings, you should revert that.


Como fazer query contendo MAX e COUNT via LINQ

Question: Tenho o seguinte model:
 public class Crm_Analise
{
    [Key]
    public int id { get; set; }
    public string cod_item_CRM { get; set; }
    public string TAG { get; set; }
    public string data_creat { get; set; }
    public string modelo { get; set; }
    public int cliente_CRM { get; set; }
}

Via scaffolding gerei o controller e as views.
Alterei a View Index para:

            @Html.ActionLink("TAG", "Index")

            @Html.ActionLink("ATUALIZAÇÃO", "Index")

            @Html.ActionLink("RELATÓRIOS", "Index")

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.TAG)

            @Html.DisplayFor(modelItem => item.data_creat)

            @Html.DisplayFor(modelItem => item.modelo)

            @Html.ActionLink("Visualizar", "Details")

}

Então queria agrupar por TAG, sendo MAX(data_creat) e COUNT(modelo).
Se fosse via SQL, eu faria:
SELECT TAG, MAX(data_creat) AS 'ATUALIZAÇÃO', COUNT(modelo) AS 'RELATÓRIOS'
FROM Crm_Analise
WHERE cliente_CRM = @cliente_CRM
GROUP BY TAG

Então no controller fiz:
// GET: Crm_Analise
        [Authorize]
        public async Task<ActionResult> Index()
        {

        if (Session["cod_cli"] != null)
        {
            int cod_cli = Convert.ToInt32(Session["cod_cli"]);

            var query = from s in db.Crm_Analise
                        select s;

            query = query.Where(s => s.cliente_CRM == cod_cli);

            return View(await query.ToListAsync());
        }
        else
        {
            return RedirectToAction("Login", "Account");
        }
    }

Mas como aplico o MAX, COUNT e o GROUP BY?
Atualização ref. a resposta do @Maniero:
Ao tentar executar conforme a resposta, foi gerado o erro:

Atualização ref. ao comentado do @LINQ:
Alterei a variável do Count para uma variável do tipo int:
Comment: Não, você está confundindo as coisas. Você precisa saber **o que** quer contar. O `Count` recebe um predicado e não um elemento. E no SQL não existe "contar mesmo que seja varchar", se você pôr uma coluna no count vai ser validado se aquela coluna é nula.
Comment: Como é que você pretende aplicar um `Count` passando uma `string`? Você quer contar os modelos que não sejam nulos?
Comment: @Linq, me corrija se estiver errado por favor, No sql, eu consigo contar, mesmo que for do tipo `Varchar` certo? porque aqui não? alterei, para um variavel INT e ainda assim continua o erro.
Answer: A query está certa mesmo? É isso que quer? Então em LINQ vai usar Max(), Count() e GroupBy(). Não garanto o jeito exato, mas é algo assim:
var query = from s in db.Crm_Analise
                group s by s.TAG into g
                where s.cliente_CRM == cod_cli
                select new {TAG = g.TAG, ATUALIZAÇÂO = g.Max(t => t.data_creat), RELATÓRIOS = g.Count(t => t.modelo != null)};

Coloquei no GitHub para referência futura.
Comment: bom dia, obrigado pela ajuda, mas esta me retornando um erro.. fiz uma atualização na pergunta com a imagem do erro, tambem fiquei com uma duvida, a clausura `Where` tem que vir antes do  `Group By` certo?
Comment: Responda ao que o LINQ disse para saber o que fazer. Eu achei que teria esse e até outros problemas. Se for o que ele comentou eu mudo na resposta, é só verificar se não é nulo, embora eu acho essa contagem bem esquisita.
Comment: Eu queria contar, quantas vezes a TAG se repete dentro da lista, por isso o Count.. obrigado.
Answer: O Count no SQL, quando recebe um campo, retorna a contagem de todas as linhas da tabela menos aquelas onde o campo passado for nulo.
No LINQ, o Count sempre recebe um predicado e não um elemento, então, para simular o efeito do SQL, você precisa fazer uma condição com o campo.
var query = from s in db.Crm_Analise
            where s.cliente_CRM == cod_cli
            group s by s.TAG into g
            select new
            {
                TAG = g.TAG,
                ATUALIZAÇÂO = g.Max(t => t.data_creat),
                RELATÓRIOS = g.Count(t => t.modelo != null)
            };

Comment: No LINQ ... referencia circular  ( ͡° ͜ʖ ͡°) ...


How to represent a complete picture of uncertainty in linear regression predictions [rather than intervals]?

Question: Say I have a set of data for three quantities $x$, $z$, and $y$ at various locations, $i$. I then fit a linear model,
$$ y_i = a x_i + b z_i + \epsilon_i $$
to this data, assuming $\epsilon_i \sim N(0, \sigma)$, with the value of $\sigma$ unknown.
I'm then interested in predicting $y$ at some new locations $j \in \{1,2,...n\}$, and most importantly I'd like to quantify uncertainty in that prediction. We have $x$ and $z$ values in these new locations. The question is how do I generate something like a histogram of $y$ at each of these locations that account for all uncertainty. Presumably, simply saying
$$y_j \sim N( \hat a x_j + \hat b z_j, \hat \sigma ),$$
where $\hat a$ and $\hat b$ are the estimates of the coefficients from the linear regression model and $\hat \sigma$ is the residual standard error, is not account for all of the uncertainty, because it assumes the estimated coefficients are true.
So for example how might I plot a histogram for each $y_j$, given the model that accounts for all uncertainty. I think this is related to prediction, vs. confidence intervals for which there are a lot of tutorials online, but I'm interested in the full distribution. The R code below does roughly what I want to do, but I don't think it accounts for enough uncertainty.
## data for fitting
n = 100;
x = rnorm(n, 1, .5);
z = rnorm(n, .5, .1);
y = rnorm(n, mean = 2*x - 6*z, sd = 1)

mod = lm(y~x+z)

## new data
xn = rnorm(n, 1, .5);
zn = rnorm(n, .5, .1);
ytrue = rnorm(n, mean = 2*xn - 6*zn, sd = 1)

## predict with uncertainty
j=2; #choose a site to plot uncertainty
y_pred_samp = rnorm(500,
              mean = mod$coef[1]*xn[j] + mod$coef[2]*zn[j],
              sd = sigma(mod))

hist(y_pred_samp, main = paste('true value is: ', ytrue[j]))

Answer: Your R code treats the parameters as if the estimates were the true values, and only covers the uncertainty in residual noise. This is typically not what we want in a prediction interval. (You are right that this is the term you want to learn about.)
In order to account for the uncertainty in the parameter estimates, we need two new ingredients:

The covariance matrix of the parameter estimates (viewed as random variables, since they are transformations of the observations, which are in themselves realizations of a random variable)
The $t$ distribution instead of the normal distribution that we started with.

Ordinary least squares is special in that we have a neat closed form solution of the predictive distribution (assuming, of course, that our initial assumptions about the model form and the normal distribution of the error are correct). Specifically, the predictive distribution is a scaled and mean-shifted $t$ distribution, with central $1-\alpha$ level prediction intervals given by
$$ \hat{y}\pm t_{n-p}^{(\alpha/2)}\hat{\sigma}\sqrt{1+x^t(X^tX)^{-1}x}, $$
where

$x$ contains the predictor values for the prediction (assumed known and non-random)
$X$ is the design matrix of the predictors used in training
$\hat{y}=x^t\hat{\beta}$ contains the expectation prediction
$\hat{\sigma}$ contains the estimate of the residual standard deviation
$t_{n-p}^{(\alpha/2)}$ contains the $\alpha/2$ quantile of the $t$ distribution with $n-p$ degrees of freedom (where $n$ is the number of historical observations, and $p$ is the number of parameters estimated)

You can find this in any slightly more advanced book on regression, e.g., Faraday, 2002, Practical Regression and Anova using R, section 3.5. Proofs are usually to be found in standard textbooks on mathematical statistics.
So in your specific situation, you could create a histogram of predicted outcomes for a specific value of your predictors as follows:
x_new <- 0.2
z_new <- 0.4
newdata <- matrix(c(1,x_new,z_new),nrow=1,dimnames=list(NULL,c("Intercept","x","z")))
y_pred <- predict(mod,newdata=as.data.frame(newdata))

sims <- y_pred +
    rt(500,n-3) * summary(mod)$sigma *
    sqrt(1+newdata%*%solve(crossprod(model.matrix(mod)))%*%t(newdata))[1,1]
hist(sims)

Note that inverting a matrix using solve(), as we do above for clarity, may be unstable, depending on the matrix. It works fine here, though.
Alternatively, if all you wanted was a predictive interval, you can use predict.lm() (as above), with the parameter interval="prediction". This will give you prediction intervals as above, which is something different from confidence intervals (which in turn you could get using interval="confidence").
Comment: This is very useful! So if I wanted to simulate a histogram he residuals, I could draw t distributed random variable with n-p degrees of freedom and multiply it by the scalar on the right in your equation and ad it to the predicted value for y? Appologies if I misunderstood how to translate between computing the prediction interval and simulating the full distribution. Also should lowercase x include a 1 or 0 for the intercept? I get a dimension mismatch if I don't put something in for the intercept I think.
Comment: I edited my answer to include some code to simulate. The lowercase $x$ should indeed be analogous to the rows in the original design matrix $X$, so it should indeed contain a leading $1$ (assuming you have an intercept in your model).


How to suppress file output from aws s3 ls?

Question: I am using the aws cli to summarize the number of files and the total size of an s3 bucket using the following command (documentation):
aws s3 ls s3://mybucket --recursive --human-readable --summarize

This command gives me the following output:
2013-09-02 21:37:53   10 Bytes a.txt
2013-09-02 21:37:53  2.9 MiB foo.zip
2013-09-02 21:32:57   23 Bytes foo/bar/.baz/a
2013-09-02 21:32:58   41 Bytes foo/bar/.baz/b
2013-09-02 21:32:57  281 Bytes foo/bar/.baz/c
2013-09-02 21:32:57   73 Bytes foo/bar/.baz/d
2013-09-02 21:32:57  452 Bytes foo/bar/.baz/e
2013-09-02 21:32:57  896 Bytes foo/bar/.baz/hooks/bar
2013-09-02 21:32:57  189 Bytes foo/bar/.baz/hooks/foo
2013-09-02 21:32:57  398 Bytes z.txt

Total Objects: 10
   Total Size: 2.9 MiB

However, I'm only after the Total Objects and Total Size output, e.g.:
Total Objects: 10
   Total Size: 2.9 MiB

How can I only display the Total Objects and Total Size while suppressing/hiding the rest?
Comment: `aws s3 ls s3://mybucket --recursive --human-readable --summarize | tail -2`
Answer: Either use tail to show the last few lines or grep to filter the output based on the "Total" keyword at the beginning of the line (optionally with the extra whitespace), like:
aws s3 ls s3://mybucket --recursive --human-readable --summarize|tail -n2

Or
aws s3 ls s3://mybucket --recursive --human-readable --summarize|grep -e '^\s*Total'


Problems clearing TextField when designed for digit-only input

Question: I have a Java program used by my contributors and I need to update it to work on newer Windows versions.  I had to decompile the existing one to get the code.  One of the bugs is that one of the fields on the GUI is set up as a digit-only field, and then when you hit the clear button, all of the text fields get cleared except for the text field.  Here's how the digit-only restriction has been coded:
public void keyPressed(KeyEvent paramKeyEvent)
{
  char c = paramKeyEvent.getKeyChar();
  if ((!Character.isDigit(c)) && (Character.getType(c) != Character.CONTROL)) {
    paramKeyEvent.consume();
  }
}

When the clearing code writes to the text field using setText("") executes, the field is not cleared.  I suspect it is because the null is not recognized by the above if statement and the event is consumed.
I programmed in C for 15 years, but I've only been teaching myself Java since January, so I'm not able to make major changes to this code in a timely manner at this point.  I see that there are many ways to implement the digit-only input, but I'm not eager to rewrite large portions of this code if at all possible to resolve it the way it is structured.
I appreciate any help in figuring this out.  Thanks.
As an update, I tried writing a zero to the field instead of "" and that works, so it does seem like it's the way the digit-only field is implemented that is causing the problem.
After more searching (I thought I'd exhaustively searched!) I found reference to a setText bug -- the only way around it seems to be to use setText to write a blank and then null.  It works!
Answer: You cannot do setText("") instead add a blank, setText(" ")
Comment: Well, that's the weird thing -- all the other text fields work just fine writing "".  It's only the field that is digit-only that will not clear.  But I did discover as you say, that if I write a blank and then a "", it works.


Analysing transformed data

Question: Is it possible to carry out normal multiple linear regression when the dependent variable and one predictor variable have been transformed using square root transformation? (as they did not follow normal distribution).
Is there any back transformation necessary for the R2 value, coefficients and confidence intervals?
Comment: Linear regression does NOT require that the predictors be normal, nor that the dependent variable be normal, only that the residuals be normal.
Comment: See
http://stats.stackexchange.com/questions/34920/what-kinds-of-variables-should-we-use-the-normality-test-for
http://stats.stackexchange.com/questions/45671/normality-of-residuals-vs-sample-data-what-about-t-tests
Comment: I agree w/ @PeterFlom. In that vein, you may find this thread informative: [what-if-residuals-are-normally-distributed-but-y-is-not](http://stats.stackexchange.com/questions/12262/).
Answer: Only the residuals need to be normally distributed, as @PeterFlom & @Glen_b note in the comments.  The linked threads will help you to understand this issue.
If you have transformed your X variable (e.g., adding a squared term), nothing much really happens.  Everything is fine with using and interpreting your model as is.
On the other hand, if you have transformed your Y variable, people often want to know what a predicted value will be in terms of the 'regular' Y dimension.  To do this properly, you calculate a predicted y value, and back transform it.  You can also calculate upper and lower confidence bounds, and back transform them.  However, you do not back transform your betas / coefficients (cf., my answer here).  Also, you may interpret $R^2$ as is, there is no transforming or back transforming $R^2$.
Comment: Isn't the re-transformation problem more involved than simply back-transforming the prediction? For example, with the natural log transformation, $E[y_i \vert x_i]=\exp (x_i'\beta) \cdot E[\exp (u_i)]$?
Comment: I am worried that $\exp \{E[\ln y]\}\ne E[y].$ Under your normality assumptions, to get prediction on the un-logged scale you would need to multiply $\exp \{\ln(\hat y_i)\}$ by $E[\exp \{u_i\}] \approx \exp \{\frac{\hat \sigma^2}{2}\},$ where $\hat \sigma^2$ is the unbiased estimator of the log-linear regression model error.
Comment: @DimitriyV.Masterov is correct, see a pretty straight forward discussion here on the Stata blog, [Use poisson rather than regress; tell a friend](http://blog.stata.com/2011/08/22/use-poisson-rather-than-regress-tell-a-friend/). The expectation of the exponentiated error term *is not one*.
Comment: I'm not sure what you're getting at, @DimitriyV.Masterov. If you are worried about whether your assumptions are met (eg, the variance scales w/ the mean &/or the residuals are skewed), & you transform $Y$ st, eg, $$\ln(Y)=\beta_0+\beta_1X+\varepsilon\\ \text{where }\varepsilon\sim\mathcal N(0,\sigma^2)$$, then you can get the predicted value at $x_i$ on the original $Y$ scale by $\exp(\widehat{\ln(y_i)})$, but you certainly wouldn't use $\exp(\beta_0)+\exp(\beta_1)x_i$.
Comment: I still don't get the upshot here, @DimitriyV.Masterov. If the regression assumptions aren't met on the original $Y$ scale, we don't want $E[y_i|x_i]$, so it doesn't matter that $E[\ln(y_i)|x_i]\ne E[y_i|x_i]$. Just to double check, I just looked this up in Neter (1996), where it says, "If it is desired to express the estimated regression function in the original units of $Y$, we simply take the antilog of $\hat Y'$... " (p. 132).
Comment: Please forgive me if I am being dense here. If I exponentiate your first equation, I get $Y=\exp \{\beta_0+\beta_1 X\}\cdot exp\{\varepsilon\}.$ Taking the expectation in the homoskedastic case, I get $E[Y \vert X]=\exp \{\beta_0+\beta_1 X\} \cdot E[exp\{\varepsilon\}].$ Doesn't the antilog of $\hat Y$ ignore the second term?
Comment: I'm sure it's me who's being dense here, @DimitriyV.Masterov (& it wouldn't be the first time... ). Setting aside whether $y_i$ has been transformed, we calculate $\hat y_i$ as $\beta_0+\beta_1x_i$; that is, we set $\varepsilon=0$, b/c $E[\varepsilon]=0$. Now $\exp(0)=1$, so we can multiply the first part, $\exp\{\beta_0+\beta_1X\}$ by 1, if you'd like. Of course, it won't change anything. So (w/ apologies), I still don't understand what you're getting at.

Analysing transformed data


Roots of $(z^2-z)^4=81$ in polar form

Question: Question :
Find the roots of $(z^2-z)^4=81$ in polar form.
What i've done :
I'm thinking about using De Moivre's Theorem.
Let $w=z^2-z \Rightarrow w^4=81$
$\begin{align}
&\Leftrightarrow w^4=3^4\,\text{cis $2\pi$}\\
&\Leftrightarrow w=3\,\text{cis $\left(\dfrac{2\pi+2k\pi}{4}\right)$}\\
&k=0,1,2,3
\end{align}$
What's next? I'm confusing to substitute $w=z^2-z$ back...
Please help me. Thanks
Comment: You could use $z^2-z=(z-\frac12)^2-\frac14$.
Comment: Is it completing the square?
Comment: And apply the de moivre's once again?
Comment: Yes, that's how to proceed.
Answer: I like your idea that first, you denote $$w=z^2-z.$$
Then, recall that in polar form, you have
$$c = r e^{i \theta}  ,$$
where $c \in \mathbb{C}$ is any complex number, $r \in \mathbb{R}$ is its distance from the origin, and $\theta \in [0,2\pi)$ is its phase.
So now, you can first find the first root, i.e. $w_1$, in a "regular way":
$$w_1 = \sqrt[4]{81} = 3.$$
Note that this is the root located on $x$ axis, so its angle $\theta$ in polar form is $0$, which is why $w_1 = r e^{i \theta} $ lets you determine the $r$ distance (since $e^{i \cdot 0} = 1$). Thus you have that $r=3$
Next, since you know that you are taking the fourth root, by the fundamental theorem of algebra, you know that you must have $4$ roots. Then, taking a shortcut, we have $\Delta \theta = 2 \pi /4 = \pi/2$. (Or you can also write it in a more formal way with De Moivre's theorem in polar form.) Then, your other three roots would be:
$$w_2 = re^{i \pi/2}=3 e^{i \pi/2} = ...$$
$$w_3 = re^{i 2\pi/2}=3 e^{i 2\pi/2} = ...$$
$$w_4 = re^{i 3\pi/2}=3 e^{i 3\pi/2} = ...$$
Compute these answers; for each of the cases then substitute into $ z^2-z -w=0$ and proceed to computing $z$ for each case (with the computation of the determinant and using De Moivre or the shortcut described above).
Comment: That is correct, 8 roots; however, they are not necessarily distinct according to the fundamental theorem of algebra (I would expect it to be 8 distinct but would be better to numerically check probably).
Comment: Ok, i kind of understand, will it gives me $8$ roots in total? Cz when we expand the $z$ it has $8$ orders?

Roots of $(z^2-z)^4=81$ in polar form


If $f$ is twice differentiable at $a$, prove $f''(a) vw= \lim_{k \rightarrow \infty} \frac{f(a+t_k(v_k+w_k))-f(a+t_kv_k)-f(a+t_kw_k)+f(a)}{t_k^2}$

Question:
Let $f: U \subset \mathbb{R}^m \rightarrow \mathbb{R}^n$ twice differentiable at the point $a \in U$.  suppose that $\lim_{k \rightarrow \infty} t_k=0$ in $\mathbb{R}$ and that  $\lim_{k \rightarrow \infty} v_k=v$;  $\lim_{k \rightarrow \infty} w_k=w$ prove that
$$f''(a) vw= \lim_{k \rightarrow \infty} \frac{f(a+t_k(v_k+w_k))-f(a+t_kv_k)-f(a+t_kw_k)+f(a)}{t_k^2}$$

We know that since $f$ is differentiable there is a linear transformation $$T_a: \mathbb{R}^m \rightarrow \mathbb{R }^n$$ such that
$f(a+h)-f(a)=T_a h + r(h)$ where $\lim_{h \rightarrow \infty} \frac{\|r(h)\|}{\|h\|}=0$, I don't know how to proceed, any idea please.
Comment: Note that you need to use of definition of differentiable function in $(f')$.
Answer: Taylor gives
$f(x+h) =f(x) + f'(x)h + {1 \over 2} h^T f''(x)h + r(h)$, where
$\lim_{h \to 0} {r(h) \over \|h\|^2} = 0$.
Then
$f(a+t_k(v_k+w_k)) = f(a) + f'(a) t_k(v_k+w_k) +{1 \over 2} t_k^2 (v_k+w_k)^T f''(x) (v_k+w_k) + r(t_k(v_k+w_k)) $
$f(a+t_k v_k ) = f(a) + f'(a) t_k v_k +{1 \over 2} t_k^2 v_k^T f''(x) v_k + r(t_k v_k) $
$f(a+t_k w_k ) = f(a) + f'(a) t_k w_k +{1 \over 2} t_k^2 w_k^T f''(x) w_k + r(t_k w_k) $
and so
${f(a+t_k(v_k+w_k)) - f(a+t_k v_k ) - f(a+t_k w_k ) + f(a) \over t_k^2 } = v_k^T f''(a) w_k + { r(t_k(v_k+w_k)) - r(t_k v_k) - r(t_k w_k) \over t_k^2}$, and taking
limits gives $v^T f''(a)w$.


Command "cim" is not defined

Question: I'm getting the following error while running drush cim on a new environment to import the configurations as they exist in the repo:
Command "cim" is not defined
also:
Command "config:import" is not defined
Command "config:export" is not defined
Command "config:cex" is not defined
In trying to search for help online, nearly all of the results include the string "Drush was unable to query the database", which is NOT in my error, and I'm perplexed as to why I'm not getting better results and starting this post in the meantime.
Answer: Although this post shows the exact same error, it was for a different purpose, but it reminded me to add the debug flag to the command, making drush cim --debug. This showed a stack trace that included The config sync directory is not defined in $settings["config_sync_directory"]. Which is weird, because it is defined, except for a typo in the string! Fixing that typo made everything work as normal, but the error was so misleading that I'm writing it up for anyone else in the same predicament.

Command "cim" is not defined


NodeJS: Have a setInterval loop only while another variable is true

Question: function setNormal() {
    console.log(1)
}

function setAlert() {
    console.log(2)
}

function alertFunction() {
    alertVar = setInterval(alertFunc, 600);
}

function alertFunc() {
    setAlert()
    setTimeout(setNormal, 300)
}
alertFunction()
});

how do I make the function alertFunction() run only when (for example) var loop = 1 and then stop when var loop = 0?
(this is my first post to stackoverflow so sorry if I did this wrong)
Comment: I'd revisit your basic JavaScript book, and take a look at the `if` statement. To stop an interval, do a Google for "clear javascript interval".
Answer: use setTimeout with a condition.

var x = 1;

setTimeout(function foo(){
  // this is a named function expression, foo name only exists inside itself
  if(x!==0){
     // do some code
     console.log("Hello");
     setTimeout(foo,1000);
  }
},1000);

setTimeout(function(){
   // change x after 3 seconds
   x = 0;
},3000);

You can also use clear interval to do the same thing

var x = 1;

var interval = setInterval(function (){
  if(x!==0){
     // do some code
     console.log("Hello");
  }else{
     clearInterval(interval)
  }
},1000);

setTimeout(function(){
   // change x after 3 seconds
   x = 0;
},3000);
Answer: Use Like It:-
var alertVar;
function alertFunction() {
    alertVar = setInterval(alertFunc, 600);
}
function myStopFunction() {
    clearInterval(alertVar);
}
if(lool=1){
   alertFunction();
}
if(lool=0){
   myStopFunction();
}


How do I jump to code lines in IntelliJ through code commands

Question: I'm developing a plugin for IntelliJ IDEA.
Say I'm creating a GUI in my plugin in which I have a button.
On a click I want the editor to jump to a certain file and line in it.
Is it possible? what do I write in the button listener?
My GUI is written with swing if it matters.
Answer: You can create an OpenFileDescriptor with the desired file and location inside it, and then call navigate on it.


Equicontinuous family composed with a continuous function

Question: I have an equicontinuous family of functions $\mathcal{F}$, each $f:X\rightarrow X$ in the family is a function on a compact metric space $(X,d)$. I also have another continuous function $g:X \rightarrow \mathbb{R}$. I can use the composition $g\circ f$ to form a new family of functions $\mathcal{G} = \{g\circ f: f \in \mathcal{F}\}$, I wish to show that this new family is also equicontinuous.
My approach is as follows

$\mathcal{F}$ has a $\delta$ satisfying the definition of continuity for all $f \in\mathcal{F}$ (Since $\mathcal{F}$ is equicontinuous).
$g$ has a $\delta^{\prime}$ satisfying the definition of continuity.
Use these facts to show that there exists some combination of the deltas above which gives us equicontinuity on $\mathcal{G}$.

However, I am stuck on the third step, in particular, the details of the combination of the deltas which allows us to form the equicontinuity of the composition.
Thanks
Answer: For $X$ compact metric, the equicontinuity condition is "uniform" (see my remarks on EQ1 and EQ2 in my note here, if necessary), so
$$\forall \varepsilon>0 : \exists \delta>0: \forall f \in \mathcal{F}: \forall x,x' \in X: d(x,x') < \delta \implies d(f(x), f(x')) < \varepsilon$$
And your $g: X \to \mathbb{R}$ is uniformly continuous, as $X$ is compact, so
$$\forall \varepsilon > 0: \exists \delta>0: \forall x,x' < \delta : d(x,x') < \delta \implies |g(x)- g(x')| < \varepsilon$$
So start with $\varepsilon$, get $\delta$ from the second, and apply that $\delta$ as the $\varepsilon$ for the equicontinuiy I gave. Done.
Comment: Im not following your explanation at the bottom, start with which $\epsilon$? and $\delta$ from the second argument?
Answer: For $\epsilon > 0$, we let $\delta_f(\epsilon) > 0$ be defined such that $d(x_1, x_2) < \delta_f(\epsilon)$ implies $d(f(x_1), f(x_2)) < \epsilon$ for all $f\in \mathcal{F}$ and $\delta_g(\epsilon) > 0$ be defined such that $d(x_1, x_2) < \delta_g(\epsilon)$ implies $\lvert g(x_1)-g(x_2)\rvert < \epsilon$. Then, for $\epsilon > 0$, if $d(x_1, x_2) < \delta_f(\delta_g(\epsilon))$, we have that $d(f(x_1), f(x_2)) < \delta_g(\epsilon)$, or $\lvert g(f(x_1))-g(f(x_2))\rvert < \epsilon$ for all $f\in \mathcal{F}$.


How to delete values from array by using mask?

Question: Subj. For example:
array = ['value1', 'value2', 'value3', 'value4', ...(here is many values like value5, value6, value7, value49 etc.)..., 'value50' 'something', 'something2']

I should delete value* from this array. How can I do this?
Comment: What do you mean by `value*` ? please post a *real* example with expected output, what have you tried and where did you get stuck
Answer: Using list comprehension, filter out values starts with value:
>>> array = ['value1', 'value2', 'value3', 'value4', 'value50', 'something', 'something2']
>>> array = [x for x in array if not x.startswith('value')]  # NOTE: used `not`
>>> array
['something', 'something2']

Answer: making simple things complex here is my code :)
from itertools import ifilterfalse
ifilterfalse(lambda x:x.startswith('value'),array)

note if there are integer values in list you will get
AttributeError: 'int' object has no attribute 'startswith'
so to handle integer also in your list 'array' we will use this simple loop:
res = []
for ele in array:
if type(ele) is int:
    res.append(ele)
elif not ele.startswith('value'):
    res.append(ele)