Erro url $feed->id

Question: Olá, estou trabalhando em um sistema com esquema de feed. Ao clicar em "Editar" aparece o seguinte erro:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input
  syntax for integer: "$feed->id" (SQL: select * from "feeds" where
  "feeds"."id" = $feed->id limit 1)

Percebi que na URL onde era para ter algo como:
http://localhost:8000/feed/2/update

ele aparece como:
http://localhost:8000/feed/$feed->id/update

Como resolver isso? Espero que tenha deixado claro minha dúvida. Agradeço desde já.
Códigos:
home.blade.php  (home)
@extends('layouts.app')

@section('content')

   @forelse($feeds as $feed)

{{$feed->title}}

{{$feed->description}}

      Publicado por: {{$feed->user->name}}
      id/update')}}">Editar

   @empty

Nenhum chamado cadastrado!

   @endforelse

@endsection

web.php (rotas)
<?php
Route::get('/', function () {
return view('auth/login');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('feed/{id}/update', 'HomeController@update');

HomeController.php (controller)
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\feed;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(feed $feed)
    {
        //$feeds = $feed->all();
        $feeds = $feed->where('user_id', auth()->user()->id)->get();

        return view('home', compact('feeds'));
    }

    public function update($idFeed)
    {
        $feed = feed::find($idFeed);

        return view('feed-update', compact('feed'));
    }
}

feed-update.blade.php (view da feed)
@extends('layouts.app')

@section('content')

{{$feed->title}}

{{$feed->description}}

    Publicado por: {{$feed->user->name}}

@endsection

Comment: O problema está em `{{url('/feed/$feed->id/update')}}`. Utilize `{{url('/feed/'.$feed->id.'/update')}}` ou `{{url("/feed/{$feed->id}/update")}}`
Comment: Se possível poste seu código.
Comment: certo, são 3 arquivos do laravel, um momento.
Comment: Precisa só a linha que você define a URL. Provavelmente você gerou uma *string* mal formatada.
Comment: Ao meu ver está tudo certo, mas sou apenas iniciante então...
Comment: Funcionou, muito obrigado.
Comment: Ao ROBERTO DE CAMPOS que está editando minha pergunta, retirando os argumentos de educação, respeito em primeiro lugar, e em segundo lugar, a proxima vez que for editar uma pergunda, adicione argumentos que sejam importantes.
Comment: @João.Mistura Esse é um entendimento da comunidade. https://pt.meta.stackoverflow.com/a/851/99718
Comment: Ok, não sabia vlw
Answer: Acredito que o problema esteja neste trecho id/update')}}">Editar do arquivo home.blade.php onde $feed->id está dentro de aspas simples. Tente da seguinte maneira:
id .'/update')}}">Editar

Ou também:
id ))}}">Editar

Comment: Já funcionou, mas obrigado igual :)
Comment: funcionou com {{url('/feed/{$feed->id}/update')}}

Erro url $feed->id


"no line items found" in user order

Question: I have installed Drupal Commerce (7.x.1.8 version) but in user orders section when I select an order only price and total is shown. In despite of order details the message "no line items found" appears. What can I do on here to show order datails?
Answer: I found a solution that worked for me via this article.
The author propose to change the Commerce view settings.
Answer: This is a common problem for anonymous users depending on the permission configuration you might have, the usual solution is to disable the SQL query rewriting for the affected view.
Check out these related issues in drupal.org

https://drupal.org/node/1811972
https://drupal.org/node/1276450
https://drupal.org/node/1303194
Answer: 'Disable SQL rewriting' in the affected view:

Edit the view: in 'Advanced' select 'Query settings'

Select 'Disable SQL rewriting'

"no line items found" in user order


Desenvolver aplicativos para iOS utilizando Java

Question: Estou desenvolvendo meu TCC e ele se baseia no conceito multiplataforma do Java. Porém agora esbarrei em um problema o XCode IDE da Apple não compreende os pacotes Java.
Existe alguma ferramenta ou extensão que me permita desenvolver minha aplicação para iOS em Java?
Comment: até onde sei no XCode se usa Objective C apenas
Comment: O contrário disso (**Objective-C** para **Java/Android**) pode ser feito através dessa ferramenta [apportable](http://www.apportable.com/), que por enquanto trabalha bem com games.
Comment: Desenvolva seu aplicativo codificando-o em Java para android no Eclipse e... ...utilize o plugin para eclipse http://gluonhq.com/the-new-gluon-plugin-for-eclipse/ para gerar seu aplicativo para o S.O. iOS utilizado nos iPhones a partir do mesmo código Java!
Answer: Se você quer desenvolver para OSX, que é o sistema do Mac, pode usar IDEs como Eclipse, Netbeans ou IntelliJ Idea.
Já o iOS é o sistema do iPhone/iPad e seus aplicativos são desenvolvidos nativamente na linguagem Objective-C, que é uma extensão do C.
Não creio que o iOS suporte programação em Java (pode até existir algum framework para isso, já que para Android é possível "programar" em Delphi ou C# usando frameworks de terceiros (com Delphi XE6 e Xamarin, respectivamente). Falo "programar" entre aspas porque nem todas as funcionalidades podem ser suportadas - para explorar todas as potencialidades de uma plataforma, você tem que programar usando a linguagem e bibliotecas que oferecem essas funcionalidades nativamente).
Mas mesmo que exista uma forma de programar usando Java, não será um exemplo do conceito de multiplataforma do Java como você quer, porque Delphi por exemplo não é multiplataforma e nem roda em dispositivos móveis, mas ainda assim é possível "programar" para Android (e para iOS) usando Delphi (o aplicativo gerado não é compilado em Delphi e sim na linguagem nativa da plataforma móvel; o Delphi foi usado apenas para gerar uma representação intermediária do código).
Se você quer representar o conceito de multiplataforma para dispositivos móveis, isso será melhor representado pelo uso de HTML/CSS/Javascript e alguma biblioteca do tipo PhoneGap, Titanium, etc., que irão fazer seu código rodar praticamente sem modificações (mas com algumas limitações) em vários sistemas móveis, como Android, iOS, Windows Phone, BlackBerry, Firefox OS, etc.
O comportamento multiplataforma do Java não é bem representado nos dispositivos móveis exceto pelo Android, esse comportamento tem sido voltado mais para permitir o "write once, run anywhere" em sistemas desktop e servidores.
Answer: Aos olhos da Apple, você só consegue utilizar mesmo o Xcode em seu Mac, desenvolvendo com Objective-C ou Swift. Digo isso porque outra forma que não seja esta, de certa forma vai contra os princípios da empresa.
Você consegue encontrar outras formas, utilizando HTML 5, JavaScript e CSS com PhoneGap e gerar um aplicativo híbrido para iOS, ou utilizando C# com o Xamarin e até mesmo para o seu caso, o RoboVM com Java.
Mas como eu disse, são opções que não são reconhecidas pela Apple, e dependendo do seu objetivo ou para fins de publicação na própria App Store, seu aplicativo pode ser rejeitado. Mas cada caso é um caso, não posso afirmar com 100% de certeza.
Comment: Empresa com princípios complicados, né?
Answer: Não é possível desenvolver aplicativos para iOS utilizando Java, a linguagem de programação oficial para desenvolver para iOS é Objective-C. Criada pela Apple.
Se você quer usar Java aconselho desenvolver para Android.
Answer: Neste Link existe referencia a um plugin chamdo CodeName One gratuito e open-source para eclipse ou NetBeans que permite desenvolver em java para iOS
No site deles existem varios cases de aplicativos para diversas plataformas além do iOS, mas, não esquecendo do que foi dito pelo @Piovezan é um fato. Nem todas as funcionalidades da linguagem padrão podem estar disponível e o resultado pode não ser tão performático quanto o o código nativo.
Comment: Sim. Mas mesmo que não fossem necessários ajustes, o que quis dizer é que os diversos dispositivos móveis disponíveis comercialmente não rodam aplicativos em uma JVM (à exceção das antigas apps J2ME e da DVM, que é a JVM modificada do Android) e que portanto não reproduzem o comportamento multiplataforma do Java como no caso por exemplo das principais plataformas desktop. Comentei isso tendo em mente a proposta de TCC do OP.
Comment: Um comentário feito no link citado também fala do [PlayN](http://code.google.com/p/playn/), que parece interessante. Mas infelizmente nenhuma dessa soluções representa "o conceito multiplataforma do Java", como quer o OP.
Comment: @Piovezan aparentemente o CodenameOne promete aproveitar o código em todas as plataformas q ele suporta, mas como vão ser vários tipos de dispositivos, será necessário ajustes, o q já é necessário para se fazer uma app para um desktop, web e android.
Comment: Realmente @Piovezan. Concordo com você, não tinha pensado por este lado. Obrigado pelo ponto de vista.


how to fix: FATAL EXCEPTION:main android.os.NetworkOnMainThreadException

Question: i am having probelms running my code on android version 18. i have used the AsyncTask but still getting an error, plz help. I am a noob to programming so please excuse my errors
package com.example.androidhive;

import java.util.ArrayList;

import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class EditProductActivity extends Activity {

    EditText txtName;
    EditText txtPrice;
    EditText txtDesc;
    EditText txtCreatedAt;
    Button btnSave;
    Button btnDelete;

    String pid;

    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();

    // single product url
    private static final String url_product_detials = "http://10.0.2.2/android_connect/get_product_details.php";

    // url to update product
    private static final String url_update_product = "http://10.0.2.2/android_connect/update_product.php";

    // url to delete product
    private static final String url_delete_product = "http://10.0.2.2/android_connect/delete_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCT = "product";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
    private static final String TAG_PRICE = "price";
    private static final String TAG_DESCRIPTION = "description";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_product);

        // save button
        btnSave = (Button) findViewById(R.id.btnSave);
        btnDelete = (Button) findViewById(R.id.btnDelete);

        // getting product details from intent
        Intent i = getIntent();

        // getting product id (pid) from intent
        pid = i.getStringExtra(TAG_PID);

        // Getting complete product details in background thread
        new GetProductDetails().execute();

        // save button click event
        btnSave.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // starting background task to update product
                new SaveProductDetails().execute();
            }
        });

        // Delete button click event
        btnDelete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // deleting product in background thread
                new DeleteProduct().execute();
            }
        });

    }

    /**
     * Background Async Task to Get complete product details
     * */
    class GetProductDetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditProductActivity.this);
            pDialog.setMessage("Loading product details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Getting product details in background thread
         * */
        protected String doInBackground(String... params) {

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Check for success tag
                    int success;
                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("pid", pid));

                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(
                                url_product_detials, "GET", params);

                        // check your log for json response
                        Log.d("Single Product Details", json.toString());

                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // successfully received product details
                            JSONArray productObj = json
                                    .getJSONArray(TAG_PRODUCT); // JSON Array

                            // get first product object from JSON Array
                            JSONObject product = productObj.getJSONObject(0);
                            setContentView(R.layout.edit_product);

                            // product with this pid found
                            // Edit Text
                            txtName = (EditText) findViewById(R.id.inputName);
                            txtPrice = (EditText) findViewById(R.id.inputPrice);
                            txtDesc = (EditText) findViewById(R.id.inputDesc);

                            // display product data in EditText
                            txtName.setText(product.getString(TAG_NAME));
                            txtPrice.setText(product.getString(TAG_PRICE));
                            txtDesc.setText(product.getString(TAG_DESCRIPTION));

                        }else{
                            // product with pid not found
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }

    /**
     * Background Async Task to  Save product Details
     * */
    class SaveProductDetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditProductActivity.this);
            pDialog.setMessage("Saving product ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Saving product
         * */
        protected String doInBackground(String... args) {

            // getting updated data from EditTexts
            String name = txtName.getText().toString();
            String price = txtPrice.getText().toString();
            String description = txtDesc.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(TAG_PID, pid));
            params.add(new BasicNameValuePair(TAG_NAME, name));
            params.add(new BasicNameValuePair(TAG_PRICE, price));
            params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));

            // sending modified data through http request
            // Notice that update product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_update_product,
                    "POST", params);

            // check json success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully updated
                    Intent i = getIntent();
                    // send result code 100 to notify about product update
                    setResult(100, i);
                    finish();
                } else {
                    // failed to update product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product updated
            pDialog.dismiss();
        }
    }

    /*****************************************************************
     * Background Async Task to Delete Product
     * */
    class DeleteProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditProductActivity.this);
            pDialog.setMessage("Deleting Product...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Deleting product
         * */
        protected String doInBackground(String... args) {

            // Check for success tag
            int success;
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("pid", pid));

                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(
                        url_delete_product, "POST", params);

                // check your log for json response
                Log.d("Delete Product", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    // product successfully deleted
                    // notify previous activity by sending code 100
                    Intent i = getIntent();
                    // send result code 100 to notify about product      deletion
                    setResult(100, i);
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();

        }

    }
    }

the error i am getting is:
10-27 17:01:52.858: E/AndroidRuntime(2001): FATAL EXCEPTION: main
10-27 17:01:52.858: E/AndroidRuntime(2001): android.os.NetworkOnMainThreadException
10-27 17:01:52.858: E/AndroidRuntime(2001):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at libcore.io.IoBridge.connect(IoBridge.java:112)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at java.net.Socket.connect(Socket.java:842)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at com.example.androidhive.JSONParser.makeHttpRequest(JSONParser.java:62)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at com.example.androidhive.EditProductActivity$GetProductDetails$1.run(EditProductActivity.java:137)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at android.os.Handler.handleCallback(Handler.java:730)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at android.os.Handler.dispatchMessage(Handler.java:92)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at android.os.Looper.loop(Looper.java:137)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at android.app.ActivityThread.main(ActivityThread.java:5103)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at java.lang.reflect.Method.invokeNative(Native Method)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at java.lang.reflect.Method.invoke(Method.java:525)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-27 17:01:52.858: E/AndroidRuntime(2001):     at dalvik.system.NativeStart.main(Native Method)

and the layout xml layout looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:text="@string/Product_Name2"
        android:textSize="17sp" />

    <EditText android:id="@+id/inputName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/inputName2"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:singleLine="true"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:text="@string/Price2"
        android:textSize="17sp" />

    <EditText android:id="@+id/inputPrice"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:singleLine="true"
        android:inputType="numberDecimal"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:text="@string/Description2"
        android:textSize="17sp" />

    <EditText android:id="@+id/inputDesc"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/inputDesc2"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:lines="4"
        android:gravity="top"/>

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    <Button
        android:id="@+id/btnSave"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/Save_Changes" />

    <Button
        android:id="@+id/btnDelete"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/Delete" />

    </LinearLayout>

</LinearLayout>

Comment: Here's a tutorial to fix most common exceptions - http://bit.ly/1gTomGJ
Answer: In the GetProductDetails class use only try catch. remove the runOnUiThread() .
Answer: On doInBackground method you must keep the HTTP request in the background task and just put the UI update on runOnUiThread. Here is the 'quick' fix:
/**
 * Getting product details in background thread
 * */
protected String doInBackground(String... params) {

    // Check for success tag
    int success;
    try {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("pid", pid));

        // getting product details by making HTTP request
        // Note that product details url will use GET request
        JSONObject json = jsonParser.makeHttpRequest(
                url_product_detials, "GET", params);

        // check your log for json response
        Log.d("Single Product Details", json.toString());

        // json success tag
        success = json.getInt(TAG_SUCCESS);
        if (success == 1) {
            // successfully received product details
            JSONArray productObj = json
                    .getJSONArray(TAG_PRODUCT); // JSON Array

            // get first product object from JSON Array
            final JSONObject product = productObj.getJSONObject(0);

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    setContentView(R.layout.edit_product);

                    // product with this pid found
                    // Edit Text
                    txtName = (EditText) findViewById(R.id.inputName);
                    txtPrice = (EditText) findViewById(R.id.inputPrice);
                    txtDesc = (EditText) findViewById(R.id.inputDesc);

                    // display product data in EditText
                    txtName.setText(product.getString(TAG_NAME));
                    txtPrice.setText(product.getString(TAG_PRICE));
                    txtDesc.setText(product.getString(TAG_DESCRIPTION));
                }
            });

        }else{
            // product with pid not found
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}

The recommended solution is change the doInBackground method to return the request result and update the UI at onPostExecute like this:
/**
 * Background Async Task to Get complete product details
 * */
class GetProductDetails extends AsyncTask<String, String, JSONObject> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditProductActivity.this);
        pDialog.setMessage("Loading product details. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Getting product details in background thread
     * */
    protected JSONObject doInBackground(String... params) {

        JSONObject product = null;
        // Check for success tag
        int success;
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("pid", pid));

            // getting product details by making HTTP request
            // Note that product details url will use GET request
            JSONObject json = jsonParser.makeHttpRequest(
                    url_product_detials, "GET", params);

            // check your log for json response
            Log.d("Single Product Details", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // successfully received product details
                JSONArray productObj = json
                        .getJSONArray(TAG_PRODUCT); // JSON Array

                // get first product object from JSON Array
                product = productObj.getJSONObject(0);
            }else{
                // product with pid not found
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return product;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(JSONObject product) {
        if (product != null) {
            setContentView(R.layout.edit_product);

            // product with this pid found
            // Edit Text
            txtName = (EditText) findViewById(R.id.inputName);
            txtPrice = (EditText) findViewById(R.id.inputPrice);
            txtDesc = (EditText) findViewById(R.id.inputDesc);

            // display product data in EditText
            txtName.setText(product.getString(TAG_NAME));
            txtPrice.setText(product.getString(TAG_PRICE));
            txtDesc.setText(product.getString(TAG_DESCRIPTION));

        }
        // dismiss the dialog once got all details
        pDialog.dismiss();
    }
}


Horizontally align DIV elements while keeping them vertical on smaller screens

Question: Would like to horizontally align the DIV elements (create-your-own) on larger screens while keeping it vertical on smaller screens. Was able to complete them separately but cant get it to work together
Link to my test codepen div element: https://codepen.io/Newbie1122/pen/jOqwVdP

Example example Example example Example example

Example example Example example Example example Example example

Tip 1

Example example Example example Example example Example example Example example Example example Example example Example example Example example

Tip 2

Example example Example example Example example Example example Example example

.create-your-own-div {
  background-color: #fbe9e9;
}

.create-your-own-wrapper{
}

.create-your-own{

}

.create-your-own-layout-pink-h3 {
  font-size: 1rem;
  color: #c3015c !important;
  font-weight: bold;
  letter-spacing: .05em;
  text-transform: uppercase;
  margin-top: 25px !important;
  margin-bottom: 0 !important;
}

.create-your-own-layout-h5 {
  color: #494949  !important;
  font-weight: bold;
  letter-spacing: .05em;
  text-transform: uppercase;
  margin-bottom: 0 !important;
}

.create-your-own-tip-h5{
  font-size: 1rem;
  color: #c3015c !important;
  font-weight: bold;
  letter-spacing: .05em;
}

.create-your-own-tip-p{
  color: #494949 !important;
}

Comment: what do you mean by *Was able to complete them separately but cant get it to work together* ? - Also what are smaller screens - mobiles, tablet what are those ?
Comment: You question is not clear! Can you add images for desired output?
Comment: @AlwaysHelping, I had extra code, I seperated the wrapper div in half, I had 2 extra divs one for the left side and one for the right, right side is what you see now essentially text, the left side was pictures. forgot what  I had but when I saw it on my test, I saw it was horizontal on pc, liked it alot so decided to delete the 50/50 split, make it just text, showing horizontal on larger screens, but now cant replicate it.
Comment: @PranavRustagi https://ibb.co/djngMvR
Comment: If you had it working separately, then just use [media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries) to use the code at whatever breakpoint you want
Answer: You can use display: flex on the wrapper and then flex-direction: row to lay the divs horizontally. And, then, use a mediaquery with flex-direction: column to display them vertically on small screens. To do that you have to replace your .create-your-own-wrapper style with the one below. Also, you can see a demo of it working here.
.create-your-own-wrapper{
  display: flex;
  flex-direction: row;
}

@media screen and (max-width: 800px) {
  .create-your-own-wrapper {
    flex-direction: column;
  }
}


Jenkins Pipeline Interdependent Parameters

Question: I'm fairly new to Jenkins Pipeline (and Groovy), and am wondering if it's possible to define parameters in a way that one depends on another based on the selected value. For example let's say I have two choice parameters, A and B, and I want choices in B to be populated based on the [dynamically] selected value of A. Is that possible? Something like this:
pipeline {
    agent { label 'my-agent' }

    parameters {
        choice(name: 'DataCenter', choices:'Foo\nBar')
        choice(name: 'AvailabilityZone', choices: if(DataCenter.equals("Foo") {return 'A\nB'} else {return 'C\nD'}))
    }

    stages {
    ...
    }
}

Obviously this doesn't work. Is there way to support this out of the box? Otherwise is there a way to, let's say, bind a callback event to the DataCenter choice dropdown and manually change the values of AvailabilityZone?
Answer: I had the same need in the past and solved it using the Active Choices Plugin.
Unfortunately, this plugin was recently blacklisted due to a security issue in one of its dependencies.
If security is not a major concern, you can still install the plugin manually.
Comment: This plugin doesn't support Jenkins Pipeline.
Comment: It does support the now-called "scripted" pipelines (this plugin works with 4 pipeline jobs in my environment). Looking at your code again, I now understand you're working with "declarative" pipelines, which will probably not work with such plugins.


Show combinatorially that $S$ freely generates $\langle S\rangle$

Question: Let $S = \{b^nab^{-n}: n\in\mathbb{N}\}$, $S$ freely generates $\langle S\rangle$.
The definition I have of freely generates is: $F$ is freely generated by a subset $S\subset F$ if for any group $\Gamma$ and any map $\phi:S\to \Gamma$ we can uniquely extend this to a homomorphism $\varphi:F\to S$.
I think this is essentially trivial but I'm not too comfortable with using this definition yet so would like to check. If $\phi(b^nab^{-n}) = g_n\in\Gamma$ I would just extend this multiplicatively to a homomorphism on $\langle S\rangle$ and then conclude immediately. I don't really see that there's anything at all that needs to be done here?
I'm sure I'm over simplifying it so any pointers would be excellent!
Comment: I really don't know what exactly "prove combinatorially" could mean here, though all this stuff is dealt with in Combinatorial Group Theory. Perhaps you mean that we would have to show that any (normally) reduced  word in the $\;b^nab^{-n}\,'$s isn't the trivial element unless we have the word of length zero...?
Comment: If you don't see that there's anything at all that needs to be done, check if your method would also suggest that $S$ freely generates $\langle S\rangle$ if $S=\{\,a^n:n\in\Bbb N\,\}$.
Comment: Well, the last part of the original question, which you didn't write in your original post, perhaps clears this up (at least a little, I believe): if you show that for any $\;n\in\Bbb N\,,\,\,\left\{b^kab^{-k}\right\}_{k=1}^n\;$ are *free* generators, then clearly $\;S\;$ isn't f.g., and maybe they do mean what I wrote in my past comment...
Comment: @user291678 Well, yes. Still though, it should be proved that those are **actually** free generators, meaning: no non-empty word in those letter can be the trivial element of the group. Take as a lame instance the generators $\;\{a, b^{-1}, ba^{-1}\}\;$ . These three elements undoubtedly generate a (free, of course) subgroup of the free group $\;F(a,b)\;$ , but those three generators are **not free ones** since, for example with the reduced word $\;w(x,y,z):=xyz\;$ , we get $\;w(a,b^{-1},ba^{-1})=ab^{-1}ba^{-1}=1\;$ ...
Comment: @DonAntonio Yeah this is also what's thrown me, I think it may have been said so that no topological arguments were used - e.g. looking at the fundamental group of the Cayley graph or something.

The question verbatim is: "Show (combinatorially) that
$\langle S\rangle$ is freely generated by S. Deduce that $\langle S\rangle$ is not f.g."
Comment: @HagenvonEitzen ah yes of course, I've edited the original post now.
Comment: @HagenvonEitzen okay that actually helps a lot, so I'd need to in fact show that this map is firstly a well defined homomorphism and further show uniqueness?
Comment: @DonAntonio sorry for omitting this part of the question, I thought it would be a simple consequence so wasn't necessary to include. I guess showing what you said in your first post proves that the extension $\varphi$ is well defined and unique so the result follows?
Answer: Hint: "Prove combinatorially" or "show combinatorially" almost certainly means something like this.
Denote $c_n = b^n a b^{-n}$ and $C = \{c_n \,|\, n \in \mathbb{N}\}$.
Given a word $w$ in the elements of $C$, let $\bar w$ denote the element of the free group $\langle a,b \rangle$ obtained by multiplying out the letters of the word $w$. For example, if $w = c_1 c_2$ then $\bar w = (bab^{-1})(b^2ab^{-2}) = babab^{-2}$.
Prove that if $w$ is a nontrivial reduced word in the elements of $C$ then $\bar w$ is a nontrivial element of the group $\langle a,b \rangle$.


MySQL finding products viewed by others

Question: I have a table which contains products viewed by clients, it looks like this:
| id | visitor_id |  product  |

| 1  |   51a474f  |     5     |
| 2  |   51a474f  |     3     |
| 3  |   51a474f  |     3     |
| 4  |   207ed9e  |     3     |
| 4  |   207ed9e  |     5     |
| 5  |   47d98ee  |     4     |
| 6  |   47d98ee  |     3     |
| 7  |   47d98ee  |     2     |

And if someone visits e.g. product no. 5, I'd like to get all visitors who also visit the same product and then group all products (which id is other than 5) and count them by number of visits.
I know I could do this with multiple queries, but I think single query would be better than that solution.
Comment: do you have visitor ID and product ID on that page?
Comment: Here is a fiddle for your question: http://sqlfiddle.com/#!2/e34ff/1/0, the query is not a complete solution though ;)
Comment: ID is only row number and it's not relevant in this case :). Here's a list of what I'd do:

Example: I want to find products related to product no. 5

- get all visitor_id(s) who have seen product no. 5
- get all products and count them, seen by users above (except product no. 5)
- limit the query to let's say 10 results
Answer: From what I have understood from your question, here is my answer.I have not tested the data though.
select visitor_id,product, count(visitor_id)
from <your table>
where product=(select product from <your table> where id = (select max(id) from <your table>))
group by product

union

select visitor_id,product, count(visitor_id)
from <your table>
where product not in (select product from <your table> where id = (select max(id) from <your table>))

Answer: I assume you mean that you want all products (which id is other than 5) AND viewed by the visitors who viewed no. 5? You can try something like this: (just off the top of my head, not tested)
SELECT product, COUNT(id) num
FROM the_table
WHERE
    visitor_id IN  ( SELECT DISTINCT visitor_id FROM the_table WHERE product='5' AND visitor_id!='this_visitor_id' ) AND
    product != '5'
GROUP BY product
ORDER BY num DESC

MySQL finding products viewed by others


No source code is available for type org.springframework.security.core.GrantedAuthority

Question:
I have a legacy multi-module GWT project.
One of the modules contains the DTO and Enum classes.
One of the DTO classes extends the org.springframework.security.core.GrantedAuthority class, so in the pom.xml it has the maven spring-security-core dependency of org.springframework.security.
When I tried to run the package command, i got the message:

No source code is available for type
org.springframework.security.core.GrantedAuthority; did you forget to
inherit a required module?

I tried to apply solutions that were recommended in some posts that I found with similar messages, I even found one that related the same error, but none of those solutions worked for me.

Could you please help me figure out what is causing this error and how I could fix it?

To reproduce the issue you can follow the steps I did:

I used GWT Archetypes to create a basic project called GWTRPCModular; and:

JDK 17 (but also I tried it with 8)
Eclipse 2023-03
Apache Maven 3.8.6
GWT 2.10.0

The project was generated with 3 modules: GWTRPCModular-client, GWTRPCModular-server and GWTRPCModular-shared.

I added a module called GWTRPCModular-model for the DTOs (similar to my legacy project) and in the pom.xml I added the necessary dependencies.

I included the <source path="model" /> to the *.gwt.xml file.

I created the UserSessionDTO class

import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;

public class UserSessionDTO extends User {

    private static final long serialVersionUID = -6391317902265663080L;

    public UserSessionDTO(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
        // TODO Auto-generated constructor stub
    }
}

I ran the mvn clean install
Finally I ran the mvn package and the message appeared:

...
[INFO] --- gwt-maven-plugin:1.0.1:compile (default-compile) GWTRPCModular-client ---
[INFO] Compiling module com.foo.gwtmodular.App
[INFO]    Tracing compile failure path for type 'com.foo.gwtmodular.model.dto.UserSessionDTO'
[INFO]       [ERROR] Errors in 'com/foo/gwtmodular/model/dto/UserSessionDTO.java'
[INFO]          [ERROR] Line 8: No source code is available for type org.springframework.security.core.userdetails.User; did you forget to inherit a required module?
[INFO]          [ERROR] Line 12: No source code is available for type org.springframework.security.core.GrantedAuthority; did you forget to inherit a required module?
...

If you need anything else to review this case, please let me know.
I thank you in advance for any help you can provide!
Comment: If this spring library is being used in the client, the maven artifact for the spring library must include the source files (.java) so that GWT can compile the source.  Or if the source is in a separate artifact then that must be added as a dependency too.
Comment: Thanks, @RobertNewton, I really appreciate your response.

I added the "sources" as a dependency in the pom.xml of both client and model modules, but the error message still appears. Is there anything else I should add/modify?

`

org.springframework.security
spring-security-core
${spring-security-version}
sources

`
Answer: In your GWT (*.gwt.xml) module file, you need an <inherits> tag for this spring dependency also.
This spring library probably does not come with its own GWT module file though, so you will need to create your own.  In your client project you could create a package such as org.springframework.security, create a GWT module file for the spring library and put it in the package.  Then you can inherit it in your main GWT module file
Refer to this question/answer:
https://stackoverflow.com/a/70538165/1920835
Comment: I did what you recommended: I created the package _com.focussscm.gwtmodular.model_ in my client project and I created the Model.gwt.xml file; but, many more messages of the same type appeared for libraries that are somehow related to org.sprintframework.security.

Compiling module com.focussscm.gwtmodular.App
   Tracing compile failure path for type 'org.s...ion.SessionInformation'
     [ERROR] Errors in 'jar:file:/D:/.../s..re//spring-security-core-sources.jar!/..SessionInformation.java'
      [ERROR] Line 52: No source code is available for type org.springframework.util.Assert; did
Comment: what paths did you put in your   tags in the module file?
Comment: I just realized that I gave you the wrong path names _(sorry about that)_; actually the package was called _org.springframework.security_, the module file was called Security.gwt.xml and I used  in it.
Comment: So now I assume you are not getting "no source code" errors for classes in the org.springframework.security package (and it's subpackages)?
But you are getting those errors for classes in different packages?  If so, you will need to go though a similar procedure as before.
Also note that GWT doesn't emulate all classes in the JRE, so if spring is using certain classes that aren't emulated you could be in trouble:  https://www.gwtproject.org/doc/latest/DevGuideCodingBasicsCompatibility.html#runtime
Comment: Unfortunately, I'm still getting the "no source code" error for classes in org.springframework.security package, after following the steps you (and your refered question/answer) recommended.
Comment: And you are inheriting this Security gwt module in your main gwt module?  You could try the community on Gitter, they should have experience with what you are trying to do: https://gitter.im/gwtproject/gwt
Comment: Yes, I add the  to gwt module. I will try on Gitter as well, thanks!


When was the last time the Bills, Lions, Browns, & Jets won on the same day?

Question: On October 6, 2018, the Bills, Lions, Browns and Jets all won. When was the last time the Bills, Lions, Browns, & Jets won on the same day? Or even the same week?
Answer: Using Pro Football Reference's Team Game Finder with the query: "In a single game, in 2012, in the Regular Season, team won game, sorted by descending Date," the answer is October 14, 2012.

Jets over Colts 35-9 Box Score
Lions over Eagles 26-23 Box Score
Browns over Bengals 34-24 Box Score
Bills over Cardinals 19-16 Box Score
Comment: @PhilipKendall I elaborated how I got to my answer. [This answer](https://sports.stackexchange.com/a/20259) to a similar question gave me a starting point and I just went through the seasons from there.
Comment: While I'm in no way disputing this, could you add some details as to how you obtained this information?


How to make nice content manager approval page?

Question: The client wants to allow users to upload files but only publish the ones that are approved by the content managers. The content managers want a nice way to flip through pictures and quickly accept or reject pictures.
I created a view where someone can flip through unpublished pictures.
Is there a way to add a check box that corresponds to the the published checkbox in the add content? Basically be able to edit the content within this simple view, but all they would need to edit is published/unpublished.
Any Ideas. Hopefully there is a way to do this without another module, but I'm not picky at this point.
Answer: I guess Views Bulk Operations (VBO) may help you here. Here is a quote about it (from the module's project page):

... This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.


when you only sing in F#

Question: Tim Minchin sang this song:

It is called "when you only sing in F#". Apparently the song is really funny. If you know music. I do not know music, hence I am asking here: what is the joke?
He sings "I am playing in F major but I am singing in F#". First of all: is that true, does he really sing the entire song in F# while playing in F major?
And is that some hard thing to do? Or why is this funny?
I hope a kind soul will help me understand the fun.
Comment: I'm voting to close this question because I feel it's a better fit for MusicFans. However, there is a good case to be made that this belongs here, both as an analysis question and a performance question.
Comment: Really, six up votes for an off topic question?
Comment: I'm **triggered**  , because right now I'm working up my part (cello) for Franck's  Symphonic Variations (piano & orch), which **is** in F# .  It's tempting to tune all 4 strings a half-step high :-)
Comment: @CarlWitthoft - you mean there isn't a capo available for cellos (celli)??
Comment: @tim LOL sadly capos only adjust the open pitch as you know.  (We don't have frets so "just count a different fret number" doesn't work either)
Answer: The joke is that he sings in F#, even though it sounds bad, just because he prefers singing in F#.
He does not sing the whole song in F# while playing in F*.  That would be very difficult to do, but he does not do it.  He plays in F while singing in F, so it sounds good.  Until that F#... that's the punchline.  It sounds bad, and the audience laughs.
*Most of the song is actually in D minor, which shares all the same notes as F, but that's a technicality that doesn't really matter as far as the joke is concerned.
Comment: It's the way Les Dawson would play out of tune. Some notes were just a semitone out and that's more than enough. A party piece of mine is to play a piece where the l.h. plays in C#, while the r.h. is in C. Much easier than singing out of tune (for some...)
Comment: The joke goes beyond simply sounding bad. It's a spoof of musicians — particularly singers — who insist on playing or singing songs in a specific key, either because "they have the right emotion" or because it fits their voice/instrument better. I cannot tell you how many times I played in pit orchestras and had to transpose from G major to G flat to accommodate the singer. Or jam sessions where someone tried to show off by playing a well-known song in an obscure key.
Comment: Well yes, there is that, I don't think that's what really made the audience laugh though
Comment: There are a lot of people in that audience.
Comment: @Tim: Do you happen to have a recording of your C/C# piece?
Comment: @EricDuminil - no - it's a secret  - for now!
Comment: I have to dv. He doesn't sing *any* of the song**in** F#. He happens to sing a few *notes* **on** F#, that's all.
Comment: @Tim Ok, fair, a few F#s is not enough to establish a new key center, but at this point our analysis is separated from what made the joke funny in the first place.  I get that you don't find it funny, but lots of people do, and the question was "why is this funny?"
Comment: @Aaron   A shift from G to Gb may seem trivial and merely annoying to the musicians, but it can make a lot of difference when the song contains a 'money note' for the vocalist!
Answer: Ironically, he's not singing in F initially, nor F♯ when he sings that he is.
The song's far more in Dm, and the F♯ note he sings is actually the major 3rd of D - yes, it's an F♯,, but he's certainly not 'singing in F♯. Which limits the funniness of the piece, unfortunately.
EDIT: trying to find why musos may find this funny. There have been many occasions when I've encountered singers who've said 'I only sing in F♯ (or whatever key)'. Most musos will understand that it's actually a statement which doesn't hold water. For a couple of reasons.
Songs' range can vary depending far more on their highest and lowest notes, which are in fact independent to the key they're in.
Most folk have a range of more than an octave, whilst a lot of songs span only one. So changing key, up or down, will be possible for most singers - albeit a tone or two, so 'only in F♯' doesn't ring true.
Les Dawson (British comedian) was an accomplished pianist, but he usually incorporated in his act renditions of popular songs, which he expected the audience to join in with, but spectacularly made horrible mistakes with some notes - very cleverly worked out - while retaining his inimitable smile, as if there was nothing wrong. Now that was funny!
Tim has (probably) taken this and the first reason to write (?) and sing the song. But from maybe a slightly different viewpoint. He sings those F♯ notes against the F♮ played in the D minor chord, which is discordant. Had it been the other way round, it'd just sound Bluesy. Hence the reference to F♯. Musos would appreciate this, and lots would think it was actually difficult to do - it's not, but it's effective. But I still say it's a misnomer!
EXTRA EDIT: it'll probably resonate with some musos my experiences when a singer says 'I sing in x key'. You play a chord for that key, and they then proceed singing in a completely different one. Yes, sometimes F♯...
Comment: From the standpoint of what musicians find funny about music this is a total dud, I agree. He holds an F# note over a Dm chord. The rest of the time he is singing in D minor. At the very end he sings an F# over an F chord which is so sharp it is practically a G. It is further made un-funny by the fact that the entire piece is played with a orchestra, basically condoning all the inaccuracies. Sing an entire song in F# while playing in F and I will be rolling around on the floor laughing, not to mention incredibly impressed!
Comment: Yes, though it does need to be mentioned that Dm is the [relative minor](https://en.wikipedia.org/wiki/Relative_key) of F, which makes it close enough to being "in F". I reckon he tried various ways of implementing the whole idea, and found Dm to be the most practical and/or most jarring. It certainly makes it a bit easier to perform: just sing a Picardy third but stubbornly happer out the chords in minor against it.
Comment: He actually added a text note over the video on the first F♯ saying 'it's actually D min' It does close on F though.
Comment: This doesn't answer the question of why it's funny.
Comment: @leftaroundabout - yes, I'm happy with him 'being in F', but he's never 'in F#' - or its relative minor, for that matter. Singing in a key a semitone above what's being played is reserved for pub singers.
Comment: @TetsujinI missed that, although it's not unknown for songs to modulate between relatives - or in this case, maybe, parallels. Or both...
Comment: @Aaron - personally, I don't find it funny anyway. It's feeding false information, just sounds out of tune, and doesn't actually do what it says on the tin. Hence the use of 'ironically'. I'm sure not everyone laughs at it - same as not everyone laughs at some of my jokes. OP doesn't get it either, even though he 'sings out of tune'. How does one explain why a joke is funny? (Especially when one doesn't find it any more than pathetic). Your dv?
Comment: @JohnBelzaguy I did laugh when he did it but it's still ridiculous. I do not find it musical or entertaining though. Just kinda stupid that he would do it... but look what he does to his eyes. Anything to stand out. Not really that musical overall. Better piano playing than singing. Just kinda stupid stuff. Not sure why an orchestra would waste their time... and not like they added anything of value. Think about how many people there wasted their time... not just the audience but all the musicians, production team, etc. Hopefully there was more going on.
Comment: He is singing and F# over a Dm chord. This actually makes it a D chord and the F is then a #9(although given the context the #9 has been so emphasized as to make the F# sound like a dim4)... but his singing off key and badly doesn't help. If one is going to sing a dim4 it has to be done tonally at least. It's holding it out and that is obviously what makes it sound terrible and, of course, intentionally done... but stupid none the less. If someone wants to laugh at some stupid things go to a comedy show.

when you only sing in F#


Different favicon for local version of site?

Question: It's a small thing, but it would be nice if a site running locally could use a different version of a favicon, to make it easier to separate local and live sites visible in browser tabs.
I had in mind a really simple implementation, where a local favicon would just have "_local" appended to the name of the current theme favicon, so:
favicon.ico
favicon_local.ico

Then, if the site is running locally, and if a local version of the favicon exists, use it instead.
My question - what's the best way to implement this? Also, what would be a good way to check if a site is running locally?
Thanks for any ideas, code, or pointers.
Answer: Do you use any versioning like Git? If so, you can just upload the real favicon to your live site, then change the favicon locally and add it to your .gitignore afterwards.
Comment: I'm not actually using git for this site. But I should be. Thanks for an interesting approach.
Answer: If you want to try out a code solution, you can mess with the favicon in a hook_html_head_alter().
Something like this would be a starting point, but you likely need to adjust the $_SERVER test:
function MYTHEME_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => $value) {
    if (preg_match('/favicon\.ico$/', $key) === 1) {
      if (in_array($_SERVER['HTTP_HOST'], array('localhost', '127.0.0.1')) {
        // adjust $value as needed
        $head_elements[$key] = $value;
      }
    }
  }
}

Answer: Favicon module handles this for the multisite installations. You may get few pointers from the code in the module.
Answer: Based on MPDs answer above, this is the code I used to define a custom favicon on this site, when it is running locally using mamp pro. This is a function in template.php for the active theme. Seems to work well.
function sitename_html_head_alter(&$head_elements) {

  $path = 'http://sitename/sites/default/files/favicon_local.ico';

  if ($_SERVER['HTTP_HOST'] == 'sitename') {

    foreach ($head_elements as $key => $value) {
      if (preg_match('/favicon\.ico$/', $key) === 1) {
        $head_elements[$key]['#attributes']['href'] = $path;
      }
    }
  }
}

Answer: You may find the Environment Indicator module is better suited for that purpose.


python, pandas and importing multiple csv's into a dataframe

Question: My code is grabbing multiple csv files from a directory, and putting all the data into a dataFrame I created and called "df". Each CSV is the same format, but can be of various lengths so this is what I want to do:
I want to have a column in my df (DataFrame) that records the second to last piece of data in each csv I pull in before it moves onto the next one. I have modified the output below to give you an example of what I mean. Let's suppose I call this column BeforeLast. When you see a 0 value, that means its not the second to last piece of data in the csv I pulled, if you see a 1 value it means its the second to last piece of data in the csv I pulled.
How can I do this as Python is pulling in each csv called upon?
import pandas as pd
import glob
import os

path =r'X:\PublicFiles\TradingData\CSV\RealMarkets\Weekly\Futures\Contracts\Corn C'
allFiles = glob.glob(path + "/*.csv")  ##'*' means any file name can be grabbed
df = pd.DataFrame()
list_ = []

for file_ in allFiles:
    names = ['Date', 'Open', 'High', 'Low', 'Close', 'Vol', 'OI']
    df = pd.read_csv(file_, index_col = None, names = names)
    list_.append(df)
frame = pd.concat(list_)

Here is a sample of my current dataFrame (df)
    Date       Open    High     Low   Close   Vol  OI
0   20141212  427.00  427.00  427.00  427.00    0   0
1   20141219  429.00  429.00  424.00  424.00    0   0
2   20141226  424.00  425.00  423.00  425.00    0   0
3   20150102  422.75  422.75  417.50  417.50    0   0

This is what I want
    Date       Open    High     Low   Close   Vol  OI  BeforeLast
0   20141212  427.00  427.00  427.00  427.00    0   0  0
1   20141219  429.00  429.00  424.00  424.00    0   0  0
2   20141226  424.00  425.00  423.00  425.00    0   0  1
3   20150102  422.75  422.75  417.50  417.50    0   0  0 (this is the last piece of data in this csv and now it moves on to the next)
4   20141226  424.00  425.00  423.00  425.00    0   0  0
5   20150102  422.75  422.75  417.50  417.50    0   0  0
6   20141226  424.00  425.00  423.00  425.00    0   0  1
7   20150102  422.75  422.75  417.50  417.50    0   0  0

Answer: Try this.  You do not need a list.  Just append to the original data frame.
.iloc[-2, -1] is the 2nd to last row, last col
I added a index reset as in my test I ran into duplicate index numbers.
import pandas as pd
import glob
import os

path =r'X:\PublicFiles\TradingData\CSV\RealMarkets\Weekly\Futures\Contracts\Corn C'
allFiles = glob.glob(path + "/*.csv")  ##'*' means any file name can be grabbed
df = pd.DataFrame()

for file_ in allFiles:
    names = ['Date', 'Open', 'High', 'Low', 'Close', 'Vol', 'OI']
    df_temp = pd.read_csv(file_, index_col = None, names = names)
    df_temp['beforelast'] = 0
    df_temp.iloc[-2,-1] = 1
    df = df.append(df_temp)

df = df.reset_index(drop=True)

Comment: hey this worked great! one thing I noticed was that my columns re-arranged into some different order. any quick way to put them back the same way I have my [names] ordered?
Comment: try:
    df = df[names]
Answer: df = pd.DataFrame({'a': np.zeros(5)})
df[-2:-1] = 1
print df

   a
0  0
1  0
2  0
3  1
4  0

You can use this when you create each dataframe?
Example in your code:
for file_ in allFiles:
    names = ['Date', 'Open', 'High', 'Low', 'Close', 'Vol', 'OI']
    df = pd.read_csv(file_, index_col = None, names = names)
    before = np.zeros(len(df))
    before[-2] = 1
    df['before'] = before
    list_.append(df)
frame = pd.concat(list_)

Comment: well although that seems useful, how would I incorporate that into my code as the dataFrame is being built? Maybe to incorporate that piece within pd.read_csv(....  ?
Comment: I added a simpler version using numpy array, then just add it to the df before you append.
Answer: Just create a list to keep track of the last column when you are building your dataframe:
import pandas as pd

df = pd.DataFrame()
newcol = []

for i in range(10):
    # Load 10 files and get shape
    # length = df.shape[0]
    length = 10
    c = [0 for i in range(length)]
    c[-2] = 1
    newcol += c

df['BeforeLast'] = newcol

print df

Comment: It doesnt matter how many file you have. Everytime you load a file, just keep track of how long it was using the newcol list. When you have all your files loaded just add the new column to your complete dataframe


Using stokes theorem to calculate line integral (what am I doing wrong?)

Question: Let $\Sigma$ be the triangle with corners $(1,0,0)$, $(0,1,0)$ and $(0,0,1)$. Calculate the line integral $$\int_\Sigma (x+y^2)dx+(y+z^2)dy+(z+x^2)dz, $$ where the contour has a positive orientation seen from the point $(1,1,1)$. Use the stokes theorem.
So the surface of the triangle can be parametrized by $r(s,t)=(s,t,1-s-t)$ where $0\leq t\leq 1-s$ and $0\leq s\leq 1$.
And if $F(x,y,z)=(x+y^2,y+z^2,z+x^2)$ then $\text{curl }F=(-2z,-2x,-2y)$ since $R_y=0$, $Q_z=2z$, $P_z=0$, $R_x=2x$, $Q_x=0$, $P_y=2y$.
Also from $r_s=(1,0,-1)$ and $r_t=(0,1,-1)$ we have $r_s\times r_t=(1,1,1)$.
So by stokes theorem the line integral is given by $$\int_{0}^{1}\int_{0}^{1-s}\text{curl }F(r(s,t))\cdot(r_s\times r_t)dtds=-2\int_{0}^{1}\int_{0}^{1-s}(1-t-s+s+t)dtds=-1/3.$$
The right answer is $-1$.
Comment: $\int_{0}^{1}\int_{0}^{1-s}1dtds$ is the area of the right triangle of vertices $(0,0),(1,0),(0,1)$, which is $\frac{1\cdot 1}{2}$.
Answer: \begin{align}
\int_0^1\int_0^{1-s}(1-t-s+s+t)\,dt\,ds &= \int_0^1\int_0^{1-s}\,dt\,ds \\
&= \int_0^1(1-s)\,ds \\
&= s-\frac{s^2}{2}\Large|_0^1 \\
&= \frac{1}{2}
\end{align}
Comment: guess I shouldn't trust symbolab


What kind of growing function has a constant as limit?

Question: My knowledge in mathematics are a bit old and I'm looking for functions with constant as limit. The function must always grow.
The curve should be something similar to $\sqrt{x}$ or $\ln(x)$ but with $\lim _{x\to \infty \:}f\left(x\right)=\mathrm{constant}$
Could you please help to find this kind of functions?
Comment: $y=a \tan^{-1}(bx+c)+d$, $y=a \tanh(bx+c)+d$ may be
Comment: Do you mean [logistic functions](https://en.wikipedia.org/wiki/Logistic_function)? Or maybe you mean the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) for a (real-valued) random variable $X$?
Comment: The function must be bounded, like $3-e^{-x}<3$ or $\frac{\ln(x)}{\ln(x+1)}<1$ or $\arctan(x)<\pi/2$.
Comment: @travis: is your example-function growing ? And if I am right, $f(x)<1$ for all $x>0$.
Comment: Ah, you're right, I didn't parse "growing" as "increasing", cheers.
Comment: $\displaystyle f(x)=\frac{5x-1}{x}$ over $]0;+\infty[$
Answer: The simplest way is to consider any decreasing function such that its limit is $0$, like $\frac{1}{x+1}$ or $e^{-x}$, and subtract from a constant :
$$C-\frac{1}{x^2+1}$$
$$C-e^{-3x}$$
Comment: @ColdNumber that's why I say "substract" !
Comment: But didn't OP ask for increasing functions?
Comment: Whoops! you're right.
Comment: @Xoff Better say: subtract.
Comment: @CiaPan Yes, sorry, I'm not so good in english sometimes
Answer: If you just want to have some functions with the asked properties, you can easily construct one as Xoff pointed out. If you are looking for a class of functions (possibly from applied mathematics), the logistic function $$f:\mathbb R\rightarrow\mathbb R,~f(x)=\frac{L}{1+e^{-k(x-x_0)}}$$ might be something you are looking for (for the meaning of the constants $L,k,x_0$ consider the wikipedia page, it has lots of information on this).
If your familiar with stochastics and random variables, you could take a look at the cumulative distribution function. It is monotonicically non-decreasing with $\lim\limits_{x\to\infty}f(x)=1$.
Answer: An example could be $f(x)=-1/x$. It grows toward 0, its asymptote.
EDIT: As Hirshy pointed out, $f$ is not an increasing function if its domain is $\mathbb{R}\setminus\{0\}$.
So, define $f : \mathbb{R}_+ \to \mathbb{R}$ by $f(x)=-1/x$.
This function increases monotonically: If $a>b>0$, then $1/a<1/b$, and $-1/a>-1/b$, which means that $a>b \implies f(a)>f(b)$.
Comment: But this function is only monotonic on either $\mathbb R^*_-$ or $\mathbb R^*_+$, so only on restricted domains.
Comment: Yes, thanks, I'm editing my answer.
Comment: @pjs36 for the $\ln(x)$ example the domain is $D=\mathbb R_+^*$ and $f$ is monotonic on its (full) domain. This is not the case with $f(x)=\frac{1}{x}$ which IMO is a difference.
Answer: Functions of $x$: $$-e^{-x}$$ $$ -x^{-1}$$ $$\cos \tfrac 1x \ \ \text{for}\ x > \tfrac 1\pi $$ $$\arctan x$$ all are monotonically growing and have finite limit as $x\to\infty$.


model two spatial auto correlation in spdep package in r

Question: I hope to fit the spatial autoregressive model :
$$
y= \gamma_1 Wy + \gamma_2 By + X\beta +\epsilon. \quad (1)
$$
where $W, B$ are different weight matrices.
However, every references I've found only mention the SAR model that estimates one autocorrelation, i.e.
$$
y= \gamma_1 Wy + X\beta +\epsilon
,$$
which can be fitted by using lagsarlm function in the R package spdep.
Therefore, I wonder if I could fit the model (1).
Answer: I emailed to the author, Roger Bivand, who has developed the spdep package to ask this question.
Prof.Bivand, who kindly answered and gave me more suggestions, said :
"There are no such fitting functions implemented anywhere, to the best of my knowledge."
Thanks for anyone giving interest on this question.
Answer: Without knowing more about $W$ and $B$ (or why you would theoretically want to include two different weight matrices), I can't be sure that this directly answers your question. But, Spatial Durbin and Spatial Durbin-Watson models can be estimated with maximum likelihood, without having to use the spdep package. And there are many options in R for MLE. You might also consider some form of a two-stage or simultaneous equation model. For example, fit the model first with with $W$, and then use your predicted values from this in the second model with $B$. But again, the right specification will depend on your theory of the relationship between $y$, $By$, and $Wy$.
Comment: Sure thing. And also$\dots$ you should think through the implications of this, but I'd note that your model with two spatial-lags looks very similar to a model with a spatial-lag + a time-lag, which are not uncommon. And, these models can be estimated with little difficulty, so perhaps worth considering how this might relate to a model with 2x spatial lag?  I was assuming that one of your matrices was inverse-distance on $y$ or similar, but I couldn't guess your other matrix. You might get better answers if you updated your question.
Comment: For "inspiration," Franzese and Hays have a number of articles, with very well-worked examples, e.g., [Empirical Models of Spatial Interdependence](http://www-personal.umich.edu/~franzese/FranzeseHays.SpatialInterdep.OxfordHandbook2008.Corrected.pdf). Though, depending on your field, these examples may be more/less relevant.
Comment: Thanks for your response and comment :) In fact, $W$ is a within-district weight matrix and $B$ is a between-district weight matrix, and I hope to detect within or between effects simultaneously. (I missed editing my answer, sorry)
Comment: Okay, I see your thinking there, and that makes sense. But again, without knowing the details of your data/theory, I'd nevertheless suggest in this case not using the above suggestion (answer) but instead specifying the within-weight not as a spatial-lag but as a random effect. The intra-class correlation (ICC) for within-district will then give you information on within-distict-homogeneity, controlling for between ($B$) dependence. On ICC with random effects, perhaps [here](http://stats.stackexchange.com/questions/18088/intraclass-correlation-icc-for-an-interaction?rq=1) is helpful.
Comment: thanks for sharing your ideas. I'd be happy to search those possible models with your kind links. Thanks so much again.


Show/hide home button depending on route

Question: I'm doing the first steps in Ember.js and I am quite confused by the different approaches and solutions provided in communities.
I have a quite small application that has a application template and content templates which I navigate through by link-to.
My application template has a home button which I want to hide and show depending on the route i am navigating to. How do I do that?
I am using plain-old JavaScript. No preprocessors or similar.
Answer: you can use global currentRouteName property directly in your controller
in your application controller
hideHomeButtonRoutes: ['index', 'login'],
isHomeButtonVisible: Ember.computed('currentRouteName', function(){
  return this.get('hideHomeButtonRoutes').indexOf(this.get('currentRouteName')) > -1;
})

in your template
{{#if isHomeButtonVisible}} <button>home</button> {{/if}}

here is working example
Comment: Could you specify route and controller in for your solution? Do I need to set setupController for every route of my application? Or is it somesort of application route? Is controller kind of a application controller?
Comment: this is only done once same level as your home button, if it is in application template put everything in application route, controller
Comment: Like this?

App.ApplicationController = Ember.Controller.extend({
 hideHomeButtonRoutes: ['index', 'intro'],
 isHomeButtonVisible: Ember.computed('currentRouteName', function() {
  return this.get('hideHomeButtonRoutes').indexOf(this.get('currentRouteName')) > 1;
 })
});

App.ApplicationRoute = Ember.Route.extend({
 setupController: function (controller, model) {
  controller.set('currentRouteName', this.router.currentRouteName);
 },
});

Somehow doesn't work. I don't get it.
Comment: sorry I missed something I am updating answer
Comment: doesn't work either :/ I am using Ember.js 2.2. Is this important? Here my code:
App.ApplicationController = Ember.Controller.extend({
 hideHomeButtonRoutes: ['index', 'intro'],
 isHomeButtonVisible: Ember.computed('currentRouteName', function() {
  return this.get('hideHomeButtonRoutes').indexOf(this.get('currentRouteName')) > 1;
 })
});

App.ApplicationRoute = Ember.Route.extend({
 actions: {
     loading: function() {
        if (this.controller) {
         this.controller.set('currentRouteName', this.router.currentRouteName);
        }
      }
    }
});
Comment: I think the operator should be `=== -1` instead of  `> -1`.


Show that $\mathcal{P}(\mathbb{N}),\; A=\{x\in\mathcal{P}(\mathbb{N})\mid x\text{ is infinite}\}$ have the same cardinality

Question: Well, one direction is pretty trivial, we could just take $id_A$ as an injective function.
How should I approach the other direction?
Comment: $id_A : A \rightarrow A$
Comment: @RiccardoAllegrone If you mean $id_A : A \rightarrow \mathcal{P}(\mathbb{N})$ Thats the trivial part I was talking about
Comment: I mean that $id_A$ goes from $A$ to $A$, not to $\mathcal{P}$. Maybe you want to use inclusion.
Comment: @RiccardoAllegrone Thanks for the observation.
Answer: $\mathcal P(\Bbb N)\setminus A$ is countable, and one could use that fact to play Hilbert's Hotel.
Or just map $\mathcal P(\Bbb N)\to A$, $X\mapsto 2X\cup (2\Bbb N+1)$.
Comment: Hey Hagen. Thanks for your comment.
Could you elaborate furthermore on your map? I didn't quite get it.
Answer: As Hagen said, the set of finite subsets of $\Bbb N$ is countable, and so, the set of co-finite subsets of $\Bbb N$ is countable($B=\{x\in\mathcal{P}(\mathbb{N})\mid {\Bbb N}\setminus x\text{ is finite}\}$), because $|\Bbb N\times2|=|\Bbb N|$, take $G:({\cal P}(\Bbb N)\setminus A)\cup B\to B$ a bijective function.
Let $F:{\cal P}(\Bbb N)→A$ define like this: if $x∈({\cal P}(\Bbb N)\setminus A)\cup B$ then $F(x)=G(x)$, elsewhere $F(x)=x$. $F$ is a bijection


Spring-Batch job does not end after last step

Question: My Spring-Batch job is set like that:
<code>@Bean
Job myJob(JobBuilderFactory jobBuilderFactory,
                   @Qualifier("stepA") Step stepA,
                   @Qualifier("s"tepB) Step stepB) {
    return jobBuilderFactory.get("myJob")
            .incrementer(new RunIdIncrementer())
            .start(stepA)
            .next(stepB)
            .build();
}
</code>
And here is my launcher:
<code>@Autowired
JobLauncher(@Qualifier("myJob") Job job, JobLauncher jobLauncher) {
    this.job = job;
    this.jobLauncher = jobLauncher;
}

@Scheduled(fixedDelay=5000)
void launcher() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
    jobLauncher.run(job, newExecution());
}

private JobParameters newExecution() {
    Map<String, JobParameter> parameters = new HashMap<>();

    this.dateTime = new DateTime(DateTimeZone.UTC);
    this.dateTimeString = this.dateTime.toString(ISODateTimeFormat.dateTime());
    JobParameter parameter = new JobParameter(this.dateTimeString);
    parameters.put("currentTime", parameter);

    return new JobParameters(parameters);
}
</code>
As you can see, my job is scheduled to launch every 5 seconds.
But, after first launch, it does not end; it goes on the next execution.
The job is like in a loop. I would like it to stop and restart after 5 seconds.
Answer: I missed that readers need to return null when they finish. Problem solved.
Comment: If you are using Tasklet and still the issue persists?
Answer: You can also use System.exit(0); at the end of main class which will terminate JVM resulting in terminatation of batch.
Comment: This is not recommended.
Comment: this not recommended and not working


Search result is empty

Question: When I do a search, I got an empty result even though the result shouldn't be null.
I even get a null result if I don't filter anything. However fulltext search works, only facets corresponding to a field seems to not work.
I copied a production database to a test server. Everything works fine on production, but I can make the test copy works.
I've seen there is some issue with facets if the user doesn't have the permission to create temporary table. I checked that, and I think I have the permission.
Any idea ? (I use drupal commerce)
Comment: Well, I think the obvious issue is that there is something different between production and testing ... it's likely the index server (I assume it's search api and/or solr powered faceting) is not available. Are you seeing index errors? What are you using to index your data? Have you tried flushing the index on the non-production server?
Comment: I've cleared the index, rebuilt it, the index tables are correct, but that doesn't seem to be enough. I'm using the basic sql backeng.
Comment: Would need a full export of the view + search api setup to debug. You're right, if all is perfect, it should work. It's even more mysterious that it works in one environment, but not the other. Leads me to think the issue is outside of Drupal. Perhaps an older MySQL or too limited of a setup. Do you see any errors in your logs that would help you point to a problem?
Comment: I'm using docker (one container for apache and one for mysql and there are exactly the same between the two environment). I'm happy to add some trace and do some debugging but I don't how where to start
Answer: The problem was due to different behavior between mysql 5.6 and 5.7. I thought I had the same environment between production and test but I was wrong. I use a docker image for mysql but didn't specify a version so I ended up with two different versions on the two systems, even though the provisioning looked the same.

Search result is empty


Jquery find and output a dictionary

Question: I'm a beginner in jQuery, and been trying to get something like this using "find" :
Input :

Bryan Adams (Singer)
Bryan Adams (Composer)
Toto (Group)

Celine Dion (Singer)
John Travolta (Actor)

Celine Dion (Composer)
John Travolta (Director)

... and so on

Output will be a dictionary of Name (key) and Professions - appended using comma (value)
[Bryan Adams]   [Singer,Composer]
[Toto]          [Group]
[Celine Dion]   [Singer,Composer]
[John Travolta] [Actor,Director]

Thanks in advance
Comment: When you say "input", is it an HTML String, or actual DOM elements? And is this how you want the output: `{"Toto": ["Group"], "Celine Dion": ["Singer", "Composer"], ...}` ?
Comment: Psst JavaScript doesn't have dictionaries. It has arrays.
Comment: @evolutionxbox Pssst every JavaScript object is a dictionary
Comment: Like i told you @void, i'm a beginner in jQuery, i've been spending hours, i only come up with this : $.find("a[href^='/person.asp']").map( function i,v) { return $(v).text(); });
Comment: @Ragnagord I couldn't consider objects to be dictionaries... You can create your own object type which emulates dictionaries.
Comment: @evolutionxbox Of course they are dictionaries. A dictionary is nothing more than a collection of key-value pairs,  which every js object is.
Comment: @Ragnagord Meh. We're just arguing semantics.
Answer: You can use each() for td's and a's elements and add to object

var obj = {};
$('td').each(function() {
  $(this).find('a').each(function() {
    var name = $(this).text();
    var value = this.nextSibling.nodeValue;
    obj[name] = (obj[name] || []).concat(value.trim());
  })
})

document.body.innerHTML = "
" + JSON.stringify(obj, 0, 1) + "
";
table {
  display: none;
}

      Bryan Adams (Singer)
      Bryan Adams (Composer)
      Toto (Group)

      Celine Dion (Singer)
      John Travolta (Actor)

      Celine Dion (Composer)
      John Travolta (Director)

Answer: You could do it this way, using a little regex to extract the role from the parenthesis:

var result = {};

$('a[href^="person.asp"]').each(function(){
  var name = $(this).text(),
      role = this.nextSibling.textContent.match(/\(([A-Za-z\s]*)\)/);

  // If the name is not in the result Object
  if(!result.hasOwnProperty(name)) { result[name] = []; }
  // If the role is defined and not in the roles' array already
  if(typeof role !== "undefined" && role[1].length && result[name].indexOf(role[1]) < 0) {
    result[name].push(role[1]);
  }
});

document.body.innerHTML = "
" + JSON.stringify(result, 0, 4) + "
";

            Bryan Adams (Singer)
            Bryan Adams (Composer)
            Toto (Group)

            Celine Dion (Singer)
            John Travolta (Actor)

            Celine Dion (Composer)
            John Travolta (Director)

Jquery find and output a dictionary


Ajax filter in exposed view not working

Question: I am embedding a view as such:
function theme_module_name_element($element) {
  $view = views_get_view('view_name');
  $view->set_use_ajax(TRUE);
  $output = $view->render();
  return $output;
}

The view is displayed then by the filefield sources module but when you try to search it won't use ajax. I'm assuming this has something to do with the js not being loaded but I just can't figure out how to get this going!
Any ideas?
Edit: This might be related to this: http://drupal.org/node/386388
Edit 2: The pager works and when it has been used the search works...
Edit 3: When the pager is pressed (and everything works fine) there is html added to the form so it goes from:
(Edit 3 update: If I had to guess I would say "Drupal.behaviors.ViewsAjaxView" from ajaxViews.js isn't being executed when the filefield_sources source is being chosen.)

                Search

                            <input type="text" maxlength="128" name="image-title" id="edit-image-title" size="30" value="" class="form-text">

                    <input type="submit" id="edit-submit-Filefield-Sources-Imagebrowser" value="Apply" class="form-submit">

to:

    <form action="/" accept-charset="UTF-8" method="get" id="views-exposed-form-Filefield-Sources-Imagebrowser-default" class="views-processed">

                    Search

                                <input type="text" maxlength="128" name="image-title" id="edit-image-title" size="30" value="arnar" class="form-text">

                        <input type="submit" id="edit-submit-Filefield-Sources-Imagebrowser" value="Apply" class="form-submit">

        <input type="hidden" name="view_name" value="Filefield_Sources_Imagebrowser">
        <input type="hidden" name="view_display_id" value="default">
        <input type="hidden" name="view_args" value="">
        <input type="hidden" name="view_path" value="node/add/dagskrafaerslur">
        <input type="hidden" name="view_base_path" value="null">
        <input type="hidden" name="view_dom_id" value="655136b3027e2ef4608dfbaa7605db4c">
        <input type="hidden" name="pager_element" value="0">
    </form>

(Notice the addition of the form tag and input elements.)
Comment: Did you checked whether the required/necessary views js files are loaded? Please confirm the same by viewing the page source.
Comment: Yes, they are loaded. If I print the view directly (in module code or directly) everything works as it should but when the view is printed by the Filefield Sources module the js isn't applied.
Comment: Did you check in firebug or chrome dev tools weather the javascript has errors?
Comment: Yes, there are no errors. Thanks for any help though :)
Answer: Enable the Ajax in Views Basic Setting and remove $view->set_use_ajax(TRUE); and check.
Comment: I think both methods are doing the same :(
Comment: yeah but there can something missing in code.. I also worked in exposed filter yesterday. I added more than one block. But ajax was working on only one block.
Comment: Nope, that doesn't do the trick, Unfortunately.
Comment: @KarlJóhann Your other code can be the reason of this?
Answer: Not sure what you mean by:  "the js isn't applied"
So the shotgun approach...

Check the HTML source for .js files:
misc/ajax.js
sites/all/modules/views/js/ajax_view.js

views_add_js() is the command that loads the javascript.
http://api.drupal.org/api/views/views.module/function/views_add_js/7

If the js files aren't there maybe the scripts section in the header doesn't get updated:
$vars['scripts'] = drupal_get_js();
From: http://drupal.org/node/386388#comment-3176034
Comment: I have tried adding the js into the header but that doesn't help, probably because, as I then found out, the js is already there.
Comment: Did you mean misc/ahah.js? What I mean by js isn't applied is that the "apply" button does not use ajax to filter the view.
Comment: Not sure then, are there any js errors on the page? _The pager works and when it has been used the search works..._ kinda sounds like Drupal.attachBehaviors() isn't being run. Try opening a javascript console and running Drupal.attachBehaviors(), or  combo of Drupal.detachBehaviors() / Drupal.attachBehaviors()
Comment: No sorry, that's not it either... unfortunately
Answer: I just fixed a similar issue in my page. From your listing:
<input class="form-submit" type="submit" id="edit-submit-Filefield-Sources-Imagebrowser" value="Apply">

What is missing here (and was also missing in my case) are the classes which make autosubmitting code work. From my code (after fixes):
<input class="ctools-use-ajax ctools-auto-submit-click js-hide form-submit" type="submit" id="edit-submit-view-path" name="" value="Apply" />

In order to get the classes ctools-use-ajax ctools-auto-submit-click js-hide applied on input I had to fix theming. Check where your buttons are themed and if the classes aren't removed. I suspect this might be the reason because the attributes of your input are rendered in different order as in original Drupal theme. As for quick fix you can use a standard template coming with standard Drupal installation. Hope that helps.
Answer: I had the exact same problem down the same experience where using the pager caused the exposed filters to start using Ajax. In my case it was because the code was making the view get rendered inside of another form. If the views code was moved to render above the other form the JS was properly applied and the exposed form used Ajax submission. This makes sense since forms are not allowed inside of other forms.

Ajax filter in exposed view not working


Trivial norm is equivalent only to itself

Question:
Trivial norm is equivalent only to itself (on a field)

The norm here fulfills $3$ requirements
$(1) |x|\ge0$ and $ |x|=0\iff x=0$
$(2)|x\cdot y|=|x|\cdot|y|$
$(3)|x+y|\le|x|+|y|$
$2$ norms are said to be equivalent iff they induce equivalent metrics, and $2$ metrics $d_1,d_2$ are said to be equivalent if a sequence is Cauchy w.r. to $d_1$ iff it is Cauchy w.r. to $d_2$
So when I pick the trivial norm, i.e. $ |x| = \left\{ \begin{array}{ll}
         1 & \mbox{if $x \neq 0$};\\
        0 & \mbox{if $x = 0$}.\end{array} \right. $
and any nontrivial norm $|.|'$ then choose any nonzero element $x$ with $|x|'\neq1$ such an element must exist so if $|x|'>1$ then take $x^{-1}=:y$ so $|y|'<1$ and the sequence $\{y^n\}_n$ is Cauchy w.r. to $|.|'$ because for $n\ge m\ge N:|y^n-y^m|\le|y^n|+|y^m|\le2|y^m|\le2|y^N|$ and not Cauchy in $|.|$ because $\nexists N;n,m\ge N\implies|y^n-y^m|<1$
Is this enough ? I cannot mention any topology or balls, I have to stick to the definition
Comment: Well my sense is that you're going to confuse people who (like me) use the definition of a norm on a $\mathbb K$-vector space instead of the definition for a norm on some ..ring? I don't know. Up to you.
Comment: Why is $\{y^n\}_n$ Cauchy with respect to $|\cdot |'$?
Comment: @kccu Is it not ? say $m\le n$ then $|y^m-y^n|'\le|y^m|'+|y^n|'\le|y^m|'\cdot2$
Comment: Your "trivial norm" is not a norm, since $|2x| ≠ 2|x|$
Comment: @CalvinKhor What needs to be fixed ?
Comment: Don't call it a norm? Its pretty much the discrete metric. See absolute homogeneity in  https://en.wikipedia.org/wiki/Norm_(mathematics)#Definition
Comment: @CalvinKhor it is taken from the book https://ibb.co/jk295zC
Comment: I suppose they replace $\|kx\| = |k|\|x\|$ with $N(xy) = N(x)N(y)$. I don't think the real-analysis tag is correct, you should probably tag with a $p$-adics related tag and add this context to the question
Comment: @CalvinKhor Yes the book is about p-adics, but the question not so
Comment: @counterfeit I agree with that inequality, but my question is why $|y^m|'$ should go to zero as $m$ goes to infinity. You haven't said anything about how your norm plays with multiplication in the field.
Answer: I think your argument is essentially correct. You can add to clarify that in the trivial norm, $\lvert z \rvert < 1 \Leftrightarrow z = 0$ and a sequence is Cauchy if and only if it is eventually constant. Also, the last line should read
$\not \exists N: \color{red}{\forall} m,n \ge N: \lvert y^m-y^n\rvert < 1$
which you still have to show -- I would write $y^m - y^n = y^m (y^{m-n}-1)$, the first factor cannot be $0$ because $y \neq 0$ and we're in a field, the second factor cannot be zero for $m \neq n$ because $\lvert y^{m-n} \rvert = \lvert y \rvert^{m-n} \neq 1 = \lvert 1 \rvert$ by choice of $y$.
Besides those (maybe pedantic) mathematical points, I think your argument would also be improved by correct sentences, grammar, and punctuation. That is no small issue. As it stands, your decisive paragraph is a run-on sentence going "So when ... then ... and ... because ... and not ... because ... ." Please break that up into smaller bits.


There are 2 square brackets around 2 notes in this trombone part. What does it mean?

Question:
In this trombone part there is square brackets and slide numbers on these notes. What does this indicate?
Comment: The meaning of brackets is typically context dependent. If possible, please add the title, composer, and a picture that includes a measure or two on either side of the bracketed part.
Comment: Is this a treble clef or bass clef part?
Comment: Given how it lines up perfectly with what we know about trombone and E and F, almost certainly it's bass clef.  But a clef would still be nice:)
Comment: The only certain answer, from the limited context provided, is that we don't know what the brackets mean. We can probably assume the numbers are slide positions (for bass clef notes) but, again, lack enough context to say why the previous F, presumably in 1st, should be followed by an E in 7th!

Brackets sometimes indicate 'omit this'. But why would meticulous instructions be given for something that wasn't to be played? I've never known them mean 'nota bene'.
Answer: A trombonist would normally play the E in 2nd position and the F in 1st.  Alternatively, the notes can be played in 7th ad 6th positions, one partial higher.  Without seeing the larger context of the piece I don't know why they are to be played so far out, but one might guess that nearby notes of low B and C (which can only be played out there)* might make the passage easier.
I've not seen the brackets before, I can only guess they are there to call attention to the alternate positions.
The * above is to say that a trombone equipped with an F attachment can play the low B and C in 2nd and first position with the trigger.
Comment: Couldn't the brackets simply mean that those those notes could be omitted?


Identically Distributed Casella and Berger

Question: I was  reading Statistical Inference in Casella and Berger and saw that they define $X$ and $Y$ identically distributed if $\forall\mathbb{B}\in\mathbb{R}$
$$P(Y\in B)=P(X\in B)$$
It is my understanding that identically distributed does not require random variables to be defined on the same space that is $X$ and $Y$ can be defined on different probability triples. It appears to me that in this definition they are defining the random variables on the same probability triple given the same measure $P$. The only way I can see this happening for r.v defined on different spaces is constructing the product space on the two different probability triples and $P$ is the new measure defined on this space. I guess I am just confused on whether $P$ is the probability measure or its just sloppy notation to signify probability on whatever $X$ and $Y$ are defined on. Can someone help clarify my confusion?
Comment: Possibly relevant: https://math.stackexchange.com/questions/528250/do-two-random-variables-defined-on-different-probability-spaces-have-the-same-di
Answer: The probability $P$ you have here is not the measure in your probability triples. You have some "black box" set $\Omega$ with its $\sigma$-algebra $\mathcal{T}$ and its probability measure $\mathbb{P}$, but when you describe the law of your random variable $X:\Omega \rightarrow \mathbb{R}$ you use the induced measure $P$ defined by $P(B)=\mathbb{P}(X^{-1}(B))$. Thus you r.v. $Y:\Omega'\rightarrow \mathbb{R}$ can be defined on another triplet, its law will still be expressed with an induced measure on $\mathbb{R}$ which will be the same as $X$. You are still right on one thing:  it is not supposed to be the "same" $P$ in both $P(X\in B)$ and $P(Y\in B)$, but one often allow such abuse since you can construct a greater probability triplet including both of your variables without changing the law of your variables nor the way they behave as a couple.
Comment: By greater probability triple are you referring to the construction of a product space and can define the prob of X=x by taking the whole space of Y and the Cartesian product with x which produces the same prob as On the original Space of X


jQuery ScrollTo não funciona! Me ajuda? Cannot read property 'top' of undefined

Question: Boa tarde,
Estou tentando usar uma funcionalidade jQuery através de um código que encontrei na internet. Mas ele não está funcionando! Vocês podem me ajudar a repará-lo?
Quando clico em 'Veja mais', deveria rolar a página até a div 'Quero Fazer Parte'.
Olha só:
BOTÃO / LINK:

    VEJA MAIS

JQUERY:

SCROLL TO:

Comment: Edite sua pergunta, colocando o que quer fazer e qual sua dúvida!
Answer: Seu código funciona perfeitamente, se não colocar uma div com o id QueroFazerParte, como pretende que o código funcione? Você na tag a está chamando um ID com o # ", só que na div que quer fazer scroll vc colocou outro id id="row-11071" e o QueroFazerParte vc colocou na classe class="row row-collapse row-full-width QueroFazerParte". Tbm retirei o ($) da function que não está fazendo nada e o preventDefault() que também não vi o pq do uso dele neste código. Veja funcionando:

$(function() {
  $(".scrollTo").on('click', function() {

     var target = $(this).attr('href');
     $('html, body').animate({
       scrollTop: ($(target).offset().top)
     }, 2000);
  });
});
body{height: 700px;}
div{background-color: red;margin-top: 700px;}

  VEJA MAIS

DIV


What is the best method to combine (aggregate) multiple Excel files?

Question: I have multiple EXCEL spreadsheets that contain the SAME columns, just different data per source.

EXCEL File #1:
URL                     |     HITS
http://myothersite.com        5
http://mysite.com             8
EXCEL File #2:
URL                     |     HITS
http://mysite.com             2
EXCEL File COMBINED:
URL                     |     HITS
http://mysite.com 10
http://myothersite.com        5

I need a solution that will AGGREGATE all of the data from the individual spreadsheets into ONE combined spreadsheet.  Each spreadsheet will have the same columns, just different data.  Hopefully this is a common problem with some standard solutions.  I'm open to programmatic solution as well as software solutions.  Thanks!
jg
Comment: Voted to migrate to Super User given accepted answer is an addin, not code
Answer: Kindly use the addin RDBMerge.
Comment: This worked great.  To add to it.  Use RDBMerge, then use the Excel "consolidate" feature to Sum up duplicate rows -- and merge duplicates.  Thanks!


Isomorphism of $\mathbb Z[\xi]/\left<\xi-1\right>$ with $\xi$ root of unity.

Question: I am trying to prove the following isomorphism but I am not sure how to.

Let $\xi=e^{2\pi i/p}$ and $p$ a prime. Show $$\mathbb Z[\xi]/\left<\xi-1\right> \cong \mathbb F_p .$$

I wanted to create a map $\phi : \mathbb Z \rightarrow \mathbb F_p $ with kernel $<\xi-1>$ but so for I have not have good ideas. Any hint? I know that any element in $<\xi-1>$ is of the form
$$
(a_{p-1}-a_0)+(a_0-a_1)\xi+\cdots+(a_{p-2}-a_{p-1})\xi^{p-1}
$$
but I do not know how to use this information.
Thank you!
Answer: For a different approach, you can use the Third Isomorphism Theorem.  Since
$$
\mathbb{Z}[\xi] \cong \frac{\mathbb{Z}[x]}{(x^{p-1} + x^{p-2} + \cdots + x + 1)}
$$
then
\begin{align*}
\frac{\mathbb{Z}[\xi]}{(\xi - 1)} \cong \frac{\mathbb{Z}[x]}{(x^{p-1} + x^{p-2} + \cdots + x + 1, x - 1)} \cong \frac{\mathbb{Z}[1]}{(1^{p-1} + 1^{p-2} + \cdots + 1 + 1)} \cong \frac{\mathbb{Z}}{(p)} = \mathbb{F}_p \, .
\end{align*}
Comment: How did you substitute x for 1 in $ \mathbb{Z}[x]/ \langle f(x), x-1\rangle \cong \mathbb{Z}[1]/ \langle f(1), 1-1\rangle $
Comment: @MinecraftPlayer69 By the third isomorphism theorem, $\frac{\mathbb{Z}[x]}{(x^{p-1} + x^{p-2} + \cdots + x + 1, x - 1)} \cong \frac{\mathbb{Z}[x]/(x-1)}{(x^{p-1} + x^{p-2} + \cdots + x + 1, x - 1)/(x-1)}$. Now $\mathbb{Z}[x]/(x-1) \cong \mathbb{Z}$ via the map sending $x \mapsto 1$ (see [here](https://math.stackexchange.com/a/2593780/22912) for details), and under this map, $x^{p-1} + x^{p-2} + \cdots + x + 1$ is sent to $1^{p-1} + 1^{p-2} + \cdots + 1 + 1$.
Answer: A couple of hints:

You should know that $\xi$ is a zero of the polynomial $$\Phi_p(x)=x^{p-1}+x^{p-2}+\cdots+x+1.$$ Therefore $\Bbb{Z}[\xi]\simeq \Bbb{Z}[x]/\langle \Phi_p(x)\rangle$. Your mapping $\phi$ therefore must have the property
$$\xi^{p-1}+\cdots+\xi+1\mapsto 0.$$
When your kernel is to contain the ideal $I=\langle \xi-1\rangle$, basically that means that $\phi$ should equate $\xi$ and $1$, or $\phi(1+I)=\phi(\xi+I)$.
By induction the previous bullet implies that $\phi(\xi^k+I)=\phi(1+I)=1$ for all $k$.

Combining items 1 and 3 should get you there.
Answer: Hint: you need a homomorphism $\phi$ from $\Bbb{Z}[\xi]$ to $\Bbb{F}_p$ with $\xi - 1$ in its kernel, i.e., with $\phi(\xi - 1) = 0$. As $\phi(\xi - 1) = \phi(\xi) - \phi(1) = \phi(\xi) - 1$, what must $\phi(\xi)$ be?