text:
Q: Inability to render domain class object as JSON in grails 3.3.8 Hello, I am facing some serious challenges after updating my version of Grails from 3.2.4 to 3.3.8 and GORM to 6.1.10
One example is rendering a domain class object or list of domain class objects as JSON
Previously, the following would work but it fails after the update
From my understanding, after updating, domainObject.properties doesn't return only a map of persistent attributes and their values, but other sub-objects and attributes that cannot be formatted as JSON, leading to the errors.
def action() {
    List<User> users = User.list(max: 10)
    render users as JSON
}

Therefore, my question is, is there a way to walk around this issue so that I can render objects as JSON without using collect to transform them?


text:
Q: Standard pinout for RS-422? I am making a custom connector that will carry several signals to a test board including RS-422 RX+/RX- and TX+/TX-. The strange thing is that I didn't find a standard pinout for the DB9 connector used for the RS-422!
So I checked the manufacturer of the RS-422 PCI card in my PC and found their own pinout which means that my test board can only be interfaced to this RS-422 from this manufacturer and won't work on solutions from others?! Is that normal for this "standard" protocol?!

A: From Wikipedia:

RS-422 only specifies the electrical signaling characteristics of a single balanced signal.  Protocols and pin assignments are defined in other specifications.  The mechanical connections for this interface are specified by EIA-530 (DB-25 connector) or EIA-449 (DC-37 connector), however devices exist which have 4 screw-posts to implement the transmit and receive pair only.  The maximum cable length is 1500 m. Maximum data rates are 10 Mbit/s at 12 m or 100 kbit/s at 1200 m. RS-422 cannot implement a truly multi-point communications network such as with EIA-485, however one driver can be connected to up to ten receivers.

So, according to the Wiki, there indeed is no standard for the pin assignments of RS-422 on a DB-9 connector.
In addition to that, different websites say different things:

So there probably indeed is no standard.

A: Most Professional broadcast equipment will use a D-Sub9 with the standard set by Sony:
7 - TX+
2 - TX-
6 - GND
3 - RX+
8 - RX-
4 - GND
The above pinout is for a "Controlled" device such as a VTR. (for a "Controlling" device, TX becomes RX and vice versa).
But as the other contributors have said, you always need to check with the manufacturer.   And however things are pinned out, be sure to keep the +/- pairs on the same twisted pair cables.  If you, for example, accidentally pair TX+ with RX- on the twisted pair you will get intermittent errors which are nasty to figure out.

A: As previous answers have stated, there does not appear to be a standard for 422/485 pinout on a DB9 connector.
However, it is interesting to note that if you are designing a board using a transceiver that can switch between different protocols (LTC2870IUFD), or if your equipment is using such a device internally, then your hands are effectively tied.
With this particular LTC device, which contains 2 drivers and 2 receivers and supports 232, 485 and 422, the low voltage TX signal will be connected to Driver Input 1 such that RS232 TX will emerge on the Driver Output 1 (pin 19 on the TSSOP package) in 232 mode. In 485/422 mode, this signal becomes TXD+ and the corresponding TXD- emerges on Driver Output 2 (pin 17 on the TSSOP package).
Without further analog multiplexing on the output side, if these signals are routed to your DB9, then the 422 pinout is effectively defined for you:
For RS232 compatibility the TX/TXD+ signal must get routed to pin 3 (DTE)
The second driver is used for RTS in 232 mode, thus the RTS/TXD- signal must get routed to pin 7.
As can be seen, the pinout of the right hand table (above) is emerging. If you continue the exercise, CTS/RX+ end up on pin 8 and RX/RX- on pin 2.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ppm file, object declaration to a compoment So, i have a ppm file and in the ppmformat.cpp, i have      imaging::component_t *buffer = new imaging::component_t[3*numCol*numRow];. What i declare with this? I want a buffer with(3*numCol*numRow) size, but i cant understand what the use of component_t?
  class Color.h
     #include <ostream>
     #ifndef _COLOR
     #define _COLOR

     namespace imaging
     {
     /*! An alias for the floating point representation of color components (32bit per color channel).
      *
      * Each color channel goes from 0.0f (darkness) to 1.0f (full color brightness).
      * For example, bright red is (1,0,0), white is (1,1,1), magenta is (1,0,1) etc.
     */
     typedef float component_t;

     /*! Represents a triplet of Red, Green, Blue (RGB) values.
     */
    class Color
    {
    public:
    // members
    component_t r, //! The red color channel (component)
        g, //! The green color channel (component)
        b; //! The blue color channel (component)

           // member functions

           /*! This operator returns the index-th component of the image.
           *
           *    For speed, no bounds for index values are checked.
           *
           *  \param index is the index of the component to obtain. Values should be 0, 1 or 2.
           *
           *  \return a reference to the respective color component.
           */
         component_t & operator [] (size_t index)
         {
         return *(&r + index);
         }

         /*! Addition operator.
         *
         *  Adds a color to the current one and returns the result.
         *
         *  \param right is the right Color operand of the + sign.
         *
         *  \return the resulting color after the component-wise addition of the two colors.
         */
         Color operator + (Color & right)
         {
         Color left;
         left.r = r + right.r;
         left.g = g + right.g;
         left.b = b + right.b;
         return left;
         }

         // constructors

    /*! Parameterized constructor.
    *
    * \param r is the red component of the color.
    * \param g is the green component of the color.
    * \param b is the blue component of the color.
    */
    Color(component_t r, component_t g, component_t b) : r(r), g(g), b(b) {}

    /*! Default constructor.
    *
    *  All components set to zero, i.e. a black color.
    */
    Color() : r(0), g(0), b(0) {}
   };
  }

  #endif _COLOR

A: You can see that component_t is an alias to float data type. so it makes no difference whether to use float or component_t in your declaration.
typedef float component_t;

but I recommend you to use component_t which represents a color component so it makes your code more readable.


text:
Q: ListView not scrolling when add items at runtime. LinearLayout inside ScrollView neither does it work I have one listview inside constraintLayout. I add items at runtime in listView. When items exceed the visible part of listView, it does not move up or down to show hidden items.
I have tried changing listView by linearLayout inside scrollView but the same thing happens.
I've done enough tests and I think the problem is on xml layout file.
Is a fragment over other fragment (I had to set clickable property to true on constraintlayout parent).

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:clickable="true"
    tools:context=".CrearTurno">

    <TextView
        android:id="@+id/crear_turno_tv_comentario"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:text="@string/crear_turno_tv_comentario"
        app:layout_constraintStart_toEndOf="@+id/crear_turno_linearvisorparent"
        app:layout_constraintTop_toBottomOf="@+id/crear_turno_tv_horacomienzo" />

    <Button
        android:id="@+id/crear_turno_bt_colorfondo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="@string/crear_turno_tv_colorfondo"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/crear_turno_bt_colortexto"
        app:layout_constraintTop_toBottomOf="@+id/crear_turno_etx_comentario" />

    <EditText
        android:id="@+id/crear_turno_etx_horasturno"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="4dp"
        android:layout_marginEnd="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/crear_turno_tv_horasturno"
        app:layout_constraintTop_toBottomOf="@+id/crear_turno_etx_abreviatura" />

    <TextView
        android:id="@+id/crear_turno_tv_horasturno"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="26dp"
        android:text="@string/crear_turno_tv_horasturno"
        app:layout_constraintEnd_toEndOf="@+id/crear_turno_tv_abreviatura"
        app:layout_constraintStart_toEndOf="@+id/crear_turno_linearvisorparent"
        app:layout_constraintTop_toBottomOf="@+id/crear_turno_tv_abreviatura" />

    <LinearLayout
        android:id="@+id/crear_turno_linearvisorparent"
        android:layout_width="120dp"
        android:layout_height="450dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ListView
            android:id="@+id/crear_turno_linearvisor"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="@color/primary_light"
            android:gravity="center"
            android:orientation="vertical">

        </ListView>
    </LinearLayout>

    <TextView
        android:id="@+id/crear_turno_tv_abreviatura"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/crear_turno_tv_abreviatura"
        app:layout_constraintStart_toEndOf="@+id/crear_turno_linearvisorparent"
        app:layout_constraintTop_toBottomOf="@+id/crear_turno_itemturno" />

    <EditText
        android:id="@+id/crear_turno_etx_abreviatura"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="4dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:maxLength="1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toEndOf="@+id/crear_turno_tv_abreviatura"
        app:layout_constraintTop_toBottomOf="@+id/crear_turno_itemturno" />

    <EditText
        android:id="@+id/crear_turno_etx_comentario"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="4dp"
        android:layout_marginEnd="8dp"
        android:ems="10"
        android:hint="..."
        android:inputType="textMultiLine|textPersonName"
        android:lines="4"
        android:maxLines="6"
        android:minLines="3"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/crear_turno_linearvisorparent"
        app:layout_constraintTop_toBottomOf="@+id/crear_turno_tv_comentario" />

    <EditText
        android:id="@+id/crear_turno_etx_horacomienzo2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="4dp"
        android:layout_marginEnd="8dp"
        android:ems="10"
        android:hint="08:00"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toEndOf="@+id/crear_turno_tv_horacomienzo"
        app:layout_constraintTop_toBottomOf="@+id/crear_turno_etx_horasturno" />

    <TextView
        android:id="@+id/crear_turno_tv_horacomienzo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="28dp"
        android:text="@string/crear_turno_tv_horacomienzo"
        app:layout_constraintStart_toEndOf="@+id/crear_turno_linearvisorparent"
        app:layout_constraintTop_toBottomOf="@+id/crear_turno_tv_horasturno" />

    <LinearLayout
        android:id="@+id/crear_turno_itemturno"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="80dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="80dp"
        android:weightSum="1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/crear_turno_bti_agregarturno"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/item_turno_tv_letraturno"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:maxLength="1"
            android:paddingLeft="12sp"
            android:paddingTop="6sp"
            android:paddingRight="12sp"
            android:paddingBottom="6sp"
            android:text="M"
            android:textAlignment="center"
            android:textSize="32sp"
            android:textStyle="bold" />
    </LinearLayout>

    <Button
        android:id="@+id/crear_turno_bt_colortexto"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="@string/crear_turno_tv_colortexto"
        app:layout_constraintEnd_toStartOf="@+id/crear_turno_bt_colorfondo"
        app:layout_constraintStart_toEndOf="@+id/crear_turno_linearvisorparent"
        app:layout_constraintTop_toBottomOf="@+id/crear_turno_etx_comentario" />

    <ImageButton
        android:id="@+id/crear_turno_bti_agregarturno"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:src="@android:drawable/ic_media_rew"
        app:layout_constraintStart_toEndOf="@+id/crear_turno_linearvisorparent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Class that make the work:
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import androidx.appcompat.widget.AppCompatTextView;

import androidx.fragment.app.Fragment;

import com.azeesoft.lib.colorpicker.ColorPickerDialog;
import com.tron.miturno.utilidades.myTools;
import com.tron.miturno.vistas_personalizadas.vistaTurno;

import java.util.ArrayList;
import java.util.Date;

/**
 * A simple {@link Fragment} subclass.
 */
public class CrearTurno extends Fragment implements View.OnClickListener {

    /**
     * Una forma de pasar valores a un fragment antes de que se inicialice
     * En este caso no paso nada.
     *
     * @return
     */
    public static CrearTurno NewInstance() {
        CrearTurno edf = new CrearTurno();
        // edf.setLstDiasDelMes(listaDias);
        return edf;
    }

    public CrearTurno() {
        // Required empty public constructor
    }

    private static int ColorFondoSeleccionado, ColorTextoSeleccionado;
    private AppCompatTextView tvMuestraAbreviatura;
    private LinearLayout linearMuestraFondo;
    private Button btColorTexto, btColorFondo;
    private ImageButton btiAgregaTurno;
    private EditText etxEditAbreviatura, etxEditHoras, etxEditHoraComienzo, etxEditNotas;

    private RecyclerView recyclerView;
    private listaTurnosAdapter listaTurnosAdapter;
    private ArrayList<Turno> listaTurnos = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_crear_turno, container, false);

        recyclerView = view.findViewById(R.id.crear_turno_recyclerturnos);

        tvMuestraAbreviatura = view.findViewById(R.id.item_turno_tv_letraturno);
        tvMuestraAbreviatura.setTextColor(getResources().getColor(R.color.blanco));
        linearMuestraFondo = view.findViewById(R.id.item_turno_linearfondo);
        linearMuestraFondo.setBackgroundColor(getResources().getColor(R.color.marron));

        ColorFondoSeleccionado = getResources().getColor(R.color.marron);
        ColorTextoSeleccionado = getResources().getColor(R.color.blanco);

        btColorTexto = view.findViewById(R.id.crear_turno_bt_colortexto);
        btColorFondo = view.findViewById(R.id.crear_turno_bt_colorfondo);
        btiAgregaTurno = view.findViewById(R.id.crear_turno_bti_agregarturno);
        etxEditAbreviatura = view.findViewById(R.id.crear_turno_etx_abreviatura);
        etxEditAbreviatura.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count < 1) return;
                tvMuestraAbreviatura.setText(s.toString().substring(0, 1).toUpperCase());
                etxEditAbreviatura.setText("");
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        etxEditHoras = view.findViewById(R.id.crear_turno_etx_horasturno);
        etxEditHoraComienzo = view.findViewById(R.id.crear_turno_etx_horacomienzo2);
        etxEditNotas = view.findViewById(R.id.crear_turno_etx_comentario);

        linearMuestraFondo.setOnClickListener(this);
        btiAgregaTurno.setOnClickListener(this);
        btColorTexto.setOnClickListener(this);
        btColorFondo.setOnClickListener(this);

        listaTurnosAdapter = new listaTurnosAdapter(getActivity(), listaTurnos);
        recyclerView.setAdapter(listaTurnosAdapter);

        return view;
    }

    private void mostrarColorPicked(final boolean colorLetra) {
        /*****************************************************************************************
         * https://android-arsenal.com/details/1/3143   Para ver detalles del colorpicker
         ****************************************************************************************/

        ColorPickerDialog colorPickerDialog =
                ColorPickerDialog.createColorPickerDialog(getActivity(), ColorPickerDialog.DARK_THEME);
        colorPickerDialog.setInitialColor(R.color.blanco);
        colorPickerDialog.hideOpacityBar();
        colorPickerDialog.hideHexaDecimalValue();
        colorPickerDialog.setOnColorPickedListener(new ColorPickerDialog.OnColorPickedListener() {
            @Override
            public void onColorPicked(int color, String hexVal) {
                if (colorLetra) {
                    ColorTextoSeleccionado = color;
                    tvMuestraAbreviatura.setTextColor(color);
                } else {
                    ColorFondoSeleccionado = color;
                    linearMuestraFondo.setBackgroundColor(color);
                }
            }
        });
        colorPickerDialog.show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.crear_turno_bt_colortexto:
                mostrarColorPicked(true);
                break;
            case R.id.crear_turno_bt_colorfondo:
                mostrarColorPicked(false);
                break;
            case R.id.crear_turno_bti_agregarturno:
                agregarTurnoAlVisor();
                break;
            case R.id.item_turno_linearfondo:
                // Si presiono sobre el turno de muestra, se añade al visor de turnos
                agregarTurnoAlVisor();
                break;
        }
    }

    private void agregarTurnoAlVisor() {
        //////  HSCE FALTA CHEQUEAR LOS EDITTEXT Y DEMAS CAMPOS PARA QUE TENGAN VALORES OK
        /***** TEST ONLY ******/
        etxEditHoras.setText("6");
        etxEditHoraComienzo.setText(myTools.convertDateToTimeString(new Date()));
        /**** TEST ONLY ******/
        Turno turno = new Turno();
        turno.setColorFondo(ColorFondoSeleccionado);
        turno.setColorTexto(ColorTextoSeleccionado);
        turno.setAbreviatura(tvMuestraAbreviatura.getText().toString());

        int nh = Integer.parseInt(etxEditHoras.getText().toString());
        turno.setNumHoras(nh);
        Date horaCom = myTools.convertStringTimeToDate(etxEditHoraComienzo.getText().toString());
        turno.setHoraComienzo(horaCom);
        turno.setNotaTurno(etxEditNotas.getText().toString() + "");

        listaTurnos.add(turno);
        listaTurnosAdapter.notifyData(listaTurnos);

    }

    private class adapterRecycler extends RecyclerView.Adapter<adapterRecycler.vistaTurnoHolder>{

        @NonNull
        @Override
        public adapterRecycler.vistaTurnoHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return null;
        }

        @Override
        public void onBindViewHolder(@NonNull vistaTurnoHolder holder, int position) {

        }

        @Override
        public int getItemCount() {
            return 0;
        }

        class vistaTurnoHolder extends RecyclerView.ViewHolder {

            public AppCompatTextView txvLetra;
             adapterRecycler mAdapter;

            public vistaTurnoHolder(@NonNull View itemView, AppCompatTextView txvLetra, adapterRecycler mAdapter) {
                super(itemView);
                this.txvLetra = txvLetra;
                this.mAdapter = mAdapter;
            }

            public vistaTurnoHolder(@NonNull View itemView) {
                super(itemView);
            }
        }
    }

    /******************************************************************************************
     ******************************************************************************************
     ***
     ***                      CLASE DEL ADAPTADOR PARA EL LIST VIEW
     ***
     ******************************************************************************************
     ******************************************************************************************/
    private class adaptador extends BaseAdapter {

        private Context context;
        private ArrayList<vistaTurno> listaVistaTurnos=new ArrayList<>();
        private ArrayList<Turno> listaTurnos;
        private CrearTurno listener;

        /**
         * Adaptador para mostrar en el ListView los items añadidos
         * listenerForOnClickItem es la propia clase que crea el adaptador, que debe implementar
         * View.OnCLickListener
         *
         * @param context
         * @param lista
         * @param listenerForOnClickItem
         */
        public adaptador(Context context, ArrayList<Turno> lista, CrearTurno listenerForOnClickItem) {
            this.context = context;
            this.listaTurnos = lista;
            this.listener = listenerForOnClickItem;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Turno turno = listaTurnos.get(i);
            if (turno != null)
                listaVistaTurnos.remove(turno);

            vistaTurno vTurno = new vistaTurno(turno, context);
            //Consigo que al pulsarsobre un vista se active onclick en la clase
            vTurno.setOnClickListener(this.listener);
            listaVistaTurnos.add(vTurno);

            return vTurno;
        }

        @Override
        public int getCount() {
            int n = listaTurnos.size();
            return n;
        }

        @Override
        public Object getItem(int i) {
            return listaTurnos.get(i);
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        public vistaTurno getTurno(int i) {
            return listaVistaTurnos.get(i);
        }
    }
}

A: Try using RecyclerView for your list. It's more optimized for storing lists. Check this codelab for the detailed instructions on how to implement and use it.


text:
Q: How to run Android Unit Test classes in a specific order? Is there a way to execute Android Unit Test classes in a specific order? I am not talking about test methods within a given test, this I know how to accomplish, but I have several .java classes with each having several test methods inside and I would like to run those classes in a specific sequence, as they depend on each other due API calls and CRUD operations.
I know Unit Tests shall not depend on each other but in my case I would need to reset the server DB and the App DB programmatically before each test, which is rather tricky to accomplish in my current configuration.
I would also not want to aggregate all my test methods into a single .java file and execute them with @FixMethodOrder, because then I will end up with an unmanageable chunk of test methods.


text:
Q: Function with rapidjson::Value& parameter wants an allocator when called I have a similar issue as an earlier question (see Parsing object inside array in rapidjson ) where I am writing a recursive function to walk an arbitrary JSON tree, and I tried the suggested answer, but my C++ compiler does not like it.
I have declared the function
void traverseObject(const Value& v) {
    if (v.IsObject()) {
       // . . .
    }
    else if (v.IsArray()) {
       // . . .
    }
}

As you suggested (for the sake of clarity, I have left out some namespace syntax that my implementation must use).  However, when calling it recursively with a Value::ConstMemberIterator itr as
traverseObject(itr->value);

or with a Value::ConstValueIterator itr as
traverseObject(*itr);

my C++ compiler generates the error
Invalid arguments ' Candidates are: void traverseObject(rapidjson::GenericValue<rapidjson::UTF8<char>,rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>> &) '

I admit to being new to C++ (most of my OOP experience is with Java), so I am simultaneously climbing more than one learning curve here.  Why does this function require that I call it with an allocator if I am just calling it with an object by reference?  I also looked though the RapidJSON docs and none of the examples mention the use of an allocator with method calls, so I am probably missing something basic here due to my C++ newbie-ness, but any suggestions would be helpful.
If it helps, I am using the Eclipse C++ Development Toolkit and the MinGW compiler on Windows 7.  This combination has been painful in other ways which I will not go into here, but I really like Eclipse's code analysis and refactoring tools.  I am open to using other IDEs which offer comparable features.
Thanks very much for your help.
Eric


text:
Q: EAC & FLAC: The cue sheet can be applied to which file? I just encoded a CD to FLAC with the help of EAC (Exact Audio Copy) and I was wondering if the cue sheet can be used for the .wav file only or for the .flac file to? The CD is encoded into a single FLAC file; an full image of the CD. My goal is to only save the FLAC image, cue sheet and .log file for backup purposes.

A: EAC would likely have produced the CUE sheet for the FLAC file only. However, if you edit the CUE sheet in a text editor (e.g. Notepad) and change the file name near the top from filename.flac to filename.wav, you can save it as a second CUE sheet which will work with the WAV file.


text:
Q: Ionic 2 Storage - store maps instead of arrays Since I need offline functionality in my Ionic 2 app and dealing with lots of data, I heavily rely on Storage.
I used to put my objects in maps like
public hashtags:Map<any,Hashtag> = new Map<any,Hashtag>();
...
this.hashtags.set(hashtag.id,hashtag)

stored it like
this.storage.set("hashtags",this.hashtags).then(()=>{
    console.log("stored hashtags");
})

and retrieve it like
this.storage.get("hashtags").then(data => {
    console.log("retrieved hashtags", data);
    this.hashtags = data;
})

On newer devices (Android > 4.4?), this works fine, but on older ones I get [object object] when retrieving the data. It seems that there, objects are saved as strings and cannot be converted back to maps anymore (the driver was asyncStorage).
I have seen that some people store at least arrays in the same way and it seems to work, but since I have a lot of relational data, I would prefer to stick to maps to avoid looping through the arrays for a particular object.
Is there a reliable way to store maps using Storage(2.0.0)? What could be alternatives, if not?
In case of falling back to arrays, what happens to nested objects or arrays of nested objects? like
users:User[] = [new User(1),new User(2)]
let hashtags = [];
hashtags.push(new Hashtag(id,text, users,...))
this.storage.set("hashtags",hashtags)

Thanks!


text:
Q: How to get correct current video settings for DJI Drone using DJI Android SDK I need to get the currently set video resolution for the camera live stream on a DJI Drone. I have attempted to get it through DJICodecManager, however it returns inconsistent results.
val codecManager = DJICodecManager(
      this@MainActivity,
      null,
      0,
      0,
      UsbAccessoryService.VideoStreamSource.Camera
)

val width = codecManager.videoWidth
val height = codecManager.videoHeight

Sometimes the videoWidth and videoHeight values return the aspect ratio values (16 and 9) and sometimes it returns the video width and height correctly (1280 and 720).
I haven't found any other way in the documentation. Does anyone know a reliable way to get the currently set video height and width values from a DJI drone?
Thanks.
eg.

A: You have to give more info. Is it the livestream you're after or do you want to change the recorded resolution?
You have to send data to the codec with sendDataToDecoder().
Have a look at the dji example on github.


text:
Q: Which Year's Best Science Fiction contained Cilia of Gold, The Remoras What year's best science fiction had the story Cilia of Gold, Remoras on the outside of an immense interstellar travelling planetoid, and a dormant alien who arrives on Earth and mistakes smiling humans as agressors and activates a destructive force?

A: Since you know it has Cilia of Gold & 'Remoras on the outside of an immense interstellar traveling planetoid', AND it's a Year's Best SciFi, I think I can conclusively say its:
The Year's Best Science Fiction Twelfth Annual Collection from 1995, since two of the stories are named Cilia of Gold and Remoras.
I'm not sure of the last story, but hopefully the story names will give it to you.
Stealing from Wikipedia, here's the list of Authors & Stories:

*

*Ursula K. Le Guin:"Forgiveness Day"

*Robert Reed:"The Remoras"

*Maureen F. McHugh:"Nekropolis"

*Nancy Kress:"Margin of Error"

*Stephen Baxter:"Cilia-of-gold"

*William Sanders:"Going After Old Man Alabama"

*Michael F. Flynn:"Melodies of the Heart"

*Terry Bisson:"The Hole in the Hole"

*Pat Cadigan:"Paris In June"

*George Turner:"Flowering Mandrake"

*Joe Haldeman:"None So Blind"

*Greg Egan:"Cocoon"

*Mike Resnick:"Seven Views of Olduvai Gorge"

*Geoff Ryman:"Dead Space for the Unexpected"

*Michael Bishop:"Cri de Coeur"

*Howard Waldrop:"The Sawing Boys"

*Ursula K. Le Guin:"The Matter of Seggri"

*Eliot Fintushel:"Ylem"

*Katherine Kerr:"Asylum"

*Walter Jon Williams:"Red Elvis"

*Mary Rosenblum:"California Dreamer"

*Lisa Goldstein:"Split Light"

*Brian Stableford:"Les Fleurs du Mal"


text:
Q: How exactly does tail recursion work? I almost understand how tail recursion works and the difference between it and a normal recursion. I only don't understand why it doesn't require stack to remember its return address.
// tail recursion
int fac_times (int n, int acc) {
    if (n == 0) return acc;
    else return fac_times(n - 1, acc * n);
}

int factorial (int n) {
    return fac_times (n, 1);
}

// normal recursion
int factorial (int n) {
    if (n == 0) return 1;
    else return n * factorial(n - 1);
}

There is nothing to do after calling a function itself in a tail recursion function but it doesn't make sense for me.

A: Here is a simple example that shows how recursive functions work:
long f (long n)
{

    if (n == 0) // have we reached the bottom of the ocean ?
        return 0;

    // code executed in the descendence

    return f(n-1) + 1; // recurrence

    // code executed in the ascendence

}

Tail recursion is a simple recursive function, where recurrence is done at the end of the function, thus no code is done in ascendence, which helps most compilers of high-level programming languages to do what is known as Tail Recursion Optimization, also has a more complex optimization known as the Tail recursion modulo

A: You ask why "it doesn't require stack to remember its return address".
I would like to turn this around. It does use the stack to remember the return address. The trick is that the function in which the tail recursion occurs has its own return address on the stack, and when it jumps to the called function, it will treat this as it's own return address.
Concretely, without tail call optimization:
f: ...
   CALL g
   RET
g:
   ...
   RET

In this case, when g is called, the stack will look like:
   SP ->  Return address of "g"
          Return address of "f"

On the other hand, with tail call optimization:
f: ...
   JUMP g
g:
   ...
   RET

In this case, when g is called, the stack will look like:
   SP ->  Return address of "f"

Clearly, when g returns, it will return to the location where f was called from.
EDIT: The example above use the case where one function calls another function. The mechanism is identical when the function calls itself.

A: The recursive function is a function which calls by itself
It allows programmers to write efficient programs using a minimal amount of code.
The downside is that they can cause infinite loops and other unexpected results if not written properly.
I will explain both Simple Recursive function and Tail Recursive function
In order to write a Simple recursive function

*

*The first point to consider is when should you decide on coming out
of the loop which is the if loop

*The second is what process to do if we are our own function
From the given example:
public static int fact(int n){
  if(n <=1)
     return 1;
  else
     return n * fact(n-1);
}

From the above example
if(n <=1)
     return 1;

Is the deciding factor when to exit the loop
else
     return n * fact(n-1);

Is the actual processing to be done
Let me the break the task one by one for easy understanding.
Let us see what happens internally if I run fact(4)

*

*Substituting n=4
public static int fact(4){
  if(4 <=1)
     return 1;
  else
     return 4 * fact(4-1);
}

If loop fails so it goes to else loop
so it returns 4 * fact(3)

*In stack memory, we have 4 * fact(3)
Substituting n=3
public static int fact(3){
  if(3 <=1)
     return 1;
  else
     return 3 * fact(3-1);
}

If loop fails so it goes to else loop
so it returns 3 * fact(2)
Remember we called ```4 * fact(3)``
The output for fact(3) = 3 * fact(2)
So far the stack has 4 * fact(3) = 4 * 3 * fact(2)

*In stack memory, we have 4 * 3 * fact(2)
Substituting n=2
public static int fact(2){
  if(2 <=1)
     return 1;
  else
     return 2 * fact(2-1);
}

If loop fails so it goes to else loop
so it returns 2 * fact(1)
Remember we called 4 * 3 * fact(2)
The output for fact(2) = 2 * fact(1)
So far the stack has 4 * 3 * fact(2) = 4 * 3 * 2 * fact(1)

*In stack memory, we have 4 * 3 * 2 * fact(1)
Substituting n=1
public static int fact(1){
  if(1 <=1)
     return 1;
  else
     return 1 * fact(1-1);
}

If loop is true
so it returns 1
Remember we called 4 * 3 * 2 * fact(1)
The output for fact(1) = 1
So far the stack has 4 * 3 * 2 * fact(1) = 4 * 3 * 2 * 1
Finally, the result of fact(4) = 4 * 3 * 2 * 1 = 24

The Tail Recursion would be
public static int fact(x, running_total=1) {
    if (x==1) {
        return running_total;
    } else {
        return fact(x-1, running_total*x);
    }
}

*

*Substituting n=4
public static int fact(4, running_total=1) {
    if (x==1) {
        return running_total;
    } else {
        return fact(4-1, running_total*4);
    }
}

If loop fails so it goes to else loop
so it returns fact(3, 4)

*In stack memory, we have fact(3, 4)
Substituting n=3
public static int fact(3, running_total=4) {
    if (x==1) {
        return running_total;
    } else {
        return fact(3-1, 4*3);
    }
}

If loop fails so it goes to else loop
so it returns fact(2, 12)

*In stack memory, we have fact(2, 12)
Substituting n=2
public static int fact(2, running_total=12) {
    if (x==1) {
        return running_total;
    } else {
        return fact(2-1, 12*2);
    }
}

If loop fails so it goes to else loop
so it returns fact(1, 24)

*In stack memory, we have fact(1, 24)
Substituting n=1
public static int fact(1, running_total=24) {
    if (x==1) {
        return running_total;
    } else {
        return fact(1-1, 24*1);
    }
}

If loop is true
so it returns running_total
The output for running_total = 24
Finally, the result of fact(4,1) = 24

A: The compiler is simply able to transform this
int fac_times (int n, int acc) {
    if (n == 0) return acc;
    else return fac_times(n - 1, acc * n);
}

into something like this:
int fac_times (int n, int acc) {
label:
    if (n == 0) return acc;
    acc *= n--;
    goto label;
}

A: Tail recursion can usually be transformed into a loop by the compiler, especially when accumulators are used.
// tail recursion
int fac_times (int n, int acc = 1) {
    if (n == 0) return acc;
    else return fac_times(n - 1, acc * n);
}

would compile to something like
// accumulator
int fac_times (int n) {
    int acc = 1;
    while (n > 0) {
        acc *= n;
        n -= 1;
    }
    return acc;
}

A: There are two elements that must be present in a recursive function:

*

*The recursive call

*A place to keep count of the return values.

A "regular" recursive function keeps (2) in the stack frame.
The return values in regular recursive function are composed of two types of values:

*

*Other return values

*Result of the owns function computation

Let's look at your example:
int factorial (int n) {
    if (n == 0) return 1;
    else return n * factorial(n - 1);
}

The frame f(5) "stores" the result of it's own computation (5) and the value of f(4), for example. If i call factorial(5), just before the stack calls begin to collapse, i have:
 [Stack_f(5): return 5 * [Stack_f(4): 4 * [Stack_f(3): 3 * ... [1[1]]

Notice that each stack stores, besides the values i mentioned, the whole scope of the function. So, the memory usage for a recursive function f is O(x), where x is the number of recursive calls i have to made. So, if i needb 1kb of RAM to calculate factorial(1) or factorial(2), i need ~100k to calculate factorial(100), and so on.
A Tail Recursive function put (2) in it's arguments.
In a Tail Recursion, i pass the result of the partial calculations in each recursive frame to the next one using parameters. Let's see our factorial example, Tail Recursive:
int factorial (int n) {
    int helper(int num, int accumulated)
        {
            if num == 0 return accumulated
            else return helper(num - 1, accumulated*num)
        }
    return helper(n, 1)
}

Let's look at it's frames in factorial(4):
[Stack f(4, 5): Stack f(3, 20): [Stack f(2,60): [Stack f(1, 120): 120]]]]

See the differences? In "regular" recursive calls the return functions recursively compose the final value. In Tail Recursion they only reference the base case (last one evaluated). We call accumulator the argument that keeps track of the older values.
Recursion Templates
The regular recursive function go as follows:
type regular(n)
    base_case
    computation
    return (result of computation) combined with (regular(n towards base case))

To transform it in a Tail recursion we:

*

*Introduce a helper function that carries the accumulator

*run the helper function inside the main function, with the accumulator set to the base case.

Look:
type tail(n):
    type helper(n, accumulator):
        if n == base case
            return accumulator
        computation
        accumulator = computation combined with accumulator
        return helper(n towards base case, accumulator)
    helper(n, base case)

See the difference?
Tail Call optimization
Since no state is being stored on the Non-Border-Cases of the Tail Call stacks, they aren't so important. Some languages/interpreters then substitute the old stack with the new one. So, with no stack frames constraining the number of calls, the Tail Calls behave just like a for-loop in these cases.
It's up to your compiler to optimize it, or no.

A: My answer is more of a guess, because recursion is something relating to internal implementation.
In tail recursion, the recursive function is called at the end of the same function. Probably compiler can optimize in below way:

*

*Let the ongoing function wind up (i.e. used stack is recalled)

*Store the variables which are going to be used as arguments to the function in a temporary storage

*After this, call the function again  with the temporarily stored argument

As you can see, we are winding up the original function before the next iteration of the same function, so we are not actually "using" the stack.
But I believe if there are destructors to be called inside the function then this optimization may not apply.

A: Compiler is enough intelligent to understand tail recursion.In case, while returning back from a recursive call,there is no pending operation and recursive call is the last statement, fall under the category of tail recursion.
Compiler basically performs tail recursion optimization, removing stack implementation.Consider below code.
void tail(int i) {
    if(i<=0) return;
    else {
     system.out.print(i+"");
     tail(i-1);
    }
   }

After performing optimization , the above code is converted into below one.
void tail(int i) {
    blockToJump:{
    if(i<=0) return;
    else {
     system.out.print(i+"");
     i=i-1;
     continue blockToJump;  //jump to the bolckToJump
    }
    }
   }

This is how compiler does Tail Recursion Optimization.


text:
Q: Improper integral confusing step The following passage is in my textbook:

$$A(S) = \int_0^{\infty} f(E) \max(S-E,0)dE$$
This simplifies to $$A(S) = \int_0^{S} f(E)(S-E) dE$$

Now this is from a finance textbook so it might not be fully rigorous, but I'm curious about what happens with the integral. I think this is an improper integral, and I haven't really studied those yet, but after reading up on them I'm still confused as to what is done here and why it's allowed.

A: This is because $\max(S - E, 0) = 0$ for $E \geq S$.  Alternatively, it is equal to $S - E$ for $E \leq S$.


text:
Q: MiKTeX update error (Windows API error 32): MiKTeX console already in use I just downloaded MiKTeX with the goal of using TeXstudio. My laptop is running Windows 10 Pro.
After installing MiKTex 2.9.6942, when I try to install updates using the MiKTeX Console (as per the instructions on their website), I get an error saying that the file 'miktex-console.exe' is in use and that I need to close running MiKTeX programs and try again. Of course, I'm using the console to run my updates, so that's why the file is in use.
Details included below. Does anyone have any ideas for how to get around this?
None of the previous posts I've found address the same problem.
Main error message:

Something went wrong while installing package updates.
MiKTeX could not remove the file
'C:\Users\myname\AppData\Local\Programs\MiKTeX
2.9\miktex\bin\x64\miktex-console.exe'.
Remedy: Close running MiKTeX programs and try again.
For more information, visit https://miktex.org/kb/fix-file-in-use.

Error report:

GENERAL MIKTEX INFORMATION
Date: 2019-02-19 00:10:04
MiKTeX: 2.9.6930
OS: Windows 10 Pro, 64-bit, build 17134
SharedSetup: no
PathOkay: yes
LastUpdateCheck: 2019-02-19 00:00:53
LastUpdate: not yet
SystemAdmin: yes
RootPrivileges: no
AdminMode: no
Root0: C:\Users\myname\AppData\Roaming\MiKTeX\2.9
Root1: C:\Users\myname\AppData\Local\MiKTeX\2.9
Root2: C:\Users\myname\AppData\Local\Programs\MiKTeX 2.9
Root3: C:\ProgramData\MiKTeX\2.9
Root4: C:\Program Files\MiKTeX 2.9
UserInstall: C:\Users\myname\AppData\Local\Programs\MiKTeX 2.9
UserConfig: C:\Users\myname\AppData\Roaming\MiKTeX\2.9
UserData: C:\Users\myname\AppData\Local\MiKTeX\2.9     `
CommonInstall: C:\Program Files\MiKTeX 2.9
CommonConfig: C:\ProgramData\MiKTeX\2.9
CommonData: C:\ProgramData\MiKTeX\2.9
Invokers: non-existing/explorer
Warning: the following problems were detected:
1: installation is not up-to-date
ERROR DETAILS
Program: C:\Users\myname\AppData\Local\Programs\MiKTeX 2.9\miktex\bin\x64\miktex-console.exe
Source: Libraries\MiKTeX\Core\File\win\winFile.cpp:321
Error: Windows API error 32: The process cannot access the file because it is being used by another process.
Description: MiKTeX could not remove the file 'C:\Users\myname\AppData\Local\Programs\MiKTeX 2.9\miktex\bin\x64\miktex-console.exe'.
Remedy: Close running MiKTeX programs and try again.
Details:
path: C:\Users\myname\AppData\Local\Programs\MiKTeX 2.9\miktex\bin\x64\miktex-console.exe

A: Most likely cause is a dead console session in memory or the editor /viewer is stuck in some update loop.
Next most likely cause can be interference by antivirus or other systems monitors.
That good old advice still stands Have you tried pressing the off key at the wall (joke)
Seriously, a reboot should kill any duplicate sessions. Then on start-up DO NOT run anything other than MiKTeX-console, try at first to run without elevation to admin rights, since in this case you are using a basic install and try again.
IF message is still the same again, then you need to go to MiKTeX support site to check if there are others with similar issues (open or closed) and if not then open a fresh one.
https://github.com/MiKTeX/miktex/issues


text:
Q: plugin java version and project java version I am writing an eclipse plugin, compatible to java 1.5.
If anybody who is working with java 1.5 or lower or higher, installs this plugin, will it work well?

A: You should included a Bundle-RequiredExecutionEnvironment: J2SE-1.5 statement in your plugin MANIFEST.MF if you are targetting java 1.5.  That is both documentation and a note to the OSGi runtime about what is valid within that bundle.

A: No. It won't work on lower versions if you are using java 1.5 specific library calls which are not available in lower versions.

A: It depends on what functions your plugin uses. Certain functions are eventually marked as deprecated and are dropped in future releases, this can cause issues when newer versions of Java will run your code.
On the other hand, new functions tend to be added from one version to the next, so in your case, older versions might crash since some functions your application uses simply do not exist.
At most, what you can do is to specify a minimum Java version, and eventually even this can cause problems.


text:
Q: Discrepancies with $_item->getFreeShipping() - can't find whether order item had free shipping I have a script which runs through order items.
I also set up a Shopping Cart Promotional Rule for Free Shipping on certain items 'For matching items only' which I've matched by SKU in the Actions tab.
I know this rule is working because I have a custom shipping module and when calculating the shipping costs via this module the function $_item->getFreeShipping below returns 1 if the rule has applied free shipping to the item. There are no problems with this as far as I can see:
// Looping through items in checkout to calculate shipping cost to apply.
foreach ($request->getAllItems() as $_item) {
    ...
    // returns 1 for the product in question
    $_item->getFreeShipping();
    ...
}

So the above is for the items in the shipping quote.
However, after I have gone through checkout, placed the order (using Check/Money order), and invoiced the order (manually in admin panel), when I loop through the order items of the order, the $_item->getFreeShipping call is returning 0 for all items (even those that were returning 1 when calculating shipping costs)
foreach ($order->getAllItems() as $_item ) {
    ...
    // returns 0 for the product in question (and all other products)
    $_item->getFreeShipping();
    ...
}

I'm currently working with a fresh install of CE 1.7.0.2. No third party modules apart from my custom shipping module, but this only adds some custom shipping methods that calculate shipping costs based off units ordered, with some custom logic.
I need a way of getting whether the order item had free shipping when it was placed - the script is for sending an order feed to a distributor, and I need to send them the shipping cost for the order. In some cases it's more complicated than using $_order->getShippingAmount as some orders will need to be separated into separate shipments, so the effective shipping cost needs to be recalculated for each order item.
Please note for these orders I am not using the "Free Shipping" Shipping Method, just a Free Shipping Promotional Rule - might that be where the discrepancy lies?
Can anyone shed any light? Thanks in advance.


text:
Q: How do call a method inside a component in OctoberCMS? I don't know if this is possible or if it's a complete madness but I'm trying to execute a PHP method from AJAX call using OctoberCMS Ajax Framework(I assume that this uses jQuery behind it) and is not working because I never get redirect to PayPal site. The PHP code I'm trying to get working is this one:
protected function onExecutePurchaseMethod()
{
    Omnipay::gateway('PayPal_Express');

    $params = [
        'username'  => $this->username,
        'password'  => $this->password,
        'signature' => $this->signature,
        'testMode'  => $this->sandboxMode,
        'amount'    => Session::get('amountToReload'),
        'cancelUrl' => url( 'payment/step4', "", $secure = null ),
        'returnUrl' => url( 'payment/step2', "", $secure = null ),
        'currency'  => 'USD'
    ];

    $response = Omnipay::purchase($params)->send();

    if ($response->isSuccessful()) {
        var_dump($response);
    } else {
        var_dump($response->getMessage());
    }
}

What is happening since none redirect to PayPal is executed and page is getting stuck many times forcing me to close the browser and reopen again, no method is executed and no visible errors. It's possible to do what I'm trying to do? Is not a madness? If it's possible where is my error?
As extra info I'm using Barryvdh Laravel-omnipay package for handle Omnipay from within Laravel.

A: After looking briefly through the documentation, my best guess is that you're missing a required field for the purchase() method. I believe you need a card parameter (even if it's an invalid one) to get it to process.


text:
Q: Abbreviations for loss functions to be passed to model.compile()? Here describes different loss functions, but it is possible to use abbreviations instead of importing and passing the actual loss object (see an examples here)
MeanSquaredError can be passed as the string mse, MeanAbsoluteError as mae. Some are obvious like that, but what about other losses like CategoricalCrossentropy, CosineSimilarity, or Hinge?

A: Here are some loss functions and their string aliases (All of them can be imported from tf.keras.losses):

Class Name
String Alias(es)

MeanSquaredError()
mean_squared_error, mse, MSE

MeanAbsoluteError()
mean_absolute_error, mae, MAE

MeanAbsolutePercentageError()
mean_absolute_percentage_error, mape, MAPE

MeanSquaredLogarithmicError()
mean_squared_logarithmic_error, msle, MSLE

KLDivergence()
kl_divergence, kullback_leibler_divergence, kld, KLD

Hinge()
hinge

CosineSimilarity()
cosine_similarity

LogCosh()
log_cosh, logcosh

CategoricalCrossentropy()
categorical_crossentropy

SparseCategoricalCrossentropy()
sparse_categorical_crossentropy

BinaryCrossentropy()
binary_crossentropy

As you can see, some of them have more than one string alias, whereas mostly have one alias.
Reference: Source code of keras.losses


text:
Q: Compare two datasets and place the unique values in another dataset I have two datasets one is holding the data from excel sheet and another is from database
now i need to compare the datasets and place the unique values from excel grid to another dataset


text:
Q: Issue with user-defined function for descriptive statistics from imputed data I am trying to write a function that will calculate the mean and SD for a variable from a multiply imputed dataframe (mids). The code works fine outside of the function (as shown in two examples below), but will produce unreliable results when placed inside of a function. The function seems to keep giving results for bmi despite calling upon chl.
Any insight into this issue is appreciated. Eventually I would like this function to be able to calculate means and SDs for multiple variables at once (i.e., bmi and chl) but that is likely a separate question.
library(mice, warn.conflicts = FALSE)
data(nhanes)
imp <- mice(nhanes, m = 3, print = FALSE, seed = 123)

# workflow that i want to automate
# from here: https://bookdown.org/mwheymans/bookmi/data-analysis-after-multiple-imputation.html
# example 1 - bmi
impdat <- mice::complete(imp, action = "long", include = FALSE)
pool_mean <- with(impdat, by(impdat, .imp, function(x) c(mean(x$bmi), sd(x$bmi))))
result <- (Reduce("+", pool_mean)/length(pool_mean))
print(result)
#> [1] 27.117333  3.980506
rm(impdat, pool_mean, result)

# example 2 - chl
impdat <- mice::complete(imp, action = "long", include = FALSE)
pool_mean <- with(impdat, by(impdat, .imp, function(x) c(mean(x$chl), sd(x$chl))))
result <- (Reduce("+", pool_mean)/length(pool_mean))
print(result)
#> [1] 195.10667  39.95247
rm(impdat, pool_mean, result)

# automating the workflow
automate <- function(a, b) {
  impdat <- mice::complete(a, action = "long", include = FALSE)
  pool_mean <- with(impdat, by(impdat, .imp, function(x) c(mean(x$b), sd(x$b))))
  result <- (Reduce("+", pool_mean)/length(pool_mean))
  print(result)
}

automate(a=imp, b=bmi) # looks correct ... ?
#> [1] 27.117333  3.980506
automate(a=imp, b=chl) # no, it isn't
#> [1] 27.117333  3.980506

A: Two and a half problems here:

*

*b = bmi looks like an object bmi, which does not exist in our global environment. We can use deparse(susbtitute(x)) for this, to tell the function to wait with the evaluation.

*Accessor function $, see ?Extract: Both [[ and $ select a single element of the list. The main difference is that $ does not allow computed indices
automate <- function(a, b) {
  b <- deparse(substitute(b))
  impdat <- mice::complete(a, action = "long", include = FALSE)
  pool_mean <- with(impdat, by(impdat, .imp, function(x) c(mean(x[[b]]), sd(x[[b]]))))
  (Reduce("+", pool_mean)/length(pool_mean))
}
automate(a=imp, b=bmi)
[1] 27.117333  3.980506
automate(a=imp, b=chl)
[1] 195.10667  39.95247

To do this on a list of variables, we can rewrite it slightly to
automate_list <- function(a, ...){
  impdat <- mice::complete(a, action = "long", include = FALSE)
  lapply(list(...), function(x){
    x = as.name(x)
    pool_mean <- with(impdat, by(impdat, .imp, function(y) c(mean(y[[x]]), sd(y[[x]]))))
    Reduce("+", pool_mean)/length(pool_mean)
  }) |>
    setNames(list(...))
}

automate_list(imp, "bmi", "chl")
$bmi
[1] 27.117333  3.980506

$chl
[1] 195.10667  39.95247


text:
Q: making of list of clusters from `sklearn` cluster labels output sklearn's clustering outputs produce lists of labels (where the ith element will be labeled with the cluster it is in. Now, suppose I want a list of clusters. There is a fairly obvious way of doing that:
def clustarrays(labs):
    howmany = np.max(labs)+1
    results = [[] for i in range(howmany)]
    for i in range(len(labs)):
        cnum = labs[i]
        results[cnum].append(i)
    return results

ll = [1, 2, 3, 0, 0, 5, 5, 5]

clustarrays(ll)
[[3, 4], [0], [1], [2], [], [5, 6, 7]]

This is all very well and good, but this will be very slow for large datasets. Is there a more numpy-centric way of doing this?

A: If you want pure numpy use:
def clustarrays(labs):
    return np.split(np.argsort(labs),np.unique(labs,return_counts=True)[1].cumsum())

output:
[array([3, 4]), array([0]), array([1]), array([2]), array([5, 6, 7]), array([], dtype=int64)]

I would suggest pandas:
import pandas as pd
def clustarrays(labs):
  df = pd.DataFrame({'labs':labs})
  return df.groupby(df.labs).groups

output:
{0: Int64Index([3, 4], dtype='int64'), 1: Int64Index([0], dtype='int64'), 2: Int64Index([1], dtype='int64'), 3: Int64Index([2], dtype='int64'), 5: Int64Index([5, 6, 7], dtype='int64')}


text:
Q: force swagger to ask for basic http authentication with springfox I have web service that secure with spring security with basic http authentication.
when i was document it with swagger using springfox-swagger2 library
how can i force  swagger ui to ask for user name password

A: I am not sure why do you want to do that?
If you don't want to expose certain api's in swagger, use a PathSelector. If you don't want everyone to see your Api's, host your swagger ui on a specific server and share the details as per need. Not sure why you would want to add a http authentication.


text:
Q: Problem with #1's in DSolve I've entered the following functions into my notebook, but the solution to them contains #1's that I can't seem to make any sense of. The functions are:
z := R[r, t]
P := D[R[r, t], t]
eqn := P^2 - (2 x[r])/z - 2 y[r] == 0
sol = DSolve[eqn, z, t]

and the solution returns the following:
{
 {R[r, t] ->
  InverseFunction[-((Log[Sqrt[#1] y[r] + Sqrt[y[r]] Sqrt[x[r] + #1 y[r]]] x[r])/
    y[r]^(3/2)) + (Sqrt[#1] Sqrt[x[r] + #1 y[r]])/y[r] &][-Sqrt[2]t + C[1]]},
 {R[r, t] ->
  InverseFunction[-((Log[Sqrt[#1] y[r] + Sqrt[y[r]] Sqrt[x[r] + #1 y[r]]] x[r])/
    y[r]^(3/2)) + (Sqrt[#1] Sqrt[x[r] + #1 y[r]])/y[r] &][Sqrt[2] t + C[1]]}
}

Any thoughts on the matter?

A: InverseFunction
InverseFunction[f] yields a function that, given an argument y, gives a result x for which y==f[x] holds. That is to say:
f[x_] = x + x^2;
g = InverseFunction[f];

g[6]

-3

f[-3]

6

Take care here because, as always with inverse functions, it's not necessarily the case that $f^{-1}(f(x))=x$. Here, f maps both 2 and -3 to 6, but the inverse can take you back to only one value. Mathematica chose to map back to 3 in this case (and throws a warning message).
Pure functions
A pure function is specified in Mathematica using a Slot (#) and & syntax.
#^2+1&

In this example is a function with one argument. It squares its argument and adds 1. It can be used directly on an argument like so:
#^2 + 1 &[2]

5

or by first assigning it to a function name and then applying it to an argument:
h = #^2 + 1 &;
h[2]

5

Instead of plain Slot you can also use multiple arguments that are numbered like #1, #2, #3 etc.
m = #1/Cosh[#2] &;
m[5, 3]

5 Sech[3]

Pure functions can have inverses defined in the same way as above.
InverseFunction[#^2 &][2]

During evaluation of In[46]:= InverseFunction::ifun: Inverse functions are being used. Values may be lost for multivalued inverses. >>
-Sqrt[2]

The rather complex InverseFunction in the question
If we study the InverseFunction in the question:
InverseFunction[-((Log[Sqrt[#1] y[r] + Sqrt[y[r]] Sqrt[x[r] + #1 y[r]]] x[r])/
y[r]^(3/2)) + (Sqrt[#1] Sqrt[x[r] + #1 y[r]])/y[r] &][-Sqrt[2]t + C[1]]

You can see that it can be written as follows:
p = -((Log[Sqrt[#1] y[r] + Sqrt[y[r]] Sqrt[x[r] + #1 y[r]]] x[r])/
y[r]^(3/2)) + (Sqrt[#1] Sqrt[x[r] + #1 y[r]])/y[r] &;
q = -Sqrt[2]t + C[1]

p is admittedly a baroque beast, but it's just a pure function like the simple #^2 + 1 & above. It is a function of one argument (I only see #1's).
And with
r=InverseFunction[p]

the rule outputs of your DSolve are just
r[q],

The inverse function acting on the argument q, where C[1] is an unspecified constant that is part of the solution because no initial or boundary condition was given.


text:
Q: pywebsocket doesnt work This is how I've installed mod_pywebsocket as apache extension
root@senior:/var/www# wget http://pywebsocket.googlecode.com/files/mod_pywebsocket-0.7.8.tar.gz
root@senior:/var/www# tar xvf mod_pywebsocket-0.7.8.tar.gz
root@senior:/var/www# cd pywebsocket-0.7.8/src/
root@senior:/var/www/pywebsocket-0.7.8/src# py:/./setpuup.py build
running build
running build_py
root@senior:/var/www/pywebsocket-0.7.8/src# python ./setup.py install
running install
running build
running build_py
running install_lib
running install_egg_info
Removing /usr/local/lib/python2.6/dist-packages/mod_pywebsocket-0.7.8.egg-info
Writing /usr/local/lib/python2.6/dist-packages/mod_pywebsocket-0.7.8.egg-info
root@senior:/var/www/pywebsocket-0.7.8/src# mkdir /var/www/_wsh/
root@senior:/var/www/pywebsocket-0.7.8/src# cp example/* /var/www/_wsh/
root@senior:/var/www/pywebsocket-0.7.8/src# cd /var/www/_wsh/
root@senior:/var/www/_wsh# chmod a+x *.py
root@senior:/usr/local/lib/python2.6/dist-packages/mod_pywebsocket# cd /usr/local/lib/python2.6/dist-packages/mod_pywebsocket
root@senior:/usr/local/lib/python2.6/dist-packages/mod_pywebsocket# chmod a+rx *.py

Here is mine text inserted in httpd.conf
<IfModule python_module>
  PythonPath "sys.path+['/usr/local/lib/python2.6/dist-packages']"
  PythonOption mod_pywebsocket.handler_root /var/www/_wsh/
  PythonOption mod_pywebsocket.handler_scan /var/www/_wsh/
  #PythonOption mod_pywebsocket.allow_draft75 On
  #<Location /var/www/_vsh>
  #  PythonHeaderParserHandler mod_pywebsocket.headerparserhandler
  #</Location>
</IfModule>

After apaceh restart, I'm trying console.html code from examples of pywebsocket directory (copied in /var/www/_wsh). But it doesnt work, I cant open the connection.
When I try to run example I got this
root@senior:/usr# /var/www/_wsh/echo_client.py
Traceback (most recent call last):
  File "/var/www/_wsh/echo_client.py", line 995, in <module>
    main()
  File "/var/www/_wsh/echo_client.py", line 991, in main
    EchoClient(options).run()
  File "/var/www/_wsh/echo_client.py", line 840, in run
    self._handshake.handshake()
  File "/var/www/_wsh/echo_client.py", line 385, in handshake
    'Expected HTTP status code 101 but found %r' % status_code)
__main__.ClientHandshakeError: Expected HTTP status code 101 but found '200'

Could you please help me find out where is the problem? Thank you

A: It is much easier to run it as standalone server. Have you tried that?
"""Standalone WebSocket server.

Use this file to launch pywebsocket without Apache HTTP Server.

BASIC USAGE

Go to the src directory and run

  $ python mod_pywebsocket/standalone.py [-p <ws_port>]
                                         [-w <websock_handlers>]
                                         [-d <document_root>]

<ws_port> is the port number to use for ws:// connection.

<document_root> is the path to the root directory of HTML files.

<websock_handlers> is the path to the root directory of WebSocket handlers.
If not specified, <document_root> will be used. See __init__.py (or
run $ pydoc mod_pywebsocket) for how to write WebSocket handlers.

For more detail and other options, run

  $ python mod_pywebsocket/standalone.py --help

or see _build_option_parser method below.

For trouble shooting, adding "--log_level debug" might help you.

Update
Try this link for fixing your issue.

A: After reading many tutorials on how to set up pywebsockets, I've ended up with this configuration:
LogLevel debug
<IfModule python_module>
  Timeout 0
  #This is path where I have copied pywebsocket
  PythonPath "sys.path+['/usr/local/lib/python2.6/dist-packages']"
  #This is path where I have my websocket connection handlers (files that responds to requests, I have there example files copied too)
  PythonOption mod_pywebsocket.handler_root /var/www/websockets/
  PythonOption mod_pywebsocket.handler_scan /var/www/websockets/
  PythonHeaderParserHandler mod_pywebsocket.headerparserhandler
</IfModule>

Here is list of this paths for better understanding of where is what:
root@senior:/var/www/websockets# ls /usr/local/lib/python2.6/dist-packages/
mod_pywebsocket  mod_pywebsocket-0.7.8.egg-info
root@senior:/var/www/websockets# ls /usr/local/lib/python2.6/dist-packages/mod_pywebsocket
common.py       handshake                __init__.pyc        mux.pyc             _stream_hixie75.pyc  util.pyc
common.pyc      headerparserhandler.py   memorizingfile.py   standalone.py       _stream_hybi.py
dispatch.py     headerparserhandler.pyc  memorizingfile.pyc  standalone.pyc      _stream_hybi.pyc
dispatch.pyc    http_header_util.py      msgutil.py          _stream_base.py     stream.py
extensions.py   http_header_util.pyc     msgutil.pyc         _stream_base.pyc    stream.pyc
extensions.pyc  __init__.py              mux.py              _stream_hixie75.py  util.py
root@senior:/var/www/websockets#
root@senior:/var/www/websockets# ls .
bench_wsh.py  console.html    echo_wsh.py      origin_check_wsh.py
close_wsh.py  echo_client.py  handler_map.txt  pywebsocket.conf

I also had to edit mod_reqtimeout of apache to keep connection alive (see this question for more info Why would a websocket created with pywebsocket be closed automatically? )


text:
Q: Post-Condition in test cases Is it fine not have any post-condition in a test case?
For example, there is an employee information system or module and an employee can login into the system and views his/her profile and logs out.
If I write a test case for it, I can't think of any post-condition possible in this test case. Can I write it without post-condition?

A: Successful logout, for one.
No user data left on the screen (or other, like history).
Ready to login again.
(I assume you are already testing the user got the right info.)


text:
Q: Pebble templating for YAML file I am trying out Pebble templating for a config file which is in YAML format. The value for this comes from another YAML file. That is -

*

*value.yml contains:-

    server:
     -
      box1:
        host:"12345"

*config.yml contains:-

    server:
      -
       env: "abc"
       host: {{ server.box1.host }}

I could read the config.yml as string and create a Pebble template. Using evaluate I am able to replace the template with context variable whose name is not nested (example {{ serverBox1Host }} --> this works).
If I use {{ server.box1.host }}, I get com.mitchellbosecke.pebble.error.RootAttributeNotFoundException: Root attribute [server] does not exist or can not be accessed and strict variables is set to true.
If I set strictVariables as false, the {{ server.box1.host }} is replaced with empty.
How to solve this?
context.put("server.box1.host", "suriya" );

I took references from:
https://www.programcreek.com/java-api-examples/?api=com.mitchellbosecke.pebble.PebbleEngine
I am using "String Template":
new PebbleEngine.Builder()
                .strictVariables(true)
                .newLineTrimming(false)
                .loader(new StringLoader())
                .build();

Thanks

A: You can use the dot (.) notation to access attributes of variables that are objects. If the attribute contains any atypical characters, you can use the subscript notation ([]) instead.
{{ foo.bar }}
{{ foo["bar"] }}

Behind the scenes foo.bar will attempt the following techniques to to access the bar attribute of the foo variable:
If foo is a Map,
foo.get("bar")
foo.getBar()
foo.isBar()
foo.hasBar()
foo.bar()
foo.bar

Additionally, if foo is a List, then foo[0] can be used instead of foo.get(0).
You can take a look at pebble documentation here : https://pebbletemplates.io/wiki/guide/basic-usage/

A: Resolved this:
Variable name assigned in the context was server like -
context.put("server", new HashMap<String, Object> map1);
And map1 had nested map whose keys was box1 and host. The value of the host was suriya.
map1 :
key - box1
value - Map with key host and value suriya.

In the Pebble template was able to access {{ server.box1.host }} and this rendered with value "suriya"


text:
Q: Identity between two vectors I carried out the proofs of these two identities.
If $\vec{a}$ and $\vec{b}$ are two vectors of $\mathbb{R}^2$, therefore
1. $$|\vec{a}\times \vec{b}|^2\stackrel{id}{=}a^2b^2-(\vec{a}\cdot \vec{b})^2$$
 2. $$|\vec{a}+\vec{b}|^2\stackrel{id}{=}a^2+b^2+2(\vec{a}\cdot \vec{b})$$
First proof.
$$|\vec{a}\times \vec{b}|^2=(|\vec{a}\times \vec{b}|)^2=(ab\sin \vartheta)^2=a^2b^2\sin^2\vartheta=a^2b^2(1-\cos^2\vartheta)=a^2b^2-a^2b^2\cos^2\vartheta=$$
Being $\cos\vartheta=\dfrac{\vec{a}\cdot \vec{b}}{ab} \longrightarrow \cos^2\vartheta=\dfrac{(\vec{a}\cdot \vec{b})^2}{a^2b^2}$, I obtain:
$$=a^2b^2-a^2b^2\frac{(\vec{a}\cdot \vec{b})^2}{a^2b^2}=a^2b^2-(\vec{a}\cdot \vec{b})^2
$$
Second proof.
$$|\vec{a}+ \vec{b}|^2=((a_x+b_x)\hat x +(a_y+b_y) \hat y)^2=(a_x+b_x)^2(\hat x)^2+(a_y+b_y)^2(\hat y)^2=$$
Being $|\hat x|^2=|\hat y|^2=(\hat x)^2=(\hat y)^2=1$, I obtain:
$$=(a_x+b_x)^2+(a_y+b_y)^2=a^2_{x}+2a_{x}b_{x}+b^2_{x}+a^2_{y}+2a_{y}b_{y}+b^2_{y}=$$
$$=(a^2_{x}+a^2_{y})+(b^2_{x}+b^2_{y})+2(a_{x}b_{x}+a_{y}b_{y})=$$
$$=a^2+b^2+2(\vec{a}\cdot \vec{b})$$
Being $\vec{a}=a_x\hat x+a_y\hat y,\,\vec{b}=b_x\hat x+b_y\hat y,\,\,|\vec a|^2=a^2,\,\,|\vec b|^2=b^2,\,\, \vec{a}\cdot \vec{b}=a_xb_x+a_yb_y.\,\,_{\square}$
Are there different proofs from what I've shown? I did not have, at least until now, an answer to my question.

A: In response to Sebastiano's request, I will provide a detailed proof using Tommy xu3's hint.
First, note that $|\vec V|$ is scalar so we can use any scalar operations on $|\vec V|$.
a) The proof of the first identity is similar to Sebastiano's, but care must be taken to not divide by $ab$ in case the $ab = 0$. Thus, the identity $\sin^2\theta = 1-\cos^2\theta$ should be used instead.
$$\begin{align}
|\vec a \times \vec b|^2 &= (|\vec a \times \vec b|) (|\vec a \times \vec b|)
\text{, noting scalar multiplication: (...) times (...)}\\
&= (ab\sin\theta) (ab \sin\theta) \\
&= a^2b^2\sin^2\theta \\
&= a^2b^2(1- \cos^2\theta)\\
&= a^2b^2 - (ab\cos\theta)^2 \\
&= a^2b^2 - (\vec a\cdot\vec b)^2.
\end{align}
$$
The second identity uses hint #2, which comes from:
$$\vec V\cdot \vec V = V^2 \cos 0 = V^2 = |\vec V|^2. $$
Reading the identity above right to left, letting  $\vec V = \vec a + \vec b$, we have:
$$\begin{align}
|\vec a + \vec b|^2 &= (\vec a + \vec b )\cdot(\vec a + \vec b ) \\
&= \vec a \cdot\vec a + \vec a \cdot \vec b + \vec b \cdot \vec a + \vec b \cdot \vec b\\
&= a^2 + b^2 + 2 \vec a \cdot \vec b.
\end{align}
$$

A: Hint:
$1.$ $|\vec{a}\times\vec{b}|=|ab\sin\theta|$ and $|\vec{a}\cdot\vec{b}|=|ab\cos\theta|.$
$2.$ $|\vec{a}+\vec{b}|^2=( \vec{a}+\vec{b})\cdot(\vec{a}+\vec{b}).$


text:
Q: Can I throw an anonymous object in JavaScript? Mozilla says that we can define an object and throw it.
This way, we can encapsulate more than a simple string message and send it to the exception consumer (the catch block, or the then method of promises).
However, I don't want to constantly define types in my JS code.
Is it possible to throw anonymous objects?
I tried throw new Error({ firstKey: firstValue, secondKey: secondValue }) and it does not work. I get [object Object].

A: When an Error is created, the first parameter passed (if any) is converted to a string, and not used anywhere else. So, just by using the first parameter, there's no way to pass an object along (without using JSON.stringify, which would be ugly and also lose information).
But Errors can accept a second argument - an object with a cause property, which will then get put on the error object. You can use this to communicate any information you want, including objects.

const objForCause = {};
try {
  throw new Error(
    'Something went wrong',
    { cause: { prop: 'val', obj: objForCause } }
  );
} catch(err) {
  // Not all errors have causes
  // Ensure that it does before examining further
  if (err.cause) {
    console.log(err.cause);
    console.log(err.cause.obj === objForCause);
  }
}

A: In javascript, you can throw literally anything:

try {
  throw "a string";
} catch (error) {
  console.log("caught", error)
}

try {
  throw 10;
} catch (error) {
  console.log("caught", error)
}

try {
  throw {a: 1, b: 2};
} catch (error) {
  console.log("caught", error)
}

So to answer the question Is it possible to throw anonymous objects?: yes it's possible to throw an anonymous object.
Whether you should do so is another question.

A: If you read your own question statement carefully. This is what is being said.

*

*Define your own object

  const myobj={a:1,b:2};

*Then throw it.

  throw myobj;

*Use the object however you want

console.log(err);

Below is a working example.

try {
  const myobj = {
    a: 1,
    b: 2
  };
  throw myobj;
} catch (err) {
  console.log(err);
}

You can do all sorts of things depending upon your imagination I guess. even attaching a error object instance if you want.


text:
Q: Which Bone is Leela Missing? In Season 8, Episode 9 of Futurama, called "Fry Am the Egg Man", Leela says that she has 205 bones in her body. A normal human has 206 (at adulthood), so what bone is Leela missing?

A: As Valorum shows, her skeleton from the neck down appears normal. Indeed, the most significant difference between her ("the least-mutated mutant ever born") and a normal person is her one huge eye, suggesting that the one missing bone is part of her facial skeleton.

Since the facial bones are in pairs, the one she is missing is likely an unpaired one, specifically the vomer, which makes sense given the size of her eye and the space it would occupy in her skull.

A: We can see from the image below (from season 6) that Leela's skeleton is completely normal from the neck down. That would strongly imply that the bone that she's missing is within her skull or upper neck.
Presumably she's missing her nasal bone, since that would conflict with her big centrally-located eye.


text:
Q: Can't access the Music folder I am quite new to Android-Development. I have troubles to access my songs, stored in the Music folder. From adb shell the path is: /storage/emulated/legacy/Music.
Following code causes the exception:
try {
    Log.i("path", Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+Environment.DIRECTORY_MUSIC + "/" + name + ".mp3");
    mediaPlayer.setDataSource(getApplicationContext(),
    Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()
                                + "/"
                                + Environment.DIRECTORY_MUSIC
                                + "/"
                                + name + ".mp3"));
    mediaPlayer.prepare();
    mediaPlayer.start();
}

Here is the exception:
I/path: /storage/emulated/0/Music/A Wunder.mp3
java.io.IOException: setDataSource failed.

Any help appreciated!
EDIT:
It seems that i have problems with some of the files. My "Player" can't open all of them, but other player can.
So here is the code that works for me:
    mediaPlayer.setDataSource(getApplicationContext(),
                         Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/" + name + ".mp3"));


text:
Q: Euclidean and Manhattan distance with missing values I wanted to know what is the correct way to calculate Euclidean and Manhattan distance. I've got a vector which has values from -120 to 0 (in dB). I have to compare it but sometimes one of the vectors can be missing value.
For example:
A = [-50, -40, -20, X, -10]
B = [-55, -44, X, -10, -12, -5]
Should I insert minimum value which is -120 here and calculate Euclidean distance?


text:
Q: FileNotFoundError: [Errno 2] No such file or directory: 'transcripts/louis.txt' I have been trying to scraping 12 scripts and wanted to pickle them but some reason its not working and giving error of [Errno 2] No such file or directory: 'transcripts/louis.txt'.
Could some one help me please. Many thanks in advance.
Web scraping, pickle imports
    import requests

    from bs4 import BeautifulSoup

    import pickle

    import os

import errno

Scrapes transcript data from scrapsfromtheloft.com
def url_to_transcript(url):

    '''Returns transcript data specifically from scrapsfromtheloft.com.'''

    page = requests.get(url).text

    soup = BeautifulSoup(page, "lxml")

    text = [p.text for p in soup.find(class_="post-content").find_all('p')]

    print(url)

    return text

URLs of transcripts in scope
urls = ['http://scrapsfromtheloft.com/2017/05/06/louis-ck-oh-my-god-full-transcript/',

        'http://scrapsfromtheloft.com/2017/04/11/dave-chappelle-age-spin-2017-full-transcript/',

        'http://scrapsfromtheloft.com/2018/03/15/ricky-gervais-humanity-transcript/',

        'http://scrapsfromtheloft.com/2017/08/07/bo-burnham-2013-full-transcript/',

        'http://scrapsfromtheloft.com/2017/05/24/bill-burr-im-sorry-feel-way-2014-full-transcript/',

        'http://scrapsfromtheloft.com/2017/04/21/jim-jefferies-bare-2014-full-transcript/',

        'http://scrapsfromtheloft.com/2017/08/02/john-mulaney-comeback-kid-2015-full-transcript/',

        'http://scrapsfromtheloft.com/2017/10/21/hasan-minhaj-homecoming-king-2017-full-transcript/',

        'http://scrapsfromtheloft.com/2017/09/19/ali-wong-baby-cobra-2016-full-transcript/',

        'http://scrapsfromtheloft.com/2017/08/03/anthony-jeselnik-thoughts-prayers-2015-full-transcript/',

        'http://scrapsfromtheloft.com/2018/03/03/mike-birbiglia-my-girlfriends-boyfriend-2013-full-transcript/',

        'http://scrapsfromtheloft.com/2017/08/19/joe-rogan-triggered-2016-full-transcript/']

# Comedian names
comedians = ['louis', 'dave', 'ricky', 'bo', 'bill', 'jim', 'john', 'hasan', 'ali', 'anthony', 'mike', 'joe']

# Actually request transcripts (takes a few minutes to run)
transcripts = [url_to_transcript(u) for u in urls]

# Pickle files for later use
# Make a new directory to hold the text files
!mkdir transcripts
for i, c in enumerate(comedians):

    with open("transcripts/" + c + ".txt", "wb") as file:

        pickle.dump(transcripts[i], file)

---------------------------------------------------------------------------

 FileNotFoundError                         Traceback (most recent call last)

    <ipython-input-6-f3ce7b5495e7> in <module>
          5
          6 for i, c in enumerate(comedians):

    ----> 7     with open("transcripts/" + c + ".txt", "wb") as file:

          8         pickle.dump(transcripts[i], file)

    FileNotFoundError: [Errno 2] No such file or directory: 'transcripts/louis.txt'`**enter code here**`

A: What is your working directory? Run os.getcwd() to find out. The folder structure you wish to use needs to be in there.


text:
Q: Flutter Google Map rounded image marker not align in the center I recently worked the the google maps with flutter.
i created the marker to indicate the users current location. and added three circles in to indicate the accuracy of the Google map. And the marker image is round shaped. and it is bottom aligned.
But i need the center alignment of the marker.
Like this

The Output of my code

The function for getting user location and set marker and circles
  onInitFunc() async {
    locationicon = BitmapDescriptor.fromBytes(
        await getBytesFromAsset('assets/icons/map-store.png'));
    mylocationicon = BitmapDescriptor.fromBytes(
      await getBytesFromAsset('assets/images/avatar.png'),
    );
    setState(() {
      isIconsUpdated = true;
    });
    var _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return;
      }
    }
    currentLocation = await location.getLocation();
    await setMarketsOfMyLocation();
    locationSubscription = location.onLocationChanged.listen((location) async {
      currentLocation = location;
      await setMarketsOfMyLocation();
      setState(() {});
    });
    setState(() {});
  }

  setMarketsOfMyLocation() async {
    markers.add(
      Marker(
        markerId: const MarkerId('myPosition'),
        position: LatLng(
          currentLocation!.latitude!,
          currentLocation!.longitude!,
        ),
        flat: true,
        icon: mylocationicon,
        onTap: () {
          mapController.animateCamera(
            CameraUpdate.newCameraPosition(
              CameraPosition(
                target: LatLng(
                  currentLocation!.latitude!,
                  currentLocation!.longitude!,
                ),
                zoom: 15,
              ),
            ),
          );
          setState(() {});
        },
      ),
    );
    circles = {
      Circle(
        circleId: const CircleId('myPosition1'),
        center: LatLng(
          currentLocation!.latitude!,
          currentLocation!.longitude!,
        ),
        radius: 100,
        fillColor: Colors.white.withOpacity(0.5),
        strokeWidth: 0,
      ),
      Circle(
        circleId: const CircleId('myPosition2'),
        center: LatLng(
          currentLocation!.latitude!,
          currentLocation!.longitude!,
        ),
        radius: 200,
        fillColor: const Color(0xFFFAAB1B).withOpacity(0.1),
        strokeWidth: 0,
      ),
      Circle(
        circleId: const CircleId('myPosition3'),
        center: LatLng(
          currentLocation!.latitude!,
          currentLocation!.longitude!,
        ),
        radius: 300,
        fillColor: const Color(0xFFFAAB1B).withOpacity(0.05),
        strokeWidth: 0,
      ),
    };
    setState(() {});
  }

The widget code of google map
SizedBox(
  width: MediaQuery.of(context).size.width,
  height: MediaQuery.of(context).size.height,
  child: GoogleMap(
    circles: circles,
    mapToolbarEnabled: false,
    myLocationButtonEnabled: false,
    myLocationEnabled: false,
    initialCameraPosition: CameraPosition(
      zoom: 10,
      target: LatLng(
        // bangalore
        currentLocation.runtimeType == Null
            ? 12.9716
            : currentLocation!.latitude!,
        currentLocation.runtimeType == Null
            ? 77.5946
            : currentLocation!.longitude!,
      ),
    ),
    onTap: (position) {
      _customInfoWindowController.hideInfoWindow();
      setState(() {
        currentStore = null;
      });
      mapController.animateCamera(
        CameraUpdate.newLatLngBounds(bounds(markers)!, 50),
      );
    },
    onCameraMove: (position) {
      _customInfoWindowController.onCameraMove();
    },
    mapType: MapType.normal,
    markers: markers,
    onMapCreated: onMapcreated,
    compassEnabled: true,
    zoomControlsEnabled: false,
  ),
),


text:
Q: Application on IIS does not able to launch Adobe Illustrator My application makes use of Adobe Illustrator on the server side to complete some routine tasks. It is working fine on IIS Express for development, however when it runs on IIS for production it throws the following error:
System.Runtime.InteropServices.COMException (0x80080005): Retrieving the COM class factory for component with CLSID {F66C7D88-4EEB-4A9B-BBF2-D229C9C46870} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT:0x80080005 (CO_E_SERVER_EXEC_FAILURE)).

The code to launch Adobe Illustrator is straightforward:
var app = new Application();

I have tried to elevate the privilege of the app pool to administrator, and add permission in COM settings in computer management too. But none of them help to resolve the issue. I wonder if there is any difference for the permission model between IIS Express and IIS, which makes IIS Express work but not IIS. Could anyone help please?
Thank you!


text:
Q: Application Server Administration Service Timer Job doesn't finish or fail Lately the Application Server Administration Service Timer Job does not complete on one WFE and runs long on the other WFE.  Since it does not fail I do not see an error logged.  What could cause this job to run, but not complete or fail?
Thanks


text:
Q: How can I create a new Powerpoint presentation with Powershell I am trying to create a new Powerpoint presentation with Powershell from scratch but am having trouble with the object model. Based on some code from the ScriptingGuy I came up with:
Add-type -AssemblyName office
$Application = New-Object -ComObject powerpoint.application
$application.visible = [Microsoft.Office.Core.MsoTriState]::msoTrue
$slideType = "microsoft.office.interop.powerpoint.ppSlideLayout" -as [type]

$blanklayout = $slideType::ppLayoutTitleOnly

$presentation = $application.Presentations.add()

$slide = $presentation.slides.addSlide(0,$blanklayout)

but receive an error:
Ausnahme beim Aufrufen von "AddSlide" mit 2 Argument(en):  "Typenkonflikt. (Ausnahme von HRESULT: 0x80020005
(DISP_E_TYPEMISMATCH))"
In C:\Users\Uwe\Dropbox\Powerpoint.ps1:12 Zeichen:1
+ $slide = $presentation.slides.addSlide(0,$blanklayout)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

How can I get the correct layout from the object model and add the new slide?

A: The first thing I see is that you need to load the assembly that contains the type microsoft.office.interop.powerpoint.ppSlideLayout. The assembly's name is microsoft.office.interop.powerpoint. So:
add-type -assembly microsoft.office.interop.powerpoint

The second thing I needed to do to get it to work for me was to use the Add method instead of the AddSlide method.
$slide = $presentation.slides.add(1,$blanklayout)

The $blanklayout can be replaced by an integer, if you know which layout the integer corresponds to. However using the code like you have is somewhat more self-documenting. 15 is the value for ppLayoutLargeObject.
The first parameter is an integer between 1 and ($presentation.slides.count + 1). If you choose a value less than the max the slide is inserted into that place in the slide deck and the slides after it have their slide number incremented by 1. If you choose the max the slide is added at the end.
Note that the "Add" method is marked as an internal API in the documentation. Probably not a big deal, but MS would have more justification for changing that API in a future version of Powerpoint than an API not marked internal. Using the AddSlide API looks more complicated. The doc says you have to use a SlideRange to get a CustomLayout.

A: I found referencing this code in the below link helpful.
https://gist.github.com/miriyagi/4240819
Also see my example. Changing the value (15) determines the style of the new slide being inserted.
$slide = $Presentation.Slides.Add($presentation.Slides.Count + 1, 15)


text:
Q: PHP o JS - Actualizar una sección de la página Como están? Le estoy dando vuelta a un tema, que no logro encontrarle como hacerlo, tengo una web, donde quiero que solo una seccion de la pagina se actualice, ya que toma datos de la BD, muestra datos nuevos esa seccion. lo unico que logre hacer es:

        <?php include('.\Querys\userQuery.php') ?>

        while ($row=sqlsrv_fetch_array($res)) {
    ?>

            <?=$row[0]?>
            <?=$row[1]?>
            <?=$row[2]?>
            <?=str_ireplace($serv_regular, $serv_nueva, $row[3])?>
            <?=str_ireplace($desc_regular, $desc_nuevo, $row[4])?>
            <?=$row[5]->format('Y-m-d H:i:s');?>

    <?php

Este es mi while, donde toma los datos de una query de SQL server, y los pongo en el DIV - en la bd se agregan datos continuamente, por eso quiero que se recargue o refresque siempre ese div, sin tener que actualizar toda la pagina. JS no tengo nada. Estaba mirando un codigo Ajax, pero estoy tratando de entenderlo.

A: Cierro el tema, ya encontre la solución a lo que buscaba, con Jquery
$(document).ready(function() {
var pageRefresh = 5000; //5 s
setInterval(function() {
refresh();
}, pageRefresh);
});

function refresh() {
$('#contenido').load(location.href + " #contenido");
$('#Contador').load(location.href + " #Contador");
}

Gracias.-


text:
Q: Undefined property, even though it's there I have an object, Brand, and I want to print the id of this object.
I am getting the following error when doing return Sentry::getUser()->brand()->get()->id:
Undefined property: Illuminate\Database\Eloquent\Collection::$id

However, if I remove the ->id part, I am getting the whole object just fine, including the id (return Sentry::getUser()->brand()->get())
What am I doing wrong?

A: You need to use:
return Sentry::getUser()->brand()->first()->id;

Otherwise, you end up with a collection of users (even though that collection may only contain one user).

A: it might be reserved in a framework you used. My guess s that every object of any kind is a default object-type object that has an id of its own. If possible change the "id" to brand_id or something like that.

A: If there is only one object and will always be one, you can use return Sentry::getUser()->brand()->first()->id. That retrieves a single object, while get () returns an array of objects even if there is only one match.


text:
Q: been struggling with this for few hours. My XPath is right but I get this error message been struggling with this for few hours. My XPath is right but I get this error message. I don't seem to get a way forward on this
o such element: Unable to locate element: {"method":"xpath","selector":"//a[@class='btn primary block']"}
  (Session info: chrome=68.0.3440.106)
  (Driver info: chromedriver=2.41.578706 (5f725d1b4f0a4acbf5259df887244095596231db),platform=Mac OS X 10.11.6 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
NydPage nydPage;
GetAQuotePage getAQuotePage;

@FindBy(xpath="//a[@class='btn primary block']")
WebElement GetAQuoteLink;

public NydPage() {
    PageFactory.initElements(driver, this);
}

public GetAQuotePage clickOnGetAQuoteLink() throws Exception{
    Thread.sleep(5000);
    GetAQuoteLink.click();
    return new GetAQuotePage();

}

@BeforeMethod
public void setUp() {
    //driver = new ChromeDriver();
    initialization();
    testUtil = new TestUtil();
    nydPage = new NydPage();
}

@Test(priority=1)
public  void verifyQuotePageLinkTest() throws Exception{
    //testUtil.switchToFrame();
    Thread.sleep(5000);
    getAQuotePage = nydPage.clickOnGetAQuoteLink();

}

@AfterMethod
public void tearDown() {
    driver.quit();
}


text:
Q: How to Export Number of Followers from Instagram accounts to Googlesheet? I manage different Instagram accounts, some of them are private and others are business accounts. Instead of checking all of them daily, I need to list them in one Google sheet and see the number of their followers.
Previously,  I have used XML to fetch that. But now it is not working. Is there any way for doing this? (Also, I need this data to be updated automatically without the needs to run a code each time so other team members can see the data whenever required)
My previous sheet was this:
enter image description here

A: You should use instagram api if you wanna extract your  own followers
First connect your instagram account to the api
And then you have followers list
Second write a loop statement and write the list one by one to a excel file  by the way you can use free excel package for python

A: There are many ways to do, i think you can use of InstaPy bot which has written by python. When you start this bot and give it some accounts, it collect all information about these accounts and save them in CSV file. It is simple and you can install it on Windows, Linux or even MacOs
https://pypi.org/project/instapy


text:
Q: Display a contantly updated text file in a web user interface using Python flask framework In my project workflow, i am invoking a sh script from a python script file. I am planning to introduce a web user interface for this, hence opted for flask framework. I am yet to figure out how to display the terminal output of the shell script invoked by my python script in a component like text area or label. This file is a log file which is constantly updated till the script run is completed.
The solution i thought was to redirect terminal output to a text file and read the text file every X seconds and display the content. I can also do it via the Ajax way from my web application. Is there any other prescribed way to achieve this ?
Thanks

A: The one way I can think of doing this is to refresh the page. So, you could set the page to refresh itself every X seconds.
You would hope that the file you are reading is not large though, or it will impact performance. Better to have the output in memory.


text:
Q: Fixing corrupted JSON from localStorage I am saving out a JavaScript object to localStorage using JSON.stringify().
localStorage.setItem('stored_object', JSON.stringify(objCases) );

Periodically, I will find that the JSON string has spontaneously changed from this:
{"9999999999999":{"case":"dummy","subj":"example","note":"placeholder"}}

into this:
{asynchronous_key:'577b3620-8cbd-5251-b526-5882044f1386', jsonObject:{"\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039":{"\u0063\u0061\u0073\u0065":"\u0064\u0075\u006d\u006d\u0079","\u0073\u0075\u0062\u006a":"\u0065\u0078\u0061\u006d\u0070\u006c\u0065","\u006e\u006f\u0074\u0065":"\u0070\u006c\u0061\u0063\u0065\u0068\u006f\u006c\u0064\u0065\u0072"}}}

In another question, user GoTo 0 provided a solution, but I am having difficulty implementing it. I think I am missing something basic:
JS Fiddle example
Stack Snippet Example:

var badjson = {asynchronous_key:'49098507-12cd-e1b0-b442-5882cd1bf37e', jsonObject:{"\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039":{"\u0063\u0061\u0073\u0065":"\u0064\u0075\u006d\u006d\u0079","\u0073\u0075\u0062\u006a":"\u0065\u0078\u0061\u006d\u0070\u006c\u0065","\u006e\u006f\u0074\u0065":"\u0070\u006c\u0061\u0063\u0065\u0068\u006f\u006c\u0064\u0065\u0072"}}};
localStorage.setItem('remindObj', JSON.stringify(badjson));
console.log('Here 03: '+ localStorage.getItem('remindObj') );

var getjson = localStorage.getItem('remindObj');
console.log('Here 06: ' +getjson);
console.log(typeof(getjson));
console.log(getjson.indexOf('asynchronous_key') );
if (getjson.indexOf('asynchronous_key') > 0){
  console.log('ASYNCHRONOUS_KEY FOUND - Attempting to fix');
  originalJSONString = JSON.stringify(getjson.jsonObject);
  console.log('FIXING: ' +originalJSONString);
  objRemind = JSON.parse(originalJSONString);
  localStorage.setItem("remindObj", originalJSONString);
  console.log('FIXED: ' +localStorage.getItem("remindObj") );
}

A: Just so you can close this: You had an error in line 11 (counting the empty line): It should be JSON.parse() not JSON.stringify()
Edited fiddle: https://jsfiddle.net/4n6dqqvn/1/

var storageKey = 'remindObj';
var badjson = {
  asynchronous_key: '49098507-12cd-e1b0-b442-5882cd1bf37e',
  jsonObject:{
    "\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039":{
    "\u0063\u0061\u0073\u0065":"\u0064\u0075\u006d\u006d\u0079","\u0073\u0075\u0062\u006a":"\u0065\u0078\u0061\u006d\u0070\u006c\u0065",
      "\u006e\u006f\u0074\u0065":"\u0070\u006c\u0061\u0063\u0065\u0068\u006f\u006c\u0064\u0065\u0072"
    }
  }
};
localStorage.setItem(storageKey, JSON.stringify(badjson));

var getjson = localStorage.getItem(storageKey);
console.log('Initial: ', getjson);

if (typeof(getjson) === 'string'){
  console.log('ASYNCHRONOUS_KEY FOUND - Attempting to fix');
  var originalJSONString = JSON.parse(getjson).jsonObject;
  console.log('FIXING: ', originalJSONString);
  localStorage.setItem(storageKey, JSON.stringify(originalJSONString));
  console.log('FIXED: ', JSON.parse(localStorage.getItem(storageKey)));
}


text:
Q: Tests are passing in jenkins command prompt and failing in jenkins windows service Can someone please help regarding the following :
Jenkins--Command Prompt:
Start Jenkins in cmd prompt
Run the selenium framework
Chrome opens in full screen and test cases are passed
Jenkins- Windows Services:
Start Jenkins as windows services
Run the selenium framework
Chrome not opening in full screen and test cases are failed
#
I have installed latest chrome driver as well
My Json config :
{
  "capabilities":
  [

    {
      "browserName": "chrome",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "acceptSslCerts":true,
      "javascriptEnabled":true
    }
  ]

and :
        cap = DesiredCapabilities.chrome();
        cap.setPlatform(Platform.WINDOWS);
        cap.setCapability("jenkins.nodeName", "(master)");

But the above scenario doesn't work :
I have tried the following options also :
options.addArguments("--start-maximized");

Note: I ran the framework as admin user too
it does fail.