FirebaseRecyclerAdapter not working or showing any data

Question: I'm a novice in Android programming. I've been able to create a userprofile table in firebase and can show user data from userprofile table in recyclerview but I cannot get my products table named "Arbrg" to show in firebaserecyclerview. Please tell me where I've done wrong in the codes. Your help is highly appreciated.
My codes as follow:

viewARBRG.java ( called on Button pressed )

package com.example.fb_app2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class viewARBRG extends AppCompatActivity {
    LinearLayoutManager mLinearLayoutManager;
    RecyclerView mRecyclerView;
    FirebaseDatabase mFirebaseDatabase;
    DatabaseReference mDatabaseReference;
    FirebaseRecyclerAdapter<MasterBarangClass, ViewHolderARBRG> firebaseRecyclerAdapter;
    FirebaseRecyclerOptions<MasterBarangClass> options;

    @Override
    protected void onStart() {
        super.onStart();
        firebaseRecyclerAdapter.startListening();

    }

    @Override
    protected void onStop() {
        super.onStop();
        firebaseRecyclerAdapter.stopListening();
    }

    @Override
    public void onBackPressed() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_arbrg);

        mLinearLayoutManager = new LinearLayoutManager(this);
        mLinearLayoutManager.setReverseLayout(true);
        mLinearLayoutManager.setStackFromEnd(true);

        mRecyclerView = findViewById(R.id.recyclerView_arbrg);
        mFirebaseDatabase = FirebaseDatabase.getInstance();

        showData();
    }

    private void showData() {
        mDatabaseReference = mFirebaseDatabase.getReference("Arbrg");

        options = new FirebaseRecyclerOptions.Builder<MasterBarangClass>()
                .setQuery(mDatabaseReference, MasterBarangClass.class).build();

        Toast.makeText(getApplicationContext(), "Table : " + mDatabaseReference.toString(), Toast.LENGTH_SHORT).show();

        firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<MasterBarangClass, ViewHolderARBRG>(options){
            @Override
            protected void onBindViewHolder(@NonNull ViewHolderARBRG viewHolderARBRG, int i, @NonNull MasterBarangClass masterBarangClass) {
                final String barcode = masterBarangClass.getBarcode();
                final String divbrg  = masterBarangClass.getDivbrg();
                final String hrgjual = masterBarangClass.getHrgjual();
                final String jnsbrg  = masterBarangClass.getJnsbrg();
                final String kdbrg = masterBarangClass.getKdbrg();
                final String nmbrg = masterBarangClass.getNmbrg();

                viewHolderARBRG.setDetails(viewARBRG.this,
                        masterBarangClass.getBarcode(),
                        masterBarangClass.getDivbrg(),
                        masterBarangClass.getHrgjual(),
                        masterBarangClass.getJnsbrg(),
                        masterBarangClass.getKdbrg(),
                        masterBarangClass.getNmbrg());

                viewHolderARBRG.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getApplicationContext(), showuser2klik.class);
                        intent.putExtra("barcode", barcode);
                        intent.putExtra("divbrg", divbrg);
                        intent.putExtra("hrgjual", hrgjual);
                        intent.putExtra("jnsbrg", jnsbrg);
                        intent.putExtra("kdbrg", kdbrg);
                        intent.putExtra("nmbrg", nmbrg);
                        startActivity(intent);
                    }
                });
            }
            @NonNull
            @Override
            public ViewHolderARBRG onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                final View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_arbrg, parent, false);

                final ViewHolderARBRG viewHolder = new ViewHolderARBRG(itemView);

                viewHolder.setOnClickListener(new ViewHolderARBRG.ClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Toast.makeText(getApplicationContext(), "clicked on " +position, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onItemLongClick(View view, int position) {
                        Toast.makeText(getApplicationContext(), "onItem Long click...", Toast.LENGTH_SHORT).show();
                    }
                });
                return viewHolder;
            }
        };
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        firebaseRecyclerAdapter.startListening();
        mRecyclerView.setAdapter(firebaseRecyclerAdapter);
    }

    public void back2main(View view) {
        finish();
        Intent int1 = new Intent(viewARBRG.this, MenuMasterActivity.class);
        startActivity(int1);
    }
}

activity_view_arbrg.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context=".viewARBRG">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="RecyclerView - MASTER BARANG VIEW" />
    <TextView
        android:id="@+id/textViewUserList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="LIST BARANG (ALL)" />
    <Button
        android:id="@+id/buttonBack"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="back2main"
        android:text="BACK" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView_arbrg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

MasterBarangClass.java ( Model class )

package com.example.fb_app2;

public class MasterBarangClass {
    public String barcode, divbrg, hrgjual, jnsbrg,  kdbrg, nmbrg;

    public MasterBarangClass(){}

    public MasterBarangClass(String barcode, String divbrg, String hrgjual, String jnsbrg, String kdbrg, String nmbrg) {
        this.barcode = barcode;
        this.divbrg = divbrg;
        this.hrgjual = hrgjual;
        this.jnsbrg = jnsbrg;
        this.kdbrg = kdbrg;
        this.nmbrg = nmbrg;
    }

    public String getBarcode() {
        return barcode;
    }
    public void setBarcode(String barcode) {
        this.barcode = barcode;
    }

    public String getDivbrg() {
        return divbrg;
    }
    public void setDivbrg(String divbrg) {
        this.divbrg = divbrg;
    }

    public String getHrgjual() {
        return hrgjual;
    }
    public void setHrgjual(String hrgjual) {
        this.hrgjual = hrgjual;
    }

    public String getJnsbrg() {
        return jnsbrg;
    }
    public void setJnsbrg(String jnsbrg) {
        this.jnsbrg = jnsbrg;
    }

    public String getKdbrg() {
        return kdbrg;
    }
    public void setKdbrg(String kdbrg) {
        this.kdbrg = kdbrg;
    }

    public String getNmbrg() {
        return nmbrg;
    }
    public void setNmbrg(String nmbrg) {
        this.nmbrg = nmbrg;
    }
}

row_arbrg.XML ( Layout file )

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    app:cardBackgroundColor="#fff"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardCornerRadius="3dp"
    app:cardElevation="3dp"
    app:cardUseCompatPadding="true"
    app:contentPadding="5dp"
    android:layout_margin="10dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/ra_tvNmbrg"
            android:text="Nama Barang"
            android:textSize="18sp"
            android:textColor="#000"
            android:textStyle="bold"
            android:layout_marginLeft="10dp"
            android:layout_marginStart="10dp"/>

        <ImageView
            android:layout_width="110dp"
            android:layout_height="130dp"
            android:id="@+id/imageIv"
            android:src="@mipmap/ic_launcher"
            android:layout_below="@id/ra_tvNmbrg"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/ra_tvKdbrg"
            android:text="Kode Barang"
            android:textSize="18sp"
            android:textColor="#000"
            android:layout_toRightOf="@id/imageIv"
            android:layout_toEndOf="@id/imageIv"
            android:layout_marginStart="10dp"
            android:layout_marginTop="20dp"/>

        <TextView
            android:id="@+id/ra_tvBarcode"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/ra_tvKdbrg"
            android:layout_marginStart="10dp"
            android:layout_marginTop="0dp"
            android:layout_toEndOf="@id/imageIv"
            android:layout_toRightOf="@id/imageIv"
            android:text="Bar code"
            android:textColor="#000"
            android:textSize="18sp" />
        <TextView
            android:id="@+id/ra_tvHargaJual"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/ra_tvBarcode"
            android:layout_marginStart="10dp"
            android:layout_marginTop="0dp"
            android:layout_toEndOf="@id/imageIv"
            android:layout_toRightOf="@id/imageIv"
            android:text="Harga Jual"
            android:textColor="#000"
            android:textSize="18sp" />
        <TextView
            android:id="@+id/ra_tvDivBrg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/ra_tvHargaJual"
            android:layout_marginStart="10dp"
            android:layout_marginTop="0dp"
            android:layout_toEndOf="@id/imageIv"
            android:layout_toRightOf="@id/imageIv"
            android:text="Divisi barang"
            android:textColor="#000"
            android:textSize="18sp" />
        <TextView
            android:id="@+id/ra_tvJnsBrg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/ra_tvDivBrg"
            android:layout_marginStart="10dp"
            android:layout_marginTop="0dp"
            android:layout_toEndOf="@id/imageIv"
            android:layout_toRightOf="@id/imageIv"
            android:text="Jenis barang"
            android:textColor="#000"
            android:textSize="18sp" />
    </RelativeLayout>

</androidx.cardview.widget.CardView>

ViewHolderARBRG.java

package com.example.fb_app2;

import android.content.Context;
import android.view.View;
import android.widget.TextView;

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

public class ViewHolderARBRG extends RecyclerView.ViewHolder {
    View mView;

    public ViewHolderARBRG(@NonNull View itemView) {
        super(itemView);
        mView = itemView;

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mClickListener.onItemClick(view, getAdapterPosition()); }
        });

        itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                mClickListener.onItemLongClick(view, getAdapterPosition());
                return true;  }
        });
    }

    public void setDetails(Context ctx, String barcode, String divbrg, String hrgjual, String jnsbrg, String kdbrg, String nmbrg) {
        TextView mbarcode = mView.findViewById(R.id.ra_tvBarcode);
        TextView mdivbrg = mView.findViewById(R.id.ra_tvDivBrg);
        TextView mhrgjual = mView.findViewById(R.id.ra_tvHargaJual);
        TextView mjnsbrg = mView.findViewById(R.id.ra_tvJnsBrg);
        TextView mkdbrg = mView.findViewById(R.id.ra_tvKdbrg);
        TextView mnmbrg = mView.findViewById(R.id.ra_tvNmbrg);

        mbarcode.setText(barcode);
        mdivbrg.setText(divbrg);
        mhrgjual.setText(hrgjual);
        mjnsbrg.setText(jnsbrg);
        mkdbrg.setText(kdbrg);
        mnmbrg.setText(nmbrg);
    }

    private ViewHolderARBRG.ClickListener mClickListener;
    public interface ClickListener {
        void onItemClick(View view, int position);
        void onItemLongClick(View view, int position);
    }

    public void setOnClickListener(ViewHolderARBRG.ClickListener clickListener){
        mClickListener = clickListener;
    }
}

Database Structure is as follow :

{
  "ArBrg" : {
    "-M0CKcYgvjxeYF6sGCma" : {
      "barcode" : "001",
      "divbrg" : "Alba satu",
      "hrgjual" : "899787",
      "jnsbrg" : "ALBA",
      "kdbrg" : "AAM",
      "nmbrg" : "500000"
    }
  },
  "Arsale" : {
    "-M02z2kgntKpso966nVB" : {
      "kdsale" : "SSR",
      "nmsale" : "Showroom salesperson"
    },
    "-M02z5me5mwau1jSMtlV" : {
      "kdsale" : "ANDI",
      "nmsale" : "ANDI"
    },
    "-M02z899rEkNHbjfANi7" : {
      "kdsale" : "BUDI",
      "nmsale" : "BUDI"
    }
  },
  "DivBrg" : {
    "-M02sY8LQIykdvaQph3a" : {
      "divbrg" : "LORUS",
      "nmdivbrg" : "LORUS"
    },
    "-M02scwzlD5-iFz_7r0j" : {
      "divbrg" : "ALBA",
      "nmdivbrg" : "ALBA"
    },
    "-M02sgYbypIab-m4gTAx" : {
      "divbrg" : "SEIKO",
      "nmdivbrg" : "SEIKO"
    },
    "-M02skAS79c-xKK_xdag" : {
      "divbrg" : "ASTRON",
      "nmdivbrg" : "ASTRON"
    },
    "vSrawft4GiUgMO1Z7ZZTwaU50H42" : {
      "divbrg" : "JEMIS",
      "nmdivbrg" : "JEMIS"
    }
  },
  "JnsBrg" : {
    "-M02w-iyneYG_rjxFDj4" : {
      "divbrg" : "ALBA",
      "jnsbrg" : "AAL",
      "nmjnsbrg" : "Analog Ladies"
    },
    "-M02w3YsFzX6SWjz0z0m" : {
      "divbrg" : "ALBA",
      "jnsbrg" : "AAM",
      "nmjnsbrg" : "Analog Men"
    },
    "-M02wC9M0cjJKEKbQHJl" : {
      "divbrg" : "SEIKO",
      "jnsbrg" : "KTL",
      "nmjnsbrg" : "kinetic ladies Seiko"
    }
  },
  "UserProfil" : {
    "2GGGxrGCQkQqaK9LFIBSdJJQ22i2" : {
      "email" : "firstname.lastname@example.com",
      "name" : "budi handoyo",
      "phone" : "+6281888112576"
    },
    "9RHvuwMVbJRkxYZsx2j5f9Gqlwx1" : {
      "email" : "email@example.com",
      "memail" : "firstname.lastname@example.com",
      "mname" : "Api Email 2",
      "mphone" : "+6282288887529",
      "name" : "Api Email 2",
      "phone" : "+6282225397529"
    },
    "GTxmtkcY5LPBWuUK9su0JQ8Dtcv2" : {
      "email" : "firstname.lastname@example.com",
      "name" : "celia ",
      "phone" : "+6281255082289"
    },
    "JBmBE4jd1cXARJJtzP7ZpMWi3TU2" : {
      "email" : "email@example.com",
      "memail" : "email@example.com",
      "mname" : "Andi Hidajat 2",
      "mphone" : "+6281888992276",
      "name" : "Andi Hidajat 2",
      "phone" : "+6281288972576"
    },
    "vSrawft4GiUgMO1Z7ZZTwaU50H42" : {
      "email" : "email@example.com",
      "memail" : "email@example.com",
      "mname" : "Andi Hidajat",
      "mphone" : "+62818902712",
      "name" : "Andi Hidajat",
      "phone" : "+628189888512"
    }
  }
}

When building the APK, it shows no error but the product data from Arbrg firebase table is not showing when I execute the viewARBRG.java. Any help
Regards,
Andi
Comment: Can you add your database structure?
Comment: I've updated my post and add an image of the database structure. Please have a look. Thank you very mucn.
Comment: I've also added a json format of the database structure. I'm looking forward to your help.
Answer: Your database reference is not correct. It's case sensitive. So, Please correct it.
Use
mDatabaseReference = mFirebaseDatabase.getReference("ArBrg");

Instead of
mDatabaseReference = mFirebaseDatabase.getReference("Arbrg");

Comment: Thank you very munch for your help. Now it's working.


choppy/ Laggy sprite animation using Farseer Physics

Question: So I am using farseer physics in this 2D platformer that I am making, but for some reason it makes the animations choppy and it's irritating. I have tried it with two different sprites. The first had 4 frames the other had 10 frames. The animation is only choppy when using farseer.
Here is the code where I create the body for the sprite:
public void CreateBody(World world, float density, Vector2 position, object userData = null)
{
    //magic number; so player doesn't look silly running into something he isn't touching because of a weapon-- CHANGE LATER
    _body = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(_attackForkFrames[0].Width * _scale.X - 20), ConvertUnits.ToSimUnits(_attackForkFrames[0].Height * _scale.Y - 2), density, ConvertUnits.ToSimUnits(position), userData);
    _body.BodyType = BodyType.Dynamic;
    _body.Restitution = 0f;
    _body.CollisionCategories = Category.All;//Category.Cat1;
    _body.CollidesWith = Category.All;//Category.Cat10;

...

Here is the code updating the position:
_body.Position = new Vector2(_body.Position.X + ConvertUnits.ToSimUnits(_movementSpeed), _body.Position.Y);

I do convert the _body.position to display units.
Comment: Is this _XNA_ or _MonoGame_?
Comment: In the future, please do not post images of your code.  Take the time to translate it into the site.
Comment: In the future don't tag questions about `monogame` with `xna` since the former is a fork of the latter and so are different products
Comment: @User52784246 In a case like this, I don't see a problem in tagging XNA and Monogame, as both frameworks are similar, and the code presented could be used in either or.
Answer: You are manually setting the position of your physics body, in your simulation world.  This is great if you are initializing the object, however, when simulating it is a bad idea.
Farseer will handle, for example, collisions in the background.  It does this by applying various forces to the bodies that are in your world.  When you move it's Position, you are not following the rules of your physics engine, you are manually moving your object in the world.
What you want to do is apply a force instead of manually moving your body.  Try playing with:
Body.ApplyForce();

Comment: It might also be worth considering kinematic vs dynamic bodies.


Can't use Python console on Gedit

Question: The error message is: Plugin loader python3 was not found
Python3 is installed...
Using Ubuntu 16.04 LTS
Answer: I believe gedit functions via plugins to highlight and console for different languages.
From a quick google search, I found a gedit bug with this comment:
'in /usr/lib/gedit/plugin choice your plugin
for example gemini.plugin
Change
[Plugin]
Loader = python
by
[Plugin]
Loader = python3
In some plugins it worked for me'
Comment: I had found this one too. it didn't work for me. The output error is: Plugin loader python was not found
Comment: @Vitor sad. Use gvim?
Comment: Never tried... is it good?
Comment: Yeah, and it's configurable so you can keep the same key bindings you've learned elsewhere, or you can learn gvim's bindings. It's basically vim with a mouse. I like it because I frequently have to open GB-sized log files, which made Gedit *super* laggy on startup. It's not necessarily as pretty as Gedit, but it *always* works.
Comment: Just remember when you start using it that if you think something is missing, it's probably just a plugin you need, or a config file to edit. It's pretty easy and stable, the two most important things for me in a text editor.

Can't use Python console on Gedit


How to check Uber Trials of Ascendancy progress?

Question: In the 3 in-game difficulties, you are able to check your progress at the plaque in Act 3, Sarn Encampment. Without doing a map run, is it possible to check your current completed trials?
Comment: Just as a comment, you will find a map trial quite fast if you spend some time on /global 820.
Answer: As of 3.0 there is a way to check the progress outside of maps.
Once you have activated the waypoint in Aspirants' plaza you will have a new icon on the world map:

Once in the Aspirants' plaza, the new "Labyrinth activation device" will show your current progress:

As I show in the image, by going with the mouse over one of the icons will show you which trial it refers to.
Comment: This is now the accepted answer. The QoL change was much needed and I'm glad they've added it in.
Answer: No. It's not possible to check without finding a trial in a map. This is a pretty common complaint and will probably get addressed at some point, but not yet.
Comment: Hopefully that gets added in. Perhaps as something in your hideout if you've unlocked Zana.
Comment: Even a chat command similar to /passives would be better than nothing.


Cooling efficiency of different fliuds?

Question: In Oxygen Not Included, what parameters are important when using a gas or liquid, pumped in a loop between the area you're trying to cool and the area you're trying to dump the heat (e.g. the cold biome)?  Are some fluids unambiguously better for this task than others?
I've seen several youtubers say that hydrogen is good for cooling - is that accurate, and if so what is the math behind it?  Hydrogen's low specific heat capacity means that when you pipe it through the cold area, it gets much cooler than, say, oxygen.  But I would expect that the effect is symmetric, and even though the hydrogen is colder when it gets to your base, it will also warm up faster and thus will not remove any more heat than if you used oxygen.
I've also seen oil used as the cooling medium.  The wiki mentions that oil did not used to be freezable so it was used as a cooling medium, but now that it has a freezing point, does it provide any advantage over, say, water?
Comment: Just realized there may be a different answer between passive cooling (run gas through the cold biome) and active cooling (thermoregulator).
Answer: Hydrogen has one of the highest Specific Heat Capacities for a gas.

I think this table is up-to-date, listing hydrogen with the highest SHC at 2.4, and a higher thermal conductivity, meaning it can exchange heat faster.
If you want to use liquids, check out this one:

However, I believe polluted water will have the same SHC as water in the next patch (rocketry). Polluted water may still be your best bet with high SHC and lower freezing point.
The high SHC of hydrogen is also useful for cooling with wheezeworts, as they cool a gas a certain number of degrees, so hydrogen will get more effective J of cooling per puff.

Cooling efficiency of different fliuds?


Elasticsearch Suggest API -Can't search numbers

Question: I'm using the Suggest API to create an autocomplete for restaurant names, but I've run into a small problem. Some restaurant names start with numbers, for example:
68 - 86 Bar & Restaurant

I want to be able to type 68 and get the restaurant back. I've tried using the whitespace analyzer, but it doesn't fix my issue.
Here is the analyze output for the restaurant name:
{
  "tokens": [
    {
      "token": "68",
      "start_offset": 0,
      "end_offset": 2,
      "type": "<NUM>",
      "position": 1
    },
    {
      "token": "86",
      "start_offset": 5,
      "end_offset": 7,
      "type": "<NUM>",
      "position": 2
    },
    {
      "token": "bar",
      "start_offset": 8,
      "end_offset": 11,
      "type": "<ALPHANUM>",
      "position": 3
    },
    {
      "token": "restaurant",
      "start_offset": 14,
      "end_offset": 24,
      "type": "<ALPHANUM>",
      "position": 4
    }
  ]
}

Here are the commands to reproduce my issue:
PUT restaurants
{ }

PUT restaurants/restaurant/_mapping
{
    "location": {
        "index_analyzer": "whitespace",
        "search_analyzer": "whitespace",
        "properties": {
            "name_suggest": {
                "type": "completion",
                "payloads": true
            }
        }
    }
}

POST restaurants/restaurant/1
{
    "name_suggest": {
        "input": [
            "68 - 86 Bar & Restaurant"
        ],
        "output": "68 - 86 Bar & Restaurant",
        "payload": {
            "id": 1067
        }
    }
}

POST restaurants/_suggest
{
    "suggestions": {
        "text": "68 - 86",
        "completion": {
            "field": "name_suggest"
        }
    }
}

I don't get any results from _suggest. Any help would be appreciated.
Answer: I've solved it, simple really, but maybe a bug?
Instead of:
PUT restaurants/restaurant/_mapping
{
    "location": {
        "index_analyzer": "whitespace",
        "search_analyzer": "whitespace",
        "properties": {
            "name_suggest": {
                "type": "completion",
                "payloads": true
            }
        }
    }
}

I now have:
PUT restaurants/restaurant/_mapping
{
    "location": {
        "properties": {
            "name_suggest": {
                "type": "completion",
                "index_analyzer": "whitespace",
                "search_analyzer": "whitespace",
                "payloads": true
            }
        }
    }
}

Comment: Just came across this problem myself, seems Simple Analyzer doesn't work for numbers... thanks for sharing!
Comment: Nice one, had the same problem
Comment: what does `"index_analyzer": "whitespace"` mean?


What is the correct way to install a washing machine drain pan?

Question: I've got a laundry room on the second floor, and when it was remodeled the contractor put in a drain pipe, but no drain pan.  At the moment, I have the washing machine hooked up, but it's away from the wall and the drain pipe.
I picked up a drain pan only to find that its shape and features weren't conducive to a good installation, so I ended up getting this one from Driptite.  I feel a lot better with this pan because it'll lay flat regardless of where I drill the hole for the drain pipe.
Now here's my issue -- I just don't know how to install it properly.  The drain pipe isn't centered with the hole in the floor, it's angled, and I don't know how to patch the area around the pipe.  This is what it looks like:

I can drill a hole in the pan in the right spot, but then how should I really make a good seal with the pan?  The pan came with a PVC fitting that is not the right size for the pipe, and I'm actually not sure how it's expected to go together.  This is what I was given with the pan:

I assume that it's supposed to go in upside down from the way it is in the picture, otherwise the water level in the pan would have to be ridiculously high before it drained.  So let's just pretent that the fitting actually fit the drain pipe (it doesn't right now) and I flip it over.  It would still sit way too high because the fitting wont go down into the floor since the pipe is off-center!
At this point, I was thinking that I would need to do the following to finish this project:

Fill in the hole in the floor with something.  If so, what should I use?  Maybe some kind of silicone sealant / caulking?  Is there a particular kind I should use for the floor?  Is this a bad idea?
Cut the hole in the drain pan at the right spot.  Sadly, this is the only step that seems pretty straightforward.  I would cut it to be as close as possible to the diameter of the fitting
Caulk around the interface between the pipe and the drain pan.  The only thing here that scares me (a lot) is that when I put the washing machine in, it'll probably shift a little, and I would expect there to be a big risk of tearing the caulk and compromising the seal.

Perhaps there's another way to deal with this?

I could try to finesse (heat up) the pipe and bend it a little to be more straight, then find a fitting that will actually fit over the pipe snugly.
I would then have to cut the pipe little by little until the screw portion of the fitting is flush with the floor
Cut a hole in the drain pan the right diameter to fit over the threaded portion of the fitting
Slide over rubber washer
Screw on nut

After typing all of this out, I bet the second approach is the "right" way to do it, though the bit about heating / bending the PVC makes me a little uneasy.
Can anyone offer their suggestions and / or solutions?
UPDATE -- I picked up a better fitting and attached it to the pipe to see how much needs to be cut:

The bottom of the wrench flats is about 1.5" from the floor, so I imagine that's how much I will need to cut.  If I do that, the bottom of the pan will have to bulge up a little where the fitting is, as I'll need to put a rubber gasket ring below the pan since the plastic nut can't screw down all of the way (the thread is tapered).  This ends up being about 3/8"... has anyone had issues with their drain pans bulging a little?  I guess my main concern is that this means the water will tend to flow away from the drain... but as long as I cut the fitting low enough and it's below the lip of the drain, I should be okay.  Perhaps it would be a good idea to cut the wrench flats off and shorten the fitting so that it can be mounted even further below the level of the floor?
Comment: What material is your drain pipe? Does it already have threads on the end?
Comment: Should be PVC from the looks of it, not ABS.  No threads on the end, just the bare pipe.
Answer: Go with your second approach of getting the right size fitting except don't bend the pipe, just deal with the angle. You pan lip should be higher than the ending (with fittings) top of the drain pipe so it can drain but that's all you need.
Why? PVC fumes are extremely toxic and you have a significantly better chance breaking the pipe than fixing the angle; then you'll have to tear up the floor to fix the pipe. A washer machine drain pan is used for worst case scenarios, not day-to-day use so as long as water can drain you'll be fine and a slight angle may actually decrease the minimum height of the drain anyways.
As for drilling the hole in the pan, mark it in place and drill it somewhere else with a sacrifice piece of wood/etc. underneath. You don't want to hold it up or anything because you'll need a decent amount of pressure to hold a bit in place and plastics like to fracture if not properly supported.
Comment: Great advice, thanks for proposing this alternative!  I had not considered the toxicity of PVC, which is ironic since I always worry about it with ABS and the 3d printer.  :)
Comment: I got the new fitting, and while it fits now, it won't clear the tile (see the top of the picture in my original post).  I could sand down one part of the fitting to make it fit, I think.  It looks like I've got some challenges ahead, and have updated my original post.
Comment: Do you know if there is a fitting that will press *inside* of the drain pipe?  While this means the hole is smaller and water won't flow as easily, maybe the installation will be easier.  It's hard to explain, but I envision the hole in the pan being the exact diameter of the drain pipe.  The pipe will stick through far enough to accomodate the gasket ring.  Then the to-be-determined fitting would be glued down over the ring, and inside of the pipe to form the seal.
Comment: Not really, you can probably find something that happens to be the right size or find it online but it is generically a bad idea and off item so it won't be stocked locally.
Answer: To do it right you need to cut the pipe down below the height of the tile. You can get a Dremel cut off wheel to cut it from the inside to the proper height.
NOTE: you can attach the bit to a drill if you dont have a Dremel.
It looks like the the pipe is too close to the tile so you will have to cut the tile too if you can not straighten out pipe. You would then glue on the fitting so the top of the threaded fitting should be about 3/4 to 1 inch above the tile.  Now drill the hole in the pan. Set in place put on gasket and screw on nut. About 1/4" of thread should be showing above nut.
Another less professional approach would be to cut the hole in the pan and let the pipe stick up through. You may need to cut pipe down so it only stick up about 1/2" higher than pan.  Then get the most expensive silicone caulk they have at your hardware store and go crazy with it. As log as the washing doesn't shake to violently it should hold. I install sunrooms and the only thing that keep the water out is silicone caulk. Can't be the cheap stuff though.
Comment: ugliness shouldn't be a huge factor with a washing machine sitting on top of it . The next owners will think you were crazy but you'll either be dead or have their money so who cares.
Comment: Can you suggest brand names / types or what specific properties of caulk to look for?
Comment: Also, do you know offhand if Dremel sells a bit for the moto-tool that can remove bits of tile?  If so, what is that bit called?
Comment: We use Tremsil 600 it comes from the sunroom manufacture. I dont know exactly what makes it better i just know that I go on repairs that homeowners try to fix it themselves and use caulk from home depot or lowes and it peels right off with your hand. I think some of that has to do with homeowner not properly cleaning surface before caulking.
Comment: mototool has their own tile cutting bit. I would just use a screw driver or nail set and a hammer to chip away the quarter inch of tile needed.  Doesnt need to look pretty its getting covered up.
Comment: Great point, thanks for the feedback.  I might just bust out the screwdriver and hammer.  :)  I'll try to go at it slowly so I don't destroy the tile any more than I need to.
Comment: Jason, I just had to upvote your comment.  :)
Answer: I used a 1 1/2" sink drain. Works awesome. Now the drain in the pan is flush with the pan. It will let all the water drain out.
Comment: Is the original question yours? If not, how was your situation the same and exactly how did you fix all of the issues asked about in the original question with fixing the angle and sealing the pipe, etc?


Inject MongDb with unity depencendy injection

Question: So far I have the following code in my Repository:
public MyRepo(ILog logger)
{
    this.Logger = logger;

    var mongoUrlBuilder = new MongoUrlBuilder(ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString);
    this.MongoClient = new MongoClient(mongoUrlBuilder.ToMongoUrl());
    this.MongoDatabase = this.MongoClient.GetDatabase("MyDB");
    this.UserCollection = this.MongoDatabase.GetCollection<MyModel>("pro");
}

And this is how I use unity DI container for instance :
var container = new UnityContainer();

container.RegisterType<IMyModel, MyModel>();

RegisterTypes(container);
return container;

How can use unity DI to inject MongoDb?
The main reason I am asking is because I want to be able to mock mongoDb and do testing on it. The requirements ask me to use Unity DI and MongoDb.
UPDATE
Eventually I went with the following patern. I Added a Db context class that look like this:
public class MongoDbContext
    {
        public const string CONNECTION_STRING_NAME = "DBContext";
        public const string DATABASE_NAME = "MyDb";

        private static readonly IMongoClient Client;
        private static readonly IMongoDatabase Database;

        static MongoDbContext()
        {
            var connectionString = ConfigurationManager.ConnectionStrings[CONNECTION_STRING_NAME].ConnectionString;
            Client = new MongoClient(connectionString);
            Database = Client.GetDatabase(DATABASE_NAME);
        }

        public IMongoCollection<TEntity> GetCollection<TEntity>()
        {
            return Database.GetCollection<TEntity>(typeof(TEntity).Name.ToLower() + "s");
        }
    }

And inside the MongoRepository use it like this:
      public class MyRepository<TModel> : IGenericMongoRepository<TModel> where TModel : BaseModel
        {
            private MongoDbContext MongoDbContext = null;

            public Exception OperationException { get; set; }
            private ILog Logger;

            public MyRepository(ILog logger)
            {
                this.Logger = logger;
                this.MongoDbContext = new MongoDbContext();
            }
      public async Task<TModel> Add(TModel item)
        {
            try
            {
                IMongoCollection<TModel> collection = this.GetCollection<TModel>();
                await collection.InsertOneAsync(item);
                return item;
            }
        catch (Exception e)
        {
        }
    }
}

Comment: wy not using repository pattern and abstracts the logic in a reposiotory
Comment: @BRAHIMKamel Could I get an example? "MyRepo" implements an interface which I am injecting in other places which use this CRUD logic inside MyRepo.
Comment: So why you need to Inject MongoDb that does not make much sense AFAK
Answer: You can refactor the repo to take the mongo database as an injectable dependency
private IMongoDatabase database;
private ILog Logger;
private IMongoCollection<MyModel> UserCollection;

public MyRepo(ILog logger, IMongoDatabase database) {
    this.Logger = logger;
    this.database = database;
    this.UserCollection = database.GetCollection<MyModel>("pro");
}

then the creation of the instance can be moved to the composition root
//Create the database instance
var mongoUrlBuilder = new MongoUrlBuilder(ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString);
var client = new MongoClient(mongoUrlBuilder.ToMongoUrl());
var database = client.GetDatabase("MyDB");

var container = new UnityContainer();
container.RegisterType<IMyModel, MyModel>();
// Register existing object instance
container.RegisterInstance<IMongoDatabase>(database);

RegisterTypes(container);
return container;

Comment: Ok but I think you are a bit away from the repository pattern goals
Comment: @BRAHIMKamel, While the OP mentions a repository doesn't necessary mean that they are applying the repository pattern. I simply wanted to demonstrate that MongoDb already provides abstractions to allow for injections and testability based on OP requirements.
Comment: I was thinking about this option, however I think that all the components that help to inject the MongoDatabase, should not belong in unity class or be as well injected in some way and configured.
Comment: @Mr.Sarunov then move it to its own class. You will still however have to pass the instance to the container some how.


Wouldn't it be better if the vertex shaders and Z-Buffer were on the CPU instead of the GPU?

Question: Wouldn't it be better if instead of unified shaders on the GPU you had separate pixels and vertex shaders again and the vertex shaders together with the Z-buffer were on the CPU die instead of on the GPU?
That way, like before, you could do the calculation of the polygon world directly on the CPU die and filter out the triangles that shouldn't be shown using the Z-buffer and then send only the triangles that should be shown to the GPU to fill the pixels?
Wouldn't this then save bandwidth from the CPU to the GPU and allow for much faster updating of 3D objects? In addition, the 3D world calculation would then be on the CPU, where the gameplay-critical physics calculation also takes place. (of course there are also physics calculations as an accessory, but these are the ones that don't affect the gameplay)
In addition, these calculations would then be able to be calculated using the clock frequency of the CPU.
And finally, there would also be a lot more RAM available, since a computer usually has more RAM than VRAM.
So why was this approach never pursued?
Comment: It was pursued, this is how it used to be done pre hardware T&L (Transform, Clipping & Lighting). The 'transform' is the triangle setup and MVP (model, view, projection operations). The 'clipping' includes occlusion (depth testing) as well as frustum clipping. Turns out to be a bit of a bottle-neck done this way.
Comment: If anything the industry is going in the opposite direction from this. Computing entire triangle visibility inside a compute shader, then sending that list off to be processed in the vertex shader. This allows triangle visibility on a per frame basis. For example, take the zbuffer from the last frame and use it to help determine if a triangle in the current frame is visible. Only the GPU has the parallel compute power to compute this sort of per frame info.
Comment: On  the CPU we usually limit ourselves to bounding volume visibility checks, which may include "occluders" in the scene, like a mountain range or large buildings. Also, the question implies that vertex and fragment shaders are put into a single shader, this is not the case, the term "unified" shader refers to many different fragment shaders rolled into one large shader, or many different vertex shaders rolled into one large shader. Those two shaders will have a seperate entry point like "main" in glsl and may be written to work together but aren't written as a single execution unit.
Comment: @lfgtm Well, there were no parallel Vertex Shaders on the CPU die. Apart from the SIMD units (MMX and SSE), there was practically nothing, and in any case there were no hundreds of vertex shaders on the CPU, as is the case with a GPU today.
Comment: @Coder Ah I see what you are saying now :). It's probably not wise to use the (already starved) CPU to transform every vertex (GPU's can do it magnitudes faster, even with the transfer via PCIE). Also, geometry is not what bottlenecks the bandwidth, more texture thrashing, and since textures are used by the fragment shaders they still need to be thrown down the PCIE bus to the GPU.
Comment: Also note that a unified shader architecture allows the programs/driver to schedule more tailored command queues and pipelines so more SM's can be used at any given time (since they are not locked into any single domain, such as vertex, fragment, compute etc). Without the unified architecture they are less likely to be fully saturated and they would stall as the fragment shaders wait for the entirety of the vertex shader programs to execute. Where would the other shaders (e.g compute) execute?
Comment: The other thing to bear in mind is during multipass rendering (which is pretty much the common standard these days), in which there can be multiple geometry passes that happen and these sometimes require feedback from the framebuffer. In these situations there would be an awful lot of data going back and forth before a single frame is even presented.
Comment: @lfgtm What i mean is putting hundreds of vertex units (hardware) on the CPU die. Thus, the CPU will be able to do it on the vertex units all in parallel and then sent the calculated data to the GPU for rasterization.
Answer:
… you could do the calculation of the polygon world directly on the CPU die and filter out the triangles that shouldn't be shown using the Z-buffer and then send only the triangles that should be shown to the GPU to fill the pixels?

The depth buffer (Z buffer) is tested per-fragment — it doesn't hide whole triangles but individual pixels of the triangles. That means that

The GPU's parallel processing is advantageous for this job. (Generally, all per-pixel operations should be done on the GPU.)
The depth test (which must happen after rasterization and before executing the fragment shader) is executed more like the fragment shader than the vertex shader.
If we did the depth tests on the CPU, then you wouldn't just be deciding which triangles to send to the GPU, but you'd have to send a list of individual pixels.

Also, if depth tests were done per-triangle, then you'd see lots of triangle-shaped artifacts whenever two objects slightly intersect. It's routine practice when putting together an environment to make overlaps, to save time on precisely modeling specific situations — for example, rocks might be placed slightly intersecting the terrain, or a door frame or arch intersecting the material of the wall it passes through. This only works because depth testing allows drawing intersecting objects near-perfectly.

Wouldn't this then save bandwidth … gameplay-critical physics calculation also takes place … calculated using the clock frequency of the CPU.

Separate from the triangles vs. pixels difference, another factor is that (in most applications) each object that the CPU tracks separately has a mesh which is made of many triangles. The CPU only has to process the object's position and rotation, then pass that to the GPU; the GPU handles (as directed by the vertex shader) transforming all the vertices of the mesh from their positions in the mesh data to their positions on screen. This operation benefits from being executed on the GPU because it is highly parallel, and because the GPU's triangle rasterizers take instructions directly from the outputs of the vertex shader.
The CPU never needs to calculate anything about thousands-to-millions of triangles, except for initially loading them from disk. That's a big advantage.


Excel/vba latebinding HTML email

Question: I have some code written in VBA designed to run in excel which is supposed to send a html email. This worked fine originally but I have tried to late bound me code, an email is still sent however the HTML appears as plain text to the recipient. The code I have is:
Dim oAPP As Object
Dim oItem As Object
Const olMailItem As Long = 0
Set oAPP = CreateObject("Outlook.Application")
Set oItem = oAPP.CreateItem(olMailItem)
With oItem
    .To = Worksheets("Emails").Cells(1, 2).Value
    .Subject = "Product set-up request"
    .BodyFormat = 2
    .Body = emailbody
    .send
End With

Answer: Change .Body = emailbody to .HTMLBody = emailbody

Excel/vba latebinding HTML email


Autolayout view swapping

Question: When swapping a sub view with another sun view, is it necessary to reapply constraints?
Do constraints need to be removed that apply to a view that is removed?
Or should they persist automatically?
Answer: Constraints are "part of" a view. When you remove a view (with removeFromSuperview), they stay with that view, provided that the view itself isn't being deallocated. You can then safely add the view again and the constraints will take care of positioning.
Compare it to a view's frame: even when you remove a view from its superview, the frame will remain the same. When you add the view back as a subview, it will be in the exact same position as it was before.
So, to answer your question: when you "swap" a view with another view, the new view won't have any constraints. This wouldn't work:
[newView addConstraints:[oldView constraints]];

It will cause a "view not in hierarchy" error, because the constraints are tied to oldView.
Comment: So, we should not try to "copy" constraints from a view to a replacement view...? I'm still trying to grok what a constraint contains. I suspect the API will get better eventually. But If I understand correctly, a constraint is tightly coupled to a relationship with one or two view objects.
Comment: Not having luck with what you describe adding it back and the frame being the same. In fact I get a zero frame.
Comment: So in practice in fact, when I re add the subview it doesn't appear. I must be doing something wrong.

Autolayout view swapping


Do you lose all history of your completed challenges when you do a prestige reset?

Question: When you do a prestige reset do you lose all history of your completed challenges? Do you get to re-do challenges for points?
I'm interested in both knowing what challenges I have completed or not completed in my entire career, and whether I'll be able to get the points for them again when I go prestige.
Answer: When you prestige all of your completed challenges (except lifetime/career challenges) are reset.  There is no history of completed challenges, and you literally start from scratch.  All challenges will pay out again when completed (both experience and money) and a special 'prestige' challenge category is opened up.
Here is a list of what you keep/lose when you prestige
Comment: Don't the career challenges stay between prestiges?
Comment: I was just looking the name of those challenges up :)  Added to the answer
Comment: that's a shame. =( cool for the getting the points over again, ick for the losing track of what you have completed.
Comment: added a link to a sticky on GameSpot that sums it up nicely
Comment: The Prestige playlist becomes available.  There is not a special prestige challenge category for this game.


Finding studs in a horse hair plaster wall?

Question: So, I've tried all the standard methods. Checked the outlet, which is screw directly into the lath(yeah, is that even up to code?!). Magnet doesn't work, I've got a rare earth magnet, and the plaster is apparently too think to pick it up(it's about an inch thick, so this doesn't make sense). I though to use the window as a base, but from the center line of where a stud would be at the edge of the window, 16 inches from there, there is no stud(I drilled it).
I'm losing my mind on this.
Comment: The outlet should be in a box that is attached to your lath. If the attachment is just with screws, you may be able to unscrew and pop the outlet box out of the wall, which should give you a way to locate the studs around that outlet.
Answer: There are numerous electronic stud finders that do not rely on magnetic signals. They use a form of density testing looking for studs, not the nails in studs. Many of them can see through plaster and wood lath.

There are a wide range of versions and prices, and, as in many things, the midrange may give you the best value.
<code> Images and links are for illustration only, not an endorsement of goods or sources.
</code>
Comment: I was really hoping to avoid spending more money, but I bought this one from HD. Will pick it up tomorrow.

Thanks.
Comment: Electronic stud finders absolutely, 100%, do NOT work in plaster walls. Certainly not reliably.    The manufacturer of the stud finder you posted states clearly that none of their stud finders work in plaster, and they recommend using their metal scanner instead.
Answer: 16"oc is just for the field, around the windows, doors & corners will vary, down to 2"s is what I've seen. Like bib said, you can get a Stud Finder, but it needs to have Deep Scan capabilities, it's especially for plaster walls.
Otherwise, just Keep Drilling. Drill a hole & stick in a crescent shape bent & inch marked coat hanger for a fairly accurate measurement to the next stud & next drilled hole. I prefer to drill on both sides of at least 2 studs to see if I'm actually dealing with a full 2" thick stud. Yours should be 2" & they usually are.
Mark your bent coat hanger where the tape measure's straight line measurement hits, so you get pretty much what your tape measurement will be on the outside of the wall. A minimum of a 1/4" hole works well to give your wire room to navigate.
Comment: I will try this, I already have a couple holes drilled where I expected studs. Thanks
Comment: It can be a chore, but easy to fill back to invisible. Great Luck!
Comment: Drilling holes to find studs!? Surely, in this day and age, there is a better way.


What thickness aluminium can be cut with a scissor?

Question: I'm thinking of cutting some thin aluminium sheet to make some covers.  I dont have a saw or skill so as a temporary solution want to use scissors or another tool(I think there is a hand tool to cut thin metal, do you know what it is called).
Whether I go for the scissors or hand tool, what is the maximum thickness of aluminium I can expect it to cut?
Thanks.
Comment: Tin snips or a fret saw : try searching
Comment: The maximum  thickness would depend on the pair of scissors. How would we know that?
Comment: Scissors and metal shears tend to leave curved, sharp edges with slivers. I prefer sheet metal nibblers, e.g. https://www.amazon.com/Draper-Expert-250mm-Hand-Nibbler/dp/B0001K9TGU/ref=as_li_ss_tl . The trick is that they remove a strip in the middle, so forces are uniform across the sheet.
Comment: try using scissors that you already have
Comment: offset aviation snips are also worth considering too (because your hand doesn't pass between the sharp edges) but if you're not in a hurry I guess the nibbler may be a cheaper option.
Comment: Some of the answer is going to be determined by how strong your hands are. If you're purchasing the aluminum, you may find it worthwhile to purchase a hacksaw to make the cuts with. They're not terribly expensive, they don't take up much space to store (if you're living in a small space), and it will make the start of a tool collection you can use to continue to DIY for the rest of your life.
Comment: I agree with drmoise I have hand nibbleRd that I can cut almost as fast as tin snips and my power nibbler is much faster.
Answer: In my experience snips can cut upto 2mm thickness, scissors upto 0.5mm thickness aluminium.
Sheet metal has sharp edges, there is a risk of minor cuts.
The sharp edges can be dulled using a file, stone, or the back of a knife blade etc.
Answer: Thicker sheets can be cut by scoring with a utility knife (from both sides for thicker material), then flexed so it snaps.


Clearing LAST_INSERT_ID() before inserting to tell if what's returned is from my insert

Question: LAST_INSERT_ID() returns the most recent id generated for the current connection by an auto increment column, but how do I tell if that value is from the last insert and not from a previous insert on the same connection?
Suppose I am using a connection from a pool, which may have inserted a row before I got the connection, and I execute an conditional insert:
insert into mytable (colA)
select 'foo' from bar
where <some condition>;
select LAST_INSERT_ID();

I have no way of knowing if the value returned is from my insert.
One way I thought of is:
@previousId := LAST_INSERT_ID();
insert into mytable (colA)
select 'foo' from bar
where <some condition>;
select if(LAST_INSERT_ID() != @previousId, LAST_INSERT_ID(), null);

Is there a way to "clear" the LAST_INSERT_ID() value, so I know it's a fresh value caused by my SQL if a non-zero value is returned?
Comment: What's wrong with using `row_count`, as Digital Chris suggested?
Comment: This is a partially-solved problem. Could you post the original problem you are trying to solve?
Answer: I agree with @Digital Chris's answer, that you should not be determining whether an insertion succeeded or failed via inspection of the value returned by LAST_INSERT_ID(): there are more direct routes, such as the affected row count.  Nevertheless, there might still be some requirement to obtain a "clean" value from LAST_INSERT_ID().
Of course, one problem with your proposed solution (of comparing against the pre-insertion value) is that it might happen that the insertion was successful and that its assigned auto-incremented value is coincidentally the same as that of the previous insertion (presumably on another table).  The comparison could therefore lead to an assumption that the insertion failed, whereas it had in fact succeeded.
I recommend that, if at all possible, you avoid using the LAST_INSERT_ID() SQL function in preference for the mysql_insert_id() API call (via your driver).  As explained under the documentation for the latter:

mysql_insert_id() returns 0 if the previous statement does not use an AUTO_INCREMENT value. If you need to save the value for later, be sure to call mysql_insert_id() immediately after the statement that generates the value.
[ deletia ]
The reason for the differences between LAST_INSERT_ID() and mysql_insert_id() is that LAST_INSERT_ID() is made easy to use in scripts while mysql_insert_id() tries to provide more exact information about what happens to the AUTO_INCREMENT column.

In any event, as documented under LAST_INSERT_ID(expr):

If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID().

Therefore, before performing your INSERT, you could reset with:
SELECT LAST_INSERT_ID(NULL);

This also ought to reset the value returned by mysql_insert_id(), although the documentation suggests the call to LAST_INSERT_ID(expr) must take place within an INSERT or UPDATE statement—may require testing to verify.  In any event, it ought to be pretty trivial to create such a no-op statement if so required:
INSERT INTO my_table (my_column) SELECT NULL WHERE LAST_INSERT_ID(NULL);

It may be worth noting that one can also set the identity and last_insert_id system variables (however these only affect the value returned by LAST_INSERT_ID() and not by mysql_insert_id()):
SET @@last_insert_id := NULL;

Answer: You speculate that you might get the previous LAST_INSERT_ID(), but practically, I don't see where this case would happen. If you're doing a conditional insert, you would HAVE to check whether it was successful before taking next steps. For example, you would always use ROW_COUNT() to check inserted/updated records. Pseudo-code:
insert into mytable (colA)
select 'foo' from bar
where <some condition>;

IF ROW_COUNT() > 0
    select LAST_INSERT_ID();
    -- ...use selected last_insert_id for other updates/inserts...
END IF;

Answer: Use ROW_COUNT() to determine if your conditional insert attempt was successful, and then return LAST_INSERT_ID() or a default value based on that:
select IF(ROW_COUNT() > 0, LAST_INSERT_ID(), 0);

Answer: Since LAST_INSERT_ID() is full of gotchas, I use an AFTER INSERT trigger to record the ID in a log table and in a manner consistent with the problem I'm trying to solve.
In your scenario, since the insert is conditional, use a unqiue identifier to "tag" the insert, then check for the presence of that tag in the insert log.  If the identifying tag is present, your insert occurred and you have the inserted ID.  If the identifying tag is not present, no insert occurred.
Reference Implementation
DELIMITER $$
CREATE TRIGGER MyTable_AI AFTER INSERT ON MyTable FOR EACH ROW
BEGIN
    INSERT INTO MyTable_InsertLog (myTableId, ident) VALUES (NEW.myTableId, COALESCE(@tag, CONNECTION_ID()));
END $$
DELIMITER ;

CREATE TABLE MyTable_InsertLog (
    myTableId BIGINT UNSIGNED PRIMARY KEY NOT NULL REFERENCES MyTable (myTableId),
    tag CHAR(32) NOT NULL
);

Example Usage
SET @tag=MD5('A');
INSERT INTO MyTable SELECT NULL,colA FROM Foo WHERE colA='whatever';
SELECT myTableId FROM MyTable_InsertLog WHERE tag=@tag;
DELETE FROM MyTable_InsertLog WHERE tag=@tag;

If the insert succeeds, you will get rows from the select -- and those rows will have your ID.  No rows, no insert.  Either way, delete results from the insert log so that you can reuse that tag in subsequent calls.
Comment: after insert trigger wouldn't help. my app code needs the id of the row just added, but only if it *was* added. i need to be able to distinguish that the last insert id returned from the function is from the sql i just executed
Comment: @Bohemian: Sure you can, if I'm understanding your use case correctly.  See my edit for working example.
Answer: The LAST_INSERT_ID() function has a rather narrow scope of application: as MySQL does not support SQL SEQUENCEs, this is used to create a transaction that INSERTs data consistently into multiple tables, if one references the surrogate key from the other table:
CREATE TABLE foo (id INTEGER PRIMARY KEY AUTO_INCREMENT, value INTEGER NOT NULL);
CREATE TABLE bar (id INTEGER PRIMARY KEY AUTO_INCREMENT, fooref INTEGER NOT NULL);
INSERT INTO foo(value) VALUES ('1');
INSERT INTO bar(fooref) VALUES (LAST_INSERT_ID());

If you really want to use this in a conditional insert, you need to make the second INSERT conditional as well by joining the inserted values against the SELECT from the first INSERT and subsequently throwing away the extra columns (so that the second INSERT also has zero or one row).
I'd advise against that, though. The conditional insert in this manner is already somewhat brittle, and building on top of it will not add stability to your application.
Comment: No good. There is no second insert. The last insert id is used outside the database by the app code. Besides, this does't answer the question either.
Comment: The answer is "you're not expected to use `LAST_INSERT_ID()` in this way." That is why I commented asking for a description of the original problem.
Comment: I want to get the last inserted id from the sql into my application, but my sql does a conditional insert, so I need to be able to distinguish between the last inserted id coming from my insert or the previous insert for the connection I'm using. If it's not from my insert (attempt), I want it to be zero or null.
Comment: That is not a supported use case. Even if you find a solution that works, it may just break at any time in the future, and you get to keep the pieces.


How to repeat firing api call out in a while loop till there are no results left in response

Question: I have an API running in Azure function which needs to be run multiple times in a loop so that i can get all the results .
The first API when it runs. It returns results with locator parameter in the heaader. Using the locator parmater we need to hit the api inside a loop to get all the results. locator paramter will always have a new value when the api is hit.
ANd each time i want to write the response into a new file. How to call the same api with different locator parameter till the locator value becomes null

const getjobresult = async(t) => {

  const requestOptions = {
    method: "GET",
    headers: {
      "Content-Type": 'application/json',
      "Accept": "text/csv",
      "Authorization": "Bearer " + t
    },
    redirect: "follow"
  };

  // This below api is called for first time where it returns 500000 records (which i am writing in a file ) and a parameter locator which contains a value through which we will get another set of record
  const resp = await fetch("https://someapi.test.com/services/data/v59.0/jobs/query/750Pw000005PqqBIAS/results?maxRecords=500000", requestOptions)
  const json = await resp.text();
  const fields = ['Id']
  let aa = resp.headers.get('locator')
  const rows = json.split((/\r?\n|\r/)).slice(1);
  let lsttis = []
  rows.forEach(res => {
    let tis = {
      'tablename': 'TestTable'
    };
    tis.AccessLevel = 'Read';
    tis.ParentId = res.replace(/['"]+/g, '')
    tis.RowCause = 'Manual'
    tis.UserOrGroupId = '11111111'
    lsttis.push(tis)
  })

  if (lsttis.length > 0) {
    await creatcsvfile(lsttis)
  }
  // In this below code i am trying to refire the api using locator parameter inside a while loop.Everytime when api gets hit inside while loop, it returns a new locator value. This while loop should run till resp1.headers.get('locator') becomes null and everytime the response should be written in
  // new file.
  var i = 0;
  while (true) {
    i++;
    const resp1 = await fetch("https://someapi.com/services/data/v59.0/jobs/query/750Pw000005PqqBIAS/results?locator=" + aa + "&maxRecords=500000", requestOptions)
    const json1 = await resp1.text();
    if (resp1.headers.get('locator') === undefined) {
      break;
    }
    const rows1 = json1.split((/\r?\n|\r/)).slice(1);
    rows1.forEach(res => {
      let tis = {
        'tablename': 'TestTable'
      };
      tis.AccessLevel = 'Read';
      tis.ParentId = res.replace(/['"]+/g, '')
      tis.RowCause = 'Manual'
      tis.UserOrGroupId = '11111111'
      lsttis.push(tis)
    })
    // in this i am sending the i for creating new file for every response.
    if (lsttis.length > 0) {
      await creatcsvfile(lsttis, i)
    }
  }
}

const creatcsvfile = async(data, t) => {
  const fields = ['AccessLevel', 'ParentId', 'RowCause', 'UserOrGroupId']
  let csv = await json2csv.parse(data, {
    fields
  });
  //console.log(csv)
  fs.writeFileSync('./test' + t + '.csv', csv)
}
Comment: I don't see you assigning the _new_ locator value to `aa` anywhere.
Comment: yes.. i am struggling how to add it correctly .. i have already added it for first time .  let aa = resp.headers.get('locator')
Comment: And what is the problem now, with doing essentially the same thing again, after your request inside the loop finished? `aa = resp1.headers.get('locator')`
Comment: problem is i want to write it in a more optimized way.
Comment: Then put the first request into the loop as well. No real good reason to make that _before_ the loop here anyway.
Answer: So, assuming that you code works and you are only talking about optimisations I can suggest some tips:
First thing that comes to my mind: don't use var in JavaScript. Hoisting issues can be a problem (not your case), but I really recommend to avoid it.
Second: create functions to segregate duties, create a function like creatcsvfile that you made. Crate one just to fetch/parse and another one just to execute the for loop inside the rows. This will create a cleaner and readable code.
Third: you can erase the first api call and all the lines outside your while loop and just adjust things inside it (so you can call all of these just only time), for example:
let aa = 0

So when you hit the API it will send the locator but it will know that its a first call. If your api doesn't support this, you can crate "aa" as undefined and pass to fetch only when its initialised. Use JS template strings like this:
let aa;
const resp1 = await fetch(`https://someapi.com/services/data/v59.0/jobs/query/750Pw000005PqqBIAS/results?${aa? "locator="+aa:""}&maxRecords=500000`, requestOptions)

Basically this works as the same, but it doesn't repeat the first declaration and eliminates 20 unnecessary lines.


plpgsql : how to reference variable in sql statement

Question: I am rather new to PL/pgSQL and don't know how to reference a variable in a SELECT statement.
In this following function the SELECT INTO always returns NULL:
$body$
DECLARE
 r RECORD;
 c CURSOR FOR select name from t_people;
 nb_bills integer;
BEGIN
 OPEN c;
 LOOP
   FETCH c INTO r;
   EXIT WHEN NOT FOUND;

   RAISE NOTICE 'name found: %', r.name;
   SELECT count(bill_id) INTO nb_bills from t_bills where name = r.name;
 END LOOP;

END;
$body$

RAISE NOTICE allows me to verify that my CURSOR is working well: names are properly retrieved, but for some reason still unknown to me, not properly passed to the SELECT INTO statement.
For debugging purpose, I tried to replace the variable in SELECT INTO with a constant value and it worked:
SELECT count( bill_id) INTO nb_bills from t_bills where name = 'joe';

I don't know how to reference r.name in the SELECT INTO statement.
I tried r.name, I tried to create another variable containing quotes, it is always returning NULL.
I am stuck. If anyone knows ...
Comment: The reference `r.name` is correct. When you run `select p.name, count(b.bill_id) from t_people p join t_bills b on t.name = b.name group by name` in a SQL client, what does it return?
Comment: Where and how you are checking `nb_bills` value? Show whole code if it possible.
Comment: The ***header*** showing `IN` and `OUT` parameters, RETURN type, language declaration etc. is an essential part of the function. Remember to always include it - as well as your ***version*** of Postgres.
Comment: Hi an thanks for your reply.
What I mean to say is the following:

   -- r.name contains 'joe'
   SELECT count(bill_id) INTO nb_bills from t_bills where name = r.name;
   RAISE NOTICE 'nb_bills: %', nb_bills; -- shows NULL

but

   SELECT count(bill_id) INTO nb_bills from t_bills where name = 'joe';
   RAISE NOTICE 'nb_bills: %', nb_bills; -- shows 5

Is there a way I could see the SQL query submitted ? I tried to activate the log feature but it does seem not show this kind of SQL statement. Only call to the procedure is logged.
Answer:
the SELECT INTO always returns NULL

not properly passed to the SELECT INTO statement.

it is always returning NULL.

None of this makes sense.
SELECT statements do not return anything by itself in PL/pgSQL. You have to either assign results to variables or explicitly return results with one of the available RETURN variants.
SELECT INTO is only used for variable assignment and does not return anything, either. Not to be confused with SELECT INTO in plain SQL - which is generally discouraged:

Combine two tables into a new one so that select rows from the other one are ignored

It's not clear what's supposed to be returned in your example. You did not disclose the return type of the function and you did not actually return anything.
Start by reading the chapter Returning From a Function in the manual.
Here are some related answers with examples:

Can I make a plpgsql function return an integer without using a variable?
Return a query from a function?
How to return multiple rows from PL/pgSQL function?
Return setof record (virtual table) from function

And there may be naming conflicts with parameter names. We can't tell unless you post the complete function definition.
Better approach
That said, explicit cursors are only actually needed on rare occasions. Typically, the implicit cursor of a FOR loop is simpler to handle and cheaper:

Truncating all tables in a Postgres database

And most of the time you don't even need any cursors or loops at all. Set-based solutions are typically simpler and faster.


Direct sum of injections is injection, categorically

Question: Given $R$-module maps $\{f_i \colon M_i \to N_i\}_{i \in I}$, the universal properties of the direct sums $\oplus M_i$ and $\oplus N_i$ give a unique map $\oplus f_i \colon \oplus M_i \to \oplus N_i$ such that $M_j \xrightarrow{f_j} N_j \to \oplus N_i$ agrees with $M_j \to \oplus M_j \xrightarrow{\oplus f_j} \oplus N_i$ for each $j \in I$. (The unlabeled maps are the inclusions.)
If we use the explicit constructions of $\oplus M_i$ and $\oplus N_i$ as sets of tuples $\{(m_i)_{i \in I} \mid m_i \in M_i\}$ and $\{(n_i)_{i \in I} \mid n_i \in N_i\}$, then the map $\oplus f_i$ is given explicitly by $(m_i) \mapsto (f(m_i))$. Now it's easy to see that if $f_i$ is an injection for all $i$, then $\oplus f_i$ is, too.
However, I was wondering if there's a way to reason about injectivity of $\oplus f_i$ directly from the universal properties, without using any particular construction for the direct sum.
Comment: Proceeding using only the universal property of direct sum and the universal property for kernels gets you a relation $ker(\bigoplus\limits_{i\in I} f_i)\circ h = \bigoplus\limits_{i\in I} (ker(f_i))$. But, the furthest I could get here was using injectivity of $f_i$ and the abelian category property to show $h$ was the zero map. Basically, this was in effort to show the kernel of the direct sum map was trivial. But you get a free condition in the end. Using biproducts (in the finite case) didn't help, nor did taking cokernels. I don't think it is provable via universal properties alone..
Answer: If $C$ is a category with infinite coproducts, taking $I$-indexed coproducts is a functor $\bigoplus : C^I \to C$ which is left adjoint to the diagonal functor $\Delta : C \to C^I$, and hence which preserves colimits. This implies that it preserves epimorphisms, since those are the morphisms with trivial cokernel pair (in an abelian category substitute "cokernel"). However, there's no abstract nonsense reason it should preserve monomorphisms; those are the morphisms with trivial kernel pair (again, in an abelian category substitute "kernel"), so this would be a limit-commuting-with-colimit type scenario, which usually requires special hypotheses.
Here you can find a counterexample by Zhen Lin in the abelian category $\text{Sh}([0, 1])^{op}$, the opposite of the category of sheaves of abelian groups on the interval.


How do I take multiple filenames from the Raku command line?

Question: This Raku program works as I expect:
sub MAIN($name) { say "Got $name" }

I can pass a single name on the command line:
$ raku m1.raku foo
Got foo

The obvious extension, however,
sub MAIN(@names) { say "Got $_" for @names }

doesn't work:
$ raku mm.raku foo
Usage:
  mm.raku <names>
$ raku mm.raku foo bar
Usage:
  mm.raku <names>

What am I doing wrong?
Answer: What @cjm said.
However, you can go a little further than that, checking whether the names you specified, are actually files.  And produce an error message if they are not.  The trick is to use multi-dispatch:
subset File of Str where *.IO.f;

multi sub MAIN(*@files where @files.all ~~ File) {
    say "These are all files: @files.join(",")";
}
multi sub MAIN(*@files) {
    say "These are *NOT* files: @files.grep(* !~~ File).join(",")";
}

The first candidate will be run if all the names specified on the command line are in fact files. The second candidate will be run if the first didn't fire, implying that not all names specified are in fact files.
Answer: You must use the slurpy array signature for this:
sub MAIN(*@names) { say "Got $_" for @names }

Works as desired:
$ raku mm.raku
$ raku mm.raku foo
Got foo
$ raku mm.raku foo bar
Got foo
Got bar

Answer: There is a special $*ARGFILES variable which provides a way to iterate over files passed in to the program on the command line.
#!/usr/bin/raku

for $*ARGFILES.handles -> $fh {

    say $fh;
}

$ ./enum_files.raku links.txt words.txt
IO::Handle<"links.txt".IO>(opened)
IO::Handle<"words.txt".IO>(opened)

We can use its lines method to read lines of the given files.
#!/usr/bin/raku

.say for $*ARGFILES.lines

$ ./read_lines.raku words.txt words2.txt
sky
cloud
cup
rock
war
tea
coffee
falcon
...

Answer: @cjm's answer is the proper one to your question.  But just as Jan said there's another way:
say "Got:" @*ARGS
Where @*ARGS is a dynamic variable defined as the args on the command line.
$*ARGFILES has some extra nuance to it. Outside of main gets its values from @*ARGS or $*IN if there are no args.  Inside main it just does $*IN.


hibernate batch insert - how flush works?

Question: I need to insert a lot of data in a database using hibernate, i was looking at batch insert from hibernate, what i am using is similar to the example on the manual:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
    if ( i % 20 == 0 ) { //20, same as the JDBC batch size
        //flush a batch of inserts and release memory:
        session.flush();
        session.clear();
    }
}

tx.commit();
session.close();

but i see that flush doesn't write the data on the database.
Reading about it, if the code is inside a transaction then nothing will be committed to the database until the transaction performs a commit.
So what is the need to use flush/clear ?  seems useless, if the data are not written on the database then they are in memory.
How can i force hibernate to write data in the database?
Thanks
Answer: The data is sent to the database, and is not in memory anymore. It's just not made definitively persistent until the transaction commit. It's exacltly the same as if you executes the following sequences of statements in any database tool:
begin;
insert into ...
insert into ...
insert into ...
// here, three inserts have been done on the database. But they will only be made
// definitively persistent at commit time
...
commit;

The flush consists in executing the insert statements.
The commit consists in executing the commit statement.
Answer: The data will be written to the database, but according to the transaction isolation level you will not see them (in other transactions) until the transaction is committed.
Use some sql statement logger, that prints the statmentes that are transported over the database connection, then you will see that the statmentes are send to the database.
Answer: For best perfromance you also have to commit transactions.  Flushing and clearing session clears hibernate caches, but data is moved to JDBC connection caches, and is still uncommited ( different RDBMS / drivers show differrent behaviour )  - you are just shifting proble to other place without real improvements in perfromance.
Answer: Having flush() at the location mentioned saves you memory too as your session will be cleared regularly. Otherwise you will have 100000 object in memory and might run out of memory for larger count. Check out this article.


Inverting pressure plate without powering piston

Question: I'm working on a trap, where if a person steps on a pressure plate, then the pistons deactivate and a pit forms in front of the plate. I decided to do this like a vertical jeb's door (a piston door in a flat surface.)
The issue I am having is that the pressure plate is powering the upwards piston directly next to it. Is there a way to invert the charge from the presureplate without powering the piston? Preferably without moving the plate away from the pistons.
Side view 1 shows how I implemented the jeb's door.
The issue is that the pressureplate that triggers the trap is also activating the [s^] piston directly next to the plate. I hope my diagrams are understandable, otherwise I can provide screenshots. :3

[p] = pressureplate
[d] = dirt
[s] = stickypiston (>,<,^,v = Piston Direction extended)
[r] = redstone
[1-4] = repeater with 1-4 number of ticks
[a] = air
|[b]| = Section for Side view
[t] = redstoneTorch

Top view
<code>[p][d][d][d][p]
</code>
Side view 1 (|[b]| for side view 2)
<code>[d][d][d][d]|[d]|[d]
[r][1][s][>]|[^]|[r]
[d][d][s][>]|[s]|[d]
[d][d][d][d]|[d]|[t]
</code>
Side view 2 (|[b]| for side view 1)
<code>[p][a]|[a]|[a]
[d][d]|[d]|[d]
[r][^]|[^]|[^]
[d][s]|[s]|[s]
</code>
Comment: I half get your diagrams, but I think screen shots would make it easier to understand :)
Answer: I am not sure if I understood correctly, but you can use a sticky piston under the pressure plate to cut off a wire that powers the other three pistons:

And with the pressure plate 'on':

You can power the side pistons with repeaters, if you want the ground to be flat.
Comment: Clever idea, didn't think of this method of powering. Thanks for the help!
Answer: You cannot invert a pressure plate, but you can move the piston away from the plate.
I don't quite understand your diagram, but from your description of what you're trying to do I've come up with a solution.

I hope you can see all the wiring in this picture, the other side is an exact mirror of this one, the repeaters are set to two ticks and all the pistons are sticky.
Comment: Its a really nice alternative method, but not exactly what I'm looking for. The issue being that I can't make the top layer flat since redstone is in the way. That is, if I understand your  diagram correctly.


Laptop freezes after suspend

Question: Recently I've experienced a problem with my laptop. It suspended perfectly after closing the lid, and everything was ok after opening it.
The issue is that now the laptop freezes when I suspend it (or close the lid). The screen goes to black (but bright black, it is not off) and the laptop remains on. I've tried changing the drivers to the NVIDIA one (like here) but nothing new, and I also tried to changesudo gedit /etc/default/grub, but the same.
I would also like to point out that I've been recently installing a couple of VMs in VirtualBox so that I had to enable the virtualization and the booting in insecure mode, just in case it has something to do with my problem.
And also, a couple of times I could read a message kind of Freezing of tasks failed after 20.01 seconds (3 tasks refusing to freeze, wq_busy=0) after suspend.
I would apreciate your help.
Technical details:

Lenovo U31
Intel Core i5 5200U CPU 2.20 GHz
Linux 4.10.0-32-generic

UPDATE: Some output.
jorge@jorge-Lenovo-U31-70:~$ ls -alt /var/crash/
total 2656
drwxrwsrwt  2 root     whoopsie    4096 ago 16 18:14 .
-rwxrwxrwx  1 root     whoopsie       0 ago 16 18:14 .lock
-rw-------  1 whoopsie whoopsie       0 ago 12 18:16 _usr_lib_virtualbox_VirtualBox.0.uploaded
-rw-r--r--  1 root     whoopsie       0 ago 12 18:16 _usr_lib_virtualbox_VirtualBox.0.upload
-rw-r-----  1 root     whoopsie 2660216 ago 12 18:15 _usr_lib_virtualbox_VirtualBox.0.crash
-rw-------  1 whoopsie whoopsie       0 ago 12 14:52 _usr_sbin_update-apt-xapian-index.0.uploaded
-rw-r--r--  1 root     whoopsie       0 ago 12 14:52 _usr_sbin_update-apt-xapian-index.0.upload
-rw-r-----  1 root     whoopsie   45613 ago 12 14:52 _usr_sbin_update-apt-xapian-index.0.crash
drwxr-xr-x 13 root     root        4096 ago 12 14:40 ..

jorge@jorge-Lenovo-U31-70:~$ free -h
              total        used        free      shared  buff/cache   available
Memoria:        7,7G        660M        6,5G        137M        590M        6,7G
Swap:          7,9G          0B        7,9G

jorge@jorge-Lenovo-U31-70:~$ swapon -s
Filename                Type        Size    Used    Priority
/dev/sda3                               partition   8299516 0   -1

 jorge@jorge-Lenovo-U31-70:~$ sudo blkid
/dev/sda1: UUID="8BFC-B5D5" TYPE="vfat" PARTLABEL="EFI System Partition" PARTUUID="afdaf7bb-755c-46d8-80d2-247bec22b9c3"
/dev/sda2: UUID="99c6efde-2951-471d-954e-9250b95605d6" TYPE="ext4" PARTUUID="24463a23-fe3d-4904-b687-ee2a0bed4968"
/dev/sda3: UUID="85f4ca7a-9e8f-42c1-ab7d-765e18fae6a4" TYPE="swap" PARTUUID="39c2bbcd-4868-477b-8c31-3032c613c201"

jorge@jorge-Lenovo-U31-70:~$ cat /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sda2 during installation
UUID=99c6efde-2951-471d-954e-9250b95605d6 /               ext4    errors=remount-ro 0       1
# /boot/efi was on /dev/sda1 during installation
UUID=8BFC-B5D5  /boot/efi       vfat    umask=0077      0       1
# swap was on /dev/sda3 during installation
UUID=85f4ca7a-9e8f-42c1-ab7d-765e18fae6a4 none            swap    sw              0       0

Today ago 16 I have experienced the freeze lots of times. When freezing, no text is shown in the screen if I press ESC, but if I press the power buttom then the elementary symbol appears in screen (as in the booting), and if I press ESC there, then I obtain some text:

UPDATE 2: After another freeze (and turning the laptop off with the power button), I start the laptop and I get a error message related to the suspend:
Comment: @heynnema yes, this is Elementary OS Loki, based on Ubuntu 16.04.2 LTS
Comment: This will be a little difficult to troubleshoot long distance, but lets try a few things. 1) try to suspend it, when it freezes, hit the ESC key... does it bring you to a text screen? 2) show me `ls -alt /var/crash` and `free -h` and `swapon -s` and `sudo blkid` and `cat /etc/fstab`. Copy/paste that output into your question, not the comments please. Ping me at `@heynnema` when you have the info for me.
Comment: Read `man pm-action` - it will leed you to the scripts the system runs when you Suspend, Hibernate, UnSuspend and UnHibernate. These scripts are meant to "help". You may have to adjust one, or write your own.
Comment: @Minkowski see my partial answer. Report back.
Comment: Is this Elementary Linux, or what Ubuntu flavor/version?
Comment: @Minkowski technically, we don't support Elementary OS here, even if it is a Ubuntu derivative... but here we are :-)
Comment: @heynnema I know and that's why  I really, really appreciate your help :)
Answer: In terminal...

cat /etc/initramfs-tools/conf.d/resume # if exists, show me the contents
dpkg -l intel-microcode | grep ii # see if this is installed, if not:

sudo dpkg -i intel-microcode

sudo cp /etc/fstab /etc/fstab.bak # backup fstab file
gksudo gedit /etc/fstab # edit fstab

change this line:
UUID=8BFC-B5D5  /boot/efi       vfat    umask=0077      0       1

to this:
UUID=8BFC-B5D5  /boot/efi       vfat    defaults      0       1

Then reboot. Retest suspend.
Go to https://www.memtest86.com/ and download the free memory diagnostic and run at least one full pass.
Update #1:

start the Disks application
select the disk in the left pane
click on the "hamburger" icon
select SMART Data & Tests
review the data
run the tests

Update #2:

/etc/initramfs-tools/conf.d/resume looks fine
we installed intel-microcode

In terminal...
sudo apt-get update
sudo apt-get install intel-microcode

Update #3:

go to https://www.memtest86.org
download the free memory diagnostic
run at least one complete pass

Update #4:

check your motherboard BIOS version and go to the manufacturer's web site and make sure it's the latest version for your make/model #. If not, update it asap.

Update #5:

we found that the suspend problem didn't occur when we disconnected the wireless and used a wired connection
we uninstalled the broadcom wl kernel module that was tainting the kernel
we'll also replace the r8169 driver

In terminal...
sudo apt-get purge bcmwl-kernel-source

pending sudo apt-get install r8168-dkms

pending BIOS update

Comment: I'm afraid suspend doesn't work yet... About the first code, here you are: `jorge@jorge-Lenovo-U31-70:~$ cat /etc/initramfs-tools/conf.d/resume
RESUME=UUID=85f4ca7a-9e8f-42c1-ab7d-765e18fae6a4` . I changed the line but my laptop still freezes before suspending. And please check the URL you sent me because I get a spam webpage (facebook sort).
Comment: @Minkowski your resume file looks fine. Did you check the `intel-microcode`? Sorry about the bad URL, I've fixed it.
Comment: @Minkowski please do the memtest, and update #1 in my answer.
Comment: Having `intel-microcode` installed (checked), I ran `dpkg -l intel-microcode | grep ii` but I obtain nothing, no text is shown.
Comment: @Minkowski then you need to install it. `sudo apt-get update` and `sudo apt-get install intel-microcode` then reboot, and retest.
Comment: **Update**: When restarting the laptop after a freeze, I have just obtained a error message related with suspend/resume failure. I will add it to the question, I feel like it might be the key.
Comment: Off we go, `jorge@jorge-Lenovo-U31-70:~$ dpkg -l intel-microcode | grep ii`
`ii  intel-microcode 3.20151106.1 amd64        Processor microcode firmware for Intel CPUs`
Comment: @Minkowski I haven't seen the newest error message yet...
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/64000/discussion-between-minkowski-and-heynnema).

Laptop freezes after suspend


$f$ is continuous, $f(0)=1$, $f(m+n+1)=f(m)+f(n)$ for all real $m,n$. Show that $f(x)=1+x$ for all real $x$.

Question: In order to prove this, I had to back the proof up into a number of Lemmas. I am wondering if my method was reasonable, or if there was a more general or expedient path I might have taken? (I have left out all of the actual proofs with the exception of Lemma 6.)
Lemma 1:
For any $a\in\mathbb{R}$,   $$f(a)=1+a \implies f(-a)=1-a.$$
Lemma 2:
For any $n\in\mathbb{N}$, $\quad f(n)=1+n$.
Lemma 3:
For any $n\in\mathbb{N}$, $\quad f\left(\frac{1}{n}\right)=1+\frac{1}{n}$.
Lemma 4:
For any rational $\frac{m}{n}$, such that $0<m<n$, $\quad f\left(\frac{m}{n}\right)=1+\frac{m}{n}$.
Lemma 5:
For any $a\in\mathbb{Q}$, $\quad f(a)=1+a$.
Lemma 6:
For any irrational $x, \quad f(x)=1+x.$
Proof: Assume, for some irrational $x, \quad f(x)\neq 1+x$.
Say $f(x)>1+x$, then $$f(x)-(1+x)=t>0$$
and so, for any rational $a<x$ $$ f(x)-(1+a)>t.$$
However, by the definition of continuity, with $\epsilon=t$, for any rational satisfying $$x-\delta<a<x \quad\implies f(x)-(1+a)<t,$$
which is a contradiction. A similar argument shows that assuming $f(x)<1+x$ also leads to a contradiction, and it follows that $$f(x)=1+x.\quad \square$$
Comment: For lemma 6, you could use sequential continuity: for every irrational $x$, you can find a rational sequence $x_n\to x$ and $f(x)=\lim_{n\to \infty}f(x_n)$.
Comment: I'd say the logic looked very good...hard to believe it could be greatly streamlined.
Answer: If you make a translation $g(x) = f(x-1)$ the problem reduces to finding all continuous functions $g$, such that $g(1) = 1$, $g(x+y) = g(x) + g(y)$ for all real $x, y$. The second of these makes $g$ what is called an additive function; is a very standard functional equation which leads to $g(x)= g(1)x$ when any of the following additional assumptions is satisfied:

$g$ is continuous at some point $x_0$ (you have that it is continuous everywhere, but it would have been enough to know it is continuous at any one arbitrary point)
$g$ is bounded on some interval
$g$ is monotonic on some interval

The proof, in general, proceeds exactly along the lines of those lemmas. But if you are allowed to use that a continuous additive function is always $g(x) = g(1)x$ as a theorem, you can "skip" all the lemmas.
Answer: By setting $m=0$, we see that $f(x+1)=f(x)+1$ for all real $x$. Since $f(0)=1$ we have $f(n)=n+1$ for all $n\in\Bbb Z$.
Lemma. $f(\frac n{2^m}) = 1+\frac n{2^m}$ for all $n,m\in\mathbb Z$.
Proof. If $m<0$ then the statement is simply a special case of $f(n)=n+1$. Suppose thus that $m\geq0$. I will use induction over $m$. Note that for $m=0$ the claim is still a special case of $f(n)=n+1$ and thus true.
Induction Step. Suppose that the Lemma is true for some $m\in\mathbb N\cup\{0\}$. Then for all $n\in\mathbb Z$,
\begin{split}
2\cdot f\left(\frac{n}{2^{m+1}}\right)&=f\left(\frac{n}{2^{m+1}}\right)+f\left(\frac{n}{2^{m+1}}\right)\\
&=f\left(\frac{n}{2^{m}}+1\right)\\
&=f\left(\frac{n}{2^{m}}\right)+1\\
&= \frac{n}{2^m}+2.
\end{split}
Between the first and second line I used the original assumption on $f$ and between the third and fourth line I used the inductive assumption.
It follows that $f\left(\frac{n}{2^{m+1}}\right)=\frac{n}{2^{m+1}}+1$. $\square$
Since $S:=\{\frac{n}{2^m}\mid n,m\in\mathbb Z\}$ is dense in $\Bbb R$, $f$ is continuous, and $f(x)=1+x$ for all $x\in S$, it follows that
$$\bbox[5px,border:2px solid #C0A000]{f\equiv 1+x \text{ on } \mathbb R.}$$


How to naturally understand Inclusion-Exclusion Principle.

Question: Workbook question:

Professor is giving an exam. (A) How many ways are there to assign five proctors to the three exam rooms, so that each exam is proctored by at least one person?
Answer:
$n = 5, a = 3$
$3^5 - \binom{3}{1}(3-1)^5 + \binom{3}{2}(3-2)^5 = 150$

I understand the answer in terms of the formula, but I don't understand the answer in terms of the principle, or in any "common sense" way. I can't visualize how the Inclusion-Exclusion principle applies to this sort of situation.
Answer: There are $3^5$ ways to distribute the five proctors to the three rooms. But some of the distributions leave a room unsupervised: for each of the $\binom{3}{1}$ rooms, there are $(3-1)^5$ ways to distribute the five proctors to the other two rooms, we're at $3^5 - \binom{3}{1}(3-1)^5$ now. But the distributions where two rooms were left unsupervised are subtracted for each of the unsupervised rooms, so twice. Thus we must correct and add the number of distributions that leave two rooms unsupervised. There are $\binom{3}{2}$ combinations of two rooms, and for each of these, there are $(3-2)^5$ ways to distribute the five proctors to the remaining rooms. Since with three rooms and more than $0$ proctors, there is no way to leave three rooms unsupervised, so we can stop now, at $3^5 - \binom{3}{1}(3-1)^5 + \binom{3}{2}(3-2)^5$.
Comment: If all five proctors are put in the same room, the other two remain unsupervised.
Comment: Why do some of the distributions leave a room or two supervised?


How can I straighten out a bent threaded rod?

Question: I recently got a 1/2" acme screw for a project that has a deflection of approximately an eighth of an inch deflection.  One would not think that it would be a big deal, but is is making alignment quite difficult on my project.  Is there any way to straighten out a threaded rod?
Answer: I've been able to manually straighten Acme leadscrew stock in the past by bending it down against a rigid surface, and checking its straightness by rolling it along a piece of scrap window glass (guaranteed to be flat). Rinse and repeat until you either bend it to within an acceptable tolerance, or you ruin it and have to buy a new one--which in this case is no big deal, since the one you've already got is already useless for your project.


The mobile version slides into two slides: left to right

Question: I don`t know why, but the mobile version of website has some lags. The mobile version of website slides into two slides: left to right. This bug appears on every page of website. The url to check the lag is this
Comment: Please provide your code here, not a link to your website.
Comment: try adding `overflow` property to body like this `body{overflow-x: hidden;}`
Answer: you have large of padding size.
below code is work
<code>
.google-auto-placed * {
    max-width: 100% !important;
    width: 100% !important;
}

/* mobile size */
@media screen and (max-width: 765px){

.google-auto-placed * {
    max-width: 100% !important;
    width: 100% !important;
}

}

</code>
Answer: I'm find your trouble
It's about a line css code
BAD CODE :
<code>#content #main {
padding-left: 20px;
padding-right: 20px;
</code>
}
GOOD CODE
<code>#content #main {
padding-left: 0px;
padding-right: 0px;
</code>
}


Using Pug (Jade) with Jinja2 tempting syntax

Question: I use grunt with Pug (Jade) to render my HTML templates.
I want to incorporate Jinja2 syntax in my Pug files but when I run grunt to build the HTML files it fails because it does not recognize the Jinja2 syntax.
Does anyone know a solution to this?
Comment: Not possible. I would suggest looking at the pug equivalents for those statements.
Answer: Have you looked at: https://github.com/kakulukia/pypugjs ?
Seems to support Jinja2:
jinja_env = Environment(extensions=['pypugjs.ext.jinja.PyPugJSExtension'])

The below pug (jade) code example
!!! 5
html(lang="en")
  head
    title= pageTitle
    script(type='text/javascript').
      if (foo) {
         bar()
      }
  body
    h1.title PugJS - node template engine
    #container
      if youAreUsingPugJS
        p You are amazing
      else
        p Get on it!

gets converted to:
<!DOCTYPE html>

    <title>{{pageTitle}}</title>

PugJS - node template engine

      {%if youAreUsingPugJS%}

You are amazing

      {%else%}

Get on it!

      {%endif%}

You can use following utility command to do it:
pypugjs -c jinja input.pug output.html

Answer: I basically wrote a whole library so that I could do exactly the same thing,
particularly as a renderer in Pyramid


Arraylist(even/odd) swapping elements java

Question: Hello folks,
             I am just trying to swap the list items irrespective of the odd or even list. I sense there might be another way of doing swap when the list size is odd. i am just patching the code based on the errors i see on console. Is there any better way to swap the list items when the list is odd not with if condition inside the else.
package org.ada.crm;

import java.util.ArrayList;
import java.util.Collections;

public class AList {

    public static void main(String[]args){
        String[] num = {"four", "score", "and", "seven", "years", "ago","sure"};
        ArrayList<String>list = new ArrayList<String>();
        for(int i=0;i<num.length;i++){
            list.add(num[i]);
        }
        System.out.println("****hhh"+list);
        swapPair(list);
    }

    private static void swapPair(ArrayList<String> list) {

        int listsize = list.size();
        for(int i=0;i<listsize;i+=2){
        if(listsize%2==0){
            Collections.swap(list, i, i+1);
        }else{
            if(i+1<listsize) ///here i want to know is there any better solution
                Collections.swap(list, i, i+1);
        }}
        System.out.println("jfsfjdsl"+ list);
    }

}

Comment: So the code works and you're looking for a way to "optimize out" the tiny fragment `if(i+1<listsize)` ?
Comment: Looking for a way to do "something" better? Then ask here: [CodeReview](http://codereview.stackexchange.com/).
Answer: I think you are looking for a combination of Arrays.asList(T...) and Collections.shuffle(List) like
String[] num = {"four", "score", "and", "seven", "years", "ago","sure"};
List<String> list = new ArrayList<>(Arrays.asList(num));
Collections.shuffle(list);
System.out.println(list);

Answer: If you just want something interesting, here is a nifty way.

If a binary number is even, the last bit is 0.
If a binary number is odd, the last bit is 1.

So you get the last bit, then subtract it from the list size.

For even list size: listSize = listSize - 0.
For odd list size: listSize = listSize - 1.

private static void swapPair(List<String> list) {
    int listSize = list.size();
    listSize -= listSize & 1;

    for(int i = 0; i < listSize; i += 2) {
        Collections.swap(list, i, i + 1);
    }
}