text:
Q: How to tell which app was selected by Intent.createChooser? Code:
Intent launchIntent = new Intent(Intent.ACTION_MAIN);
launchIntent.addCategory(Intent.CATEGORY_HOME);
Intent chooser = Intent.createChooser(launchIntent, "Complete Action using..");
activity.startActivity(chooser);

I don't see any way to tell which Intent (HOME category launcher) was selected. There is no Intent.addOnActionSetListener, and no chooser.addOnIntentChosenListener etc.
So how can I tell which was selected? Do I have to write my own chooser for this?

A: The CommonsWare's solution only works from Android 5.1 (API level 22). Here is my solution to work with all Android versions, by creating our own app chooser dialog.
Step 1: Create a custom layout for the app chooser dialog.
dialog_app_chooser.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text_view_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:paddingStart="20dp"
        android:paddingTop="14dp"
        android:paddingEnd="0dp"
        android:paddingBottom="14dp"
        android:text="Select an action"
        android:textColor="#000"
        android:textSize="16sp"
        android:textStyle="bold" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view_apps"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingStart="16dp"
        android:paddingEnd="16dp" />
</LinearLayout>

Step 2: Create a layout for an item in app chooser dialog.
item_app.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_app"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/image_view_app_icon"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp" />

    <TextView
        android:id="@+id/text_view_app_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="20dp"
        android:textColor="#000"
        android:textSize="12sp" />
</LinearLayout>

Step 3: Create a model class which indicates an app in the app chooser dialog.
App.java
public class App implements Parcelable {
    public Intent intent;
    public ResolveInfo resolveInfo;

    public App(Intent intent, ResolveInfo resolveInfo) {
        this.intent = intent;
        this.resolveInfo = resolveInfo;
    }

    protected App(Parcel in) {
        intent = in.readParcelable(Intent.class.getClassLoader());
        resolveInfo = in.readParcelable(ResolveInfo.class.getClassLoader());
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeParcelable(intent, flags);
        dest.writeParcelable(resolveInfo, flags);
    }

    public static final Creator<App> CREATOR = new Creator<App>() {
        @Override
        public App createFromParcel(Parcel in) {
            return new App(in);
        }

        @Override
        public App[] newArray(int size) {
            return new App[size];
        }
    };
}

Step 4: Create a custom adapter which display all apps in the app chooser dialog.
AppAdapter.java
public class AppAdapter extends RecyclerView.Adapter<AppAdapter.ViewHolder> {
    private List<App> apps;
    private OnItemClickListener listener;

    public AppAdapter(List<App> apps, OnItemClickListener listener) {
        this.apps = apps;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int position) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_app, parent, false);
        return new ViewHolder(view, listener);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        App app = apps.get(viewHolder.getAdapterPosition());
        viewHolder.bind(app);
    }

    @Override
    public int getItemCount() {
        return apps.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView appIcon;
        private TextView appName;
        private App app;

        ViewHolder(View itemView, final OnItemClickListener listener) {
            super(itemView);
            appIcon = itemView.findViewById(R.id.image_view_app_icon);
            appName = itemView.findViewById(R.id.text_view_app_name);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onItemClick(app);
                }
            });
        }

        void bind(App app) {
            this.app = app;
            PackageManager packageManager = appName.getContext().getPackageManager();
            appIcon.setImageDrawable(app.resolveInfo.loadIcon(packageManager));
            appName.setText(app.resolveInfo.loadLabel(packageManager));
        }
    }

    interface OnItemClickListener {
        void onItemClick(App app);
    }
}

Step 5: Create the app chooser dialog.
AppChooserDialog.java
public class AppChooserDialog extends BottomSheetDialogFragment implements AppAdapter.OnItemClickListener {
    private static final String KEY_APPS = "KEY_APPS";
    private static final String KEY_TITLE = "KEY_TITLE";
    private static final String KEY_REQUEST_CODE = "KEY_REQUEST_CODE";

    public static void show(AppCompatActivity activity, ArrayList<Intent> targets, String title, int requestCode) {
        PackageManager packageManager = activity.getPackageManager();
        ArrayList<App> apps = new ArrayList<>();
        for (Intent intent : targets) {
            List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
            for (ResolveInfo resolveInfo : activities) {
                Intent targetIntent = new Intent(intent);
                apps.add(new App(targetIntent, resolveInfo));
            }
        }

        if (apps.size() > 0) {
            if (apps.size() == 1) {
                activity.startActivityForResult(apps.get(0).intent, requestCode);
            } else {
                DialogFragment appChooserDialog = new AppChooserDialog();
                Bundle data = new Bundle();
                data.putParcelableArrayList(KEY_APPS, apps);
                data.putString(KEY_TITLE, title);
                data.putInt(KEY_REQUEST_CODE, requestCode);
                appChooserDialog.setArguments(data);
                appChooserDialog.show(activity.getSupportFragmentManager(), "AppChooserDialog");
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.dialog_app_chooser, container, false);

        TextView titleTextView = rootView.findViewById(R.id.text_view_title);
        RecyclerView appsRecyclerView = rootView.findViewById(R.id.recycler_view_apps);

        String title = getArguments().getString(KEY_TITLE);
        if (!TextUtils.isEmpty(title)) {
            titleTextView.setText(title);
        }

        List<App> apps = getArguments().getParcelableArrayList(KEY_APPS);
        appsRecyclerView.setAdapter(new AppAdapter(apps, this));

        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        float screenWidthInDp = displayMetrics.widthPixels / displayMetrics.density;
        int recyclerViewItemWidthInDp = 72;
        int recyclerViewStartEndPadding = 32;
        int numberOfColumns = (int) ((screenWidthInDp - recyclerViewStartEndPadding) / recyclerViewItemWidthInDp);
        int spanCount = (apps.size() < numberOfColumns) ? apps.size() : numberOfColumns;
        appsRecyclerView.setLayoutManager(new GridLayoutManager(requireActivity(), spanCount));

        return rootView;
    }

    @Override
    public void onItemClick(App app) {
        ActivityInfo activity = app.resolveInfo.activityInfo;
        String packageName = activity.applicationInfo.packageName;
        ComponentName component = new ComponentName(packageName, activity.name);

        Intent intent = new Intent(app.intent);
        intent.setComponent(component);

        Uri uri = app.intent.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
        if (uri != null) {
            requireActivity().grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }

        OnAppSelectedListener listener = null;
        try {
            listener = (OnAppSelectedListener) requireActivity();
        } catch (Exception e) {
            // Ignore exception
        }
        if (listener != null) {
            listener.onAppSelected(intent);
        }

        requireActivity().startActivityForResult(intent, getArguments().getInt(KEY_REQUEST_CODE));
        dismiss();
    }

    public interface OnAppSelectedListener {
        void onAppSelected(Intent intent);
    }
}

Step 6: Using the app chooser dialog from an activity.
public class MainActivity extends AppCompatActivity implements AppChooserDialog.OnAppSelectedListener {
    private static final int REQUEST_CODE_PICK_IMAGE = 100;

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

        ArrayList<Intent> intents = new ArrayList<>();
        Intent pickImageIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intents.add(pickImageIntent);
        AppChooserDialog.show(this, intents, "Pick image from", REQUEST_CODE_PICK_IMAGE);
    }

    @Override
    public void onAppSelected(Intent intent) {
        ComponentName componentName = intent.getComponent();
        String packageName = componentName.getPackageName();
        String activityName = componentName.getClassName();
        Log.i("TAG", "packageName = " + packageName + ", activityName = " + activityName);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            Log.i("TAG", "onActivityResult");
            // TODO: Put your logic here.
        }
    }
}

The result:

A: On Android 5.1+, you can use the three-parameter edition of the createChooser() method, where the last parameter is an IntentSender that you can use to find out what was chosen.
Prior to Android 5.1, there is nothing in Android to let you know what the user chose.

A: The answer provided by BinHe works but the problem is that a big number of apps is shown. In this solution I use the Intent.ACTION_PICK_ACTIVITY but only the apps compatible with Intent.ACTION_SEND will be shown, and you will know which option the user selected.
public void doSocialShare(String title, String text, String url){
    // First search for compatible apps with sharing (Intent.ACTION_SEND)
    List<Intent> targetedShareIntents = new ArrayList<Intent>();
    Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    // Set title and text to share when the user selects an option.
    shareIntent.putExtra(Intent.EXTRA_TITLE, title);
    shareIntent.putExtra(Intent.EXTRA_TEXT, url);
    shareIntent.putExtra(Intent.EXTRA_TEXT, text);
    List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(shareIntent, 0);
    if (!resInfo.isEmpty()) {
        for (ResolveInfo info : resInfo) {
            Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
            targetedShare.setType("text/plain"); // put here your mime type
            targetedShare.setPackage(info.activityInfo.packageName.toLowerCase());
            targetedShareIntents.add(targetedShare);
        }
        // Then show the ACTION_PICK_ACTIVITY to let the user select it
        Intent intentPick = new Intent();
        intentPick.setAction(Intent.ACTION_PICK_ACTIVITY);
        // Set the title of the dialog
        intentPick.putExtra(Intent.EXTRA_TITLE, title);
        intentPick.putExtra(Intent.EXTRA_INTENT, shareIntent);
        intentPick.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray());
        // Call StartActivityForResult so we can get the app name selected by the user
        this.startActivityForResult(intentPick, REQUEST_CODE_MY_PICK);
    }
}

Finally, to be able to get the app selected by the user you must override the onActivityResult on your activity:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == REQUEST_CODE_MY_PICK) {
        if(data != null && data.getComponent() != null && !TextUtils.isEmpty(data.getComponent().flattenToShortString()) ) {
            String appName = data.getComponent().flattenToShortString();
            // Now you know the app being picked.
            // data is a copy of your launchIntent with this important extra info added.

            // Start the selected activity
            startActivity(data);
        }
    }
}

A: This should work for early versions of Android.
Use intent PICKER instead of CHOOSER. The difference is that picker won't start the target intent automatically, but rather, it returns to onActivityResult() the target intent with the selected app's component name attached. Then you start the target intent in the callback as a 2nd step.
A little bit of code should explain,
// In MyActivity class
static final int REQUEST_CODE_MY_PICK = 1;

// Getting ready to start intent. Note: call startActivityForResult()
... launchIntent = the target intent you want to start;
Intent intentPick = new Intent();
intentPick.setAction(Intent.ACTION_PICK_ACTIVITY);
intentPick.putExtra(Intent.EXTRA_TITLE, "Launch using");
intentPick.putExtra(Intent.EXTRA_INTENT, launchIntent);
this.startActivityForResult(intentPick, REQUEST_CODE_MY_PICK);
// You have just started a picker activity,
// let's see what user will pick in the following callback

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == REQUEST_CODE_MY_PICK) {
         String appName = data.getComponent().flattenToShortString();
         // Now you know the app being picked.
         // data is a copy of your launchIntent with this important extra info added.

         // Don't forget to start it!
         startActivity(data);
    }
}

A: I did in different way, no need to implement custom component:
Send Intent:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "My feature text");
sendIntent.setType("text/plain");
Intent receiver = new Intent(this, ApplicationSelectorReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, receiver, PendingIntent.FLAG_UPDATE_CURRENT);
Intent chooser = Intent.createChooser(sendIntent, null, pendingIntent.getIntentSender());
startActivity(chooser);

Add BroadcastReceiver ApplicationSelectorReceiver.class in manifest.
<receiver android:name=".ApplicationSelectorReceiver"></receiver>

ApplicationSelectorReceiver.java
public class ApplicationSelectorReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        for (String key : Objects.requireNonNull(intent.getExtras()).keySet()) {
            try {
                ComponentName componentInfo = (ComponentName) intent.getExtras().get(key);
                PackageManager packageManager = context.getPackageManager();
                assert componentInfo != null;
                String appName = (String) packageManager.getApplicationLabel(packageManager.getApplicationInfo(componentInfo.getPackageName(), PackageManager.GET_META_DATA));
                Log.i("Selected Application Name", appName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Result:
Gmail
Facebook
Hangouts
Instagram
Drive

Hope this would help others.


text:
Q: Posicionamiento divs CSS Dispongo de un div búsqueda y quiero tener otro div mostrar_cabañas. Deseo que en el formulario, cual está dentro de búsqueda, si pulsamos Buscar se nos abra/cargue el div mostrar_cabañas y que éste aparezca debajo del div búsqueda con un pequeño espacio entra ambos divs...
¿Cómo coloco un div debajo de otro div con css?
Deseo que coloque cada cabana dentro de un div a su vez, cual div contendrá nombre de la cabaña, imágenes y sus opiniones.
Código HTML/PHP:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Reservar</title>

            <form action="<?php echo $_SERVER['PHP_SELF'];?>" name="mibusqueda" id="mibusqueda" method="POST" class="form_buscar">

RESERVAR

                Entrada:
                <input type="text" placeholder="Fecha de entrada" name="check_in" id="check_in" value="<?php if(isset($_POST['check_in'])){ echo $_POST['check_in']; }?>">

                Salida:
                <input type="text" placeholder="Fecha de salida" name="check_out" id="check_out" onchange="calculoNoches();" value="<?php if(isset($_POST['check_out'])){ echo $_POST['check_out']; }?>" disabled>

                    <input type="submit" value="Buscar" name="buscar" id="buscar">

            </form>

Código CSS:
* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
    box-sizing: border-box;
}

body{
    /*background: #DEDEDE;*/
    display: flex; /*Centrado en la página tanto vertical como horizontal.*/
    min-height: 100vh;
    background-repeat: no-repeat;
    background-position: center center;
    background-attachment: fixed; /*Imagen de fondo no se vaya con el scroll de la página.*/
    -o-background-size: 100% 100%, auto;
    -moz-background-size: 100% 100%, auto;
    -webkit-background-size: 100% 100%, auto;
    background-size: 100% 100%, auto;
}

.busqueda{
    margin: auto;
    width: 50%;
    max-width: 500px;
    background: #F3F3F3;
    padding: 18px;
    border: 2px solid rgba(0,0,0,0.2);
}

h2{
    text-align: center;
    margin-bottom: 20px;
    color: rgba(0,0,0,0.5);
}

input{
    display: block;
    padding: 10px;
    width: 100%;
    margin: 30px 0;
    font-size: 14px;
}

input[type="submit"] {
    background: linear-gradient(#FFDA63, #FFB940);
    border: 0;
    width: 160px;
    color: brown;
    opacity: 0.8;
    cursor: pointer;
    border-radius: 20px;
    margin-bottom: 0;
}

De inicio el div búsqueda se me centra en toda la página (TODO OK), cuando pulso "Buscar", me salen todas las cabañas disponibles pero al lado del div búsqueda y se me descentra todo.
Solución posible:
1) Lo que quiero es que al pulsar button BUSCAR, se nos genere el div mostrar_cabanas pero DEBAJO del div búsqueda.
2) Tengo de fondo una imagen para toda la página (incorporada en el body), ¿cómo haría independiente la imagen de fondo a la imagen de fondo de los divs mostrar_cabanas? Es decir, que el div mostrar_cabanas tenga el fondo blanco para poder visualizar bien los datos.
Imagen del problema:

A: Crea un div que sea en contenedor de ambos divs y display:flex se encargara de posicionarlos ambos en el centro de la pantalla:

* {
 margin: 0;
 padding: 0;
 font-family: sans-serif;
 box-sizing: border-box;
}

body{
 /*background: #DEDEDE;*/
 display: flex; /*Centrado en la página tanto vertical como horizontal.*/
 min-height: 100vh;
 background-repeat: no-repeat;
 background-position: center center;
 background-attachment: fixed; /*Imagen de fondo no se vaya con el scroll de la página.*/
 -o-background-size: 100% 100%, auto;
 -moz-background-size: 100% 100%, auto;
 -webkit-background-size: 100% 100%, auto;
 background-size: 100% 100%, auto;
}
#contenedor{
   width:100%;
  height:100%;
  margin:auto;
}

.sesion_cliente{
 position: absolute;
    top: 10px;
    right: 10px;
 float: right;
 text-align: right;
}

.negrita{
 font-weight: bold;
 color: white;
}

a:link {
    color: white;
}

a:visited {
    color: red;
}

.busqueda{
 margin: auto;
 width: 50%;
 max-width: 500px;
 background: #F3F3F3;
 padding: 18px;
 border: 2px solid rgba(0,0,0,0.2);
}

h2{
 text-align: center;
 margin-bottom: 20px;
 color: rgba(0,0,0,0.5);
}

input{
 display: block;
 padding: 10px;
 width: 100%;
 margin: 30px 0;
 font-size: 14px;
}

input[type="submit"] {
 background: linear-gradient(#FFDA63, #FFB940);
 border: 0;
 width: 160px;
 color: brown;
 opacity: 0.8;
 cursor: pointer;
 border-radius: 20px;
 margin-bottom: 0;
}

.form-link{
 font-size: 12px;
}

.mostrar_cabanas{
  background:red;
}
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Reservar</title>

            <form action="<?php echo $_SERVER['PHP_SELF'];?>" name="mibusqueda" id="mibusqueda" method="POST" class="form_buscar">

RESERVAR

                Entrada:
                <input type="text" placeholder="Fecha de entrada" name="check_in" id="check_in" value="<?php if(isset($_POST['check_in'])){ echo $_POST['check_in']; }?>">

                Salida:
                <input type="text" placeholder="Fecha de salida" name="check_out" id="check_out" onchange="calculoNoches();" value="<?php if(isset($_POST['check_out'])){ echo $_POST['check_out']; }?>" disabled>

                    <input type="submit" value="Buscar" name="buscar" id="buscar">

            </form>

          RESULTADO DE LA BUSQUEDA

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get list to dataframe with uneven row lenghts There is a list made from many dataframes of uneven row lengths. The column names is always iterating : name, var, name.1, var.1 etc.  And sometimes there are columns with just 1 row and NA.
Q: How to match all of them together?
 myData<-list(name=c("1","2","3","4","5","6","7"),var=c(5,5,5,5,5,5,5),     name=c(1,2,3,4,5,6,7),var=c(2,2,2,2,2,2),name=c(1,2,3,4,5,6),var=c(5,5,5,4,5),name=c(""),var=c(""))

The final outcome would look like this:
  name var name.1 var.1 name.2 var.2 name.3 var.3 …
1  1    5    1      2    1      5    [NA]    [NA] …
2  2    5    2      2    2      5
3  3
.
.

A: Fixed data:
myData<-list(name=c("1","2","3","4","5","6","7"),var=c(5,5,5,5,5,5,5),     name=c(1,2,3,4,5,6,7),var=c(2,2,2,2,2,2),name=c(1,2,3,4,5,6),var=c(5,5,5,4,5),name=c(""),var=c(""))

Working solution:
( maxlen <- max(lengths(myData)) )
# [1] 7
data.frame(lapply(myData, `length<-`, maxlen))
#   name var name.1 var.1 name.2 var.2 name.3 var.3
# 1    1   5      1     2      1     5
# 2    2   5      2     2      2     5   <NA>  <NA>
# 3    3   5      3     2      3     5   <NA>  <NA>
# 4    4   5      4     2      4     4   <NA>  <NA>
# 5    5   5      5     2      5     5   <NA>  <NA>
# 6    6   5      6     2      6    NA   <NA>  <NA>
# 7    7   5      7    NA     NA    NA   <NA>  <NA>

A: A tidyverse based solution by stacking list and then spreading data.frame using tidyr::spread.
library(tidyverse)

stack(myData) %>% mutate(ind = as.character(ind)) %>%
  group_by(grp = cumsum(ind != lag(ind, default="")) ) %>%
  mutate(ind = paste(ind, (grp+1) %/%2, sep="."), rn = row_number()) %>%
  ungroup() %>% select(-grp) %>%
  spread(ind, values) %>%
  select(-rn) %>% as.data.frame()

#   name.1 name.2 name.3 name.4 var.1 var.2 var.3 var.4
# 1      1      1      1            5     2     5
# 2      2      2      2   <NA>     5     2     5  <NA>
# 3      3      3      3   <NA>     5     2     5  <NA>
# 4      4      4      4   <NA>     5     2     4  <NA>
# 5      5      5      5   <NA>     5     2     5  <NA>
# 6      6      6      6   <NA>     5     2  <NA>  <NA>
# 7      7      7   <NA>   <NA>     5  <NA>  <NA>  <NA>

Data: Corrected data taken from @r2evans answer.
myData<-list(name=c("1","2","3","4","5","6","7"),
             var=c(5,5,5,5,5,5,5),
             name=c(1,2,3,4,5,6,7),
             var=c(2,2,2,2,2,2),
             name=c(1,2,3,4,5,6),
             var=c(5,5,5,4,5),name=c(""),var=c(""))


text:
Q: What kind of network attack turns a switch into a hub? I read an article today describing how a penetration tester was able to demonstrate creating a fake bank account with a $14 million balance.  However, one paragraph describing the attack stood out:

Then he "flooded" switches -- small boxes that direct data traffic --
  to overwhelm the bank's internal network with data. That kind of
  attack turns the switch into a "hub" that broadcasts data out
  indiscriminately.

I'm not familiar with the effect that is described.  Is it really possible to force a switch to broadcast traffic to all of its ports by sending massive amounts of traffic?  What exactly is going on in this situation?

A: This is called MAC flooding and makes use of the fact that the CAM tables of switches are of limited length. If they overflow, a switch turns into a hub and sends out every packet to every port, which quickly can grind a network to a halt.
Edited to correct wrong terminology.

A: This is called MAC flooding. A "MAC address" is an Ethernet hardware address. A switch maintains a CAM table that maps MAC addresses to ports.
If a switch has to send a packet to a MAC address not in its CAM table, it floods it to all ports just like a hub does. So if you flood a switch with a larger number of MAC addresses, you will force the entries of legitimate MAC addresses out of the CAM table and their traffic will be flooded to all ports.

A: As has been explained above, the switch's MAC table is 'poisoned' with fake mac addresses. This is easy to do with the macof program from the dsniff suite of tools. Warning: only try this for educational purposes in your own network, otherwise you will get into deep legal trouble!
http://www.monkey.org/~dugsong/dsniff/


text:
Q: Can I bin data in SQLite? I have a lot of rows with dates in some SQLite database. I'd like to get some aggregated statistics for weeks or some other periods.
Is it possible to bin data in SQLite (i.e. get some number which corresponds to the number of the period - e.g. week)?

A: To create a column of unique week identifiers use strftime('%Y%W', date_column).  More info here.
For your purposes I believe a "SELECT ... GROUP BY strftime('%Y%W', date_column)" should work.


text:
Q: Always launch new activity instance with no history Is there a way to launch an activity as a new instance with no history?
Tried the following in the manifest file.
android:launchmode="singleinstance"
android:noHistory=true

I am able to achieve what I need, but as soon as the screen is locked the previous activity is displayed. That's what noHistory is supposed to do, but not what I need.
Keeping the screen on always would not be preferable as it would drain the battery unnecessarily. Is there any other way to start an activity with a new instance and have no history but also work when the screen is locked?

A: This will start a activity with new information and no history
Intent intent = new Intent(MainActivity.this, TargetActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
MainActivity.startActivity(intent);

A: You can also do that  by adding android:noHistory="true"
in your android manifest Activity Tag (ClassName)

A: Try to use this flag in intent.
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

The new activity is not kept in the history stack. As soon as the user navigates away from it, the activity is finished.


text:
Q: Stata: append two datasets, retain value labels I'm using Stata14 and I'm trying to append two survey datasets that have ~200 variables with same names but different values and value labels. I would like to do the appending so that value labels are retained from the dataset 'on disk'.
Here is an example describing my problem:
Variable in dataset 1 (master):
value - label
1 - yes
2 - no
Same variable in dataset 2 (appended to master):
value - label
1 - yes absolutely
2 - no definitely not
3 - maybe
4 - don't know
Result with append using "dataset 2.dta"
value - label
1 - yes
2 - no
3 - 3
4 - 4
Desired result:
value - label
1 - yes
2 - no
3 - maybe
4 - don't know
Is there any way to do this directly using append? If not, any suggestions on doing the task efficiently are most welcome.

A: You want to make value labels consistent, which is sensible, fine and easy to do.
When you have appended all the datasets, you then overwrite any value label assignment with a quick
label define whatever 1 yes 2 no 3 maybe 4 "don't know"
label val myvar whatever

with a , modify on the first if a set of value labels with that name already exists.
It's a task to do late. It doesn't need to be fixed before or during the append, and it can most easily be done at that point.
Naturally, this is tedious for several variables, but it's not difficult to understand. Furthermore, even if append were able to take instructions on which labels to use, you would still have to spell that out. In your example, the value labels you want are not actually in use in any of the datasets. So, there will be some inevitable pain. There is a mess to sort out and what the fix is can't be fully automated because it depends on your ideas of what labels are best.

A: in short, the answer is
NOPE
so you have to be smart. Try to use this trick http://www.stata.com/support/faqs/data-management/keeping-same-variable-with-collapse/ where you get a local copy of the labels that you will be attaching to the full dataset afterwards.


text:
Q: Hide / Show Winforms GUI C# from another thread This post is continuation of Way to quickly show/hide WinForms GUI C#, as it doesn't work for me in this particular case.
I've got 2 problems:

*

*1 is that the mainAnnounceWindow gui should start hidden and later on when called by: windowStateChange("Show") it should show, by windowStateChange("Hide") it should hide. It doesn't do that properly as when i start app it's visible for like 0,5 s (i see it blinking). Is there a way to make it start hidden and not blink for half a second.

*2 is that windowStateChange doesn't work properly when called from myThreadHandler (Queue.Work).
internal class Program {
public delegate void StateCallBack(string varState);
public static readonly Announce mainAnnounceWindow = new Announce();
public static readonly Thread myThreadGuiAnnounce = new Thread(showGuiAnnounce);
public static readonly Thread myThreadTcpClient = new Thread(threadTcpClient);
public static readonly Thread myThreadUdpMonitor = new Thread(threadUdpMonitor);
public static readonly Thread myThreadHandler = new Thread(Queue.work);

public static void Main()
{
    myThreadGuiAnnounce.Start();
    myThreadTcpClient.Start();
    myThreadUdpMonitor.Start();
    myThreadHandler.Start();
    windowStateChange("Hide");

    while (true) {
        Thread.Sleep(1000);
    }
}
public static void windowStateChange(string varState) {
    if (mainAnnounceWindow.InvokeRequired) {
        mainAnnounceWindow.Invoke(new StateCallBack(windowStateChange), new object[] {varState});
    } else {
        if (varState == "Hide") {
            mainAnnounceWindow.Hide();
            mainAnnounceWindow.TopMost = false;
        } else {
            mainAnnounceWindow.Show();
            mainAnnounceWindow.TopMost = true;
        }
    }
}
    private static void showGuiAnnounce() {
    mainAnnounceWindow.ShowDialog();

}
}

Another class:
  public class Queue : IDisposable {
 public static void work() {
        while (true) {
            string task = null;
            lock (locker)
                if (tasks.Count > 0) {
                    task = tasks.Dequeue();
                    if (task == null) {
                        return;
                    }
                }
            if (task != null) {
                //MessageBox.Show("Performing task: " + task);
                Program.mainAnnounceWindow.setLogTextBox(task);
                Program.mainAnnounceWindow.setLogTrayTip(task);
                Program.windowStateChange("Show");
                Thread.Sleep(5000); // simulate work...
                Program.windowStateChange("Hide");
            } else {
                wh.WaitOne(); // No more tasks - wait for a signal
            }
        }
    }

}
The problem is with:
                Program.windowStateChange("Show");
                Thread.Sleep(5000); // simulate work...
                Program.windowStateChange("Hide");

When i call Program.windowStateChange("Show"); from inside other thread the gui shows but not quite.. like i can see that it would like to show, but it doesn't. Like a hang of app. But when the Thread.Sleep(5000) passes the app hides.
Calling:
                Program.mainAnnounceWindow.setLogTextBox(task);
                Program.mainAnnounceWindow.setLogTrayTip(task);

Has no problem. BaloonTip shows, just the Gui doesn't show up properly. Something i'm doing wrong.
Oh and of course i did some cut/paste so it may miss some stuff. If it's necessary to add something let me know.
With regards,
MadBoy

A: Your problem is you are accessing a ui object from a non ui thread, which is not allowed. You need to pass a delegate wrapping the operation you want to perform to the Invoke or BeginInvoke methods on one of the ui controls (perhaps your form object).

A: The problem is that your main thread is locked up, because you added this:
while (true) {
    Thread.Sleep(1000);
}

This will prevent the window thread from receiving and processing the windows messages (such as show and hide) appropriately.
You'll also want to use  mainAnnounceWindow.Show(), not  mainAnnounceWindow.ShowDialog(), as this will prevent control from returning properly to the main thread.  You should just call Application.Run(mainAnnounceWindow) in your Main routine:
public static void Main()
{
    myThreadGuiAnnounce.Start();
    myThreadTcpClient.Start();
    myThreadUdpMonitor.Start();
    myThreadHandler.Start();

    // Just change your main window's load to hide itself... windowStateChange("Hide");
    Application.Run(mainAnnounceWindow);
}


text:
Q: How to send ajax post with specific options using php I need to send data to another domain. Now I use jquery and ajax
var post_data = {
   foo: "foo",
   bar: "bar"
};

jQuery.ajax({
   url:"https://notmydomain.com/polling/?d=jsonp",
   crossDomain:true,
   dataType:"jsonp",
   cache:false,
   data: post_data,
   type: "post"
});

It works fine, but I need to send it using php.
Try to use this solution:
$post_data = http_build_query(
  array(
    'foo' => 'foo',
    'bar' => 'bar'
  )
);

$opts = array(
  'http' => array(
    'method'  => 'POST',
    'header'  => 'Content-type: application/x-www-form-urlencoded',
    'content' => $post_data
  )
);
$context  = stream_context_create($opts);
$result = file_get_contents('https://notmydomain.com/polling/?d=jsonp', false, $context);

But it's not work. I'm think cause of specific options in ajax like:
crossDomain:true,
dataType:"jsonp",
cache:false

Don't know how to solve it, need help!


text:
Q: How can I change image source on click with jQuery? I 'm currently building a full background image layout and I want to change the image based on which page the user is visiting. To get to the point: I need to change a images attribute when the user clickes on a link. This is how far I got:
$(function() {
  $('.menulink').click(function(){
    $("#bg").attr('src',"img/picture1.jpg");
  });
});

    switch me

Thank you, probably easy stuff, but over my head!

A: You need to use preventDefault() to make it so the link does not go  through when u click on it:
fiddle: http://jsfiddle.net/maniator/Sevdm/
$(function() {
 $('.menulink').click(function(e){
     e.preventDefault();
   $("#bg").attr('src',"img/picture1.jpg");
 });
});

A: It switches back because by default, when you click a link, it follows the link and loads the page.
In your case, you don't want that. You can prevent it either by doing e.preventDefault(); (like Neal mentioned) or by returning false :
$(function() {
 $('.menulink').click(function(){
   $("#bg").attr('src',"img/picture1.jpg");
   return false;
 });
});

Interesting question on the differences between prevent default and return false.
In this case, return false will work just fine because the event doesn't need to be propagated.

A: You should consider using a button for this. Links generally should be use for linking. Buttons can be used for other functionality you wish to add. Neals solution works, but its a workaround.
If you use a <button> instead of a , your original code should work as expected.

A: You can use jQuery's attr() function, like $("#id").attr('src',"source").

A:  $('div#imageContainer').click(function () {
      $('div#imageContainerimg').attr('src', 'YOUR NEW IMAGE URL HERE');
});

A: When you click the text or link the image will be changed to another image so you can use the below script helps to you to change image on click the link:

The  Human  Body  Parts :

Human-body-organ-diag-1

Human-body-organ-diag-2

Human-body-organ-diag-3

Human-body-organ-diag-4

Human-body-organ-diag-5

Human-body-organ-diag-6

Human-body-organ-diag-7

Human-body-organ-diag-8

Human-body-organ-diag-9

Human-body-organ-diag-10

css:


text:
Q: android.permission.INTERNET removed by Google Play? I was uploding my first App to the Google Play Store.
It includes a android.permission.INTERNET permission which worked fine localy.
In the Developer Console i can see that the app uses this permission, but while installing it says that the app don't need special permissions.
When the app opens a webpage with the standard browser, it pops up but no page opens..
instead just the last opened tab is shown.
Am i missing something important here?
Cheers, Andreas

A: Because android.permission.INTERNET is used by so many apps, Google moved it to the Other category. Permissions in this category are not shown to the user when installing.  You can confirm that the installed app has this permission from looking at it in Settings->Apps.
The blank page in your browser is caused by something else.

A: So, what i figured out..
As i submit post data using javascript.. (like at https://stackoverflow.com/a/12891955/4110640 )
it seems that this is no longer working since at least 4.2.2, maybe earlier.
I will change to an WebView to support newer devices.
Thanks for the help.


text:
Q: Removing all items from recyclerview at ONCE on firebase ui I can delete one at a time in the recyclerview but trying to figure out how to delete the entire element at ONCE in the recyclerview when the finished button is clicked. this is my first time making use of this platform to ask question. Please can someone assist me on this code, i try so many times to remove all items at ONCE from the recyclerview in firebase UI and get error or no results at all. please how to fix this kind of issue and here is my code below. enter image description here
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);

    mCartTotal = findViewById(R.id.TV_ShoppingCart_Total);
    mBtnFinish = findViewById(R.id.LinearLayout_Cart_Next_Address);
    mShopping_RecyclerView = findViewById(R.id.recycler_view_shopping_cart);

    mShopping_RecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
    mShopping_RecyclerView.setHasFixedSize(false);

    mBtnFinish.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        //Please what should i put in here

            Intent navigateShippingScreen = new Intent(CartActivity.this, ShippingAddressActivity.class);
            navigateShippingScreen.putExtra("Total Price", String.valueOf(overAllTotalPrice));
            startActivity(navigateShippingScreen);
            finish();
        }
    });

    readDataCart();

}

private void readDataCart() {
    FirebaseUser AppUser = FirebaseAuth.getInstance().getCurrentUser();
    if (AppUser != null) {
        USER_ID = FirebaseAuth.getInstance().getCurrentUser().getUid();
        CART_PRODUCT = FirebaseAuth.getInstance().getCurrentUser().getUid();

        Query query = FirebaseFirestore.getInstance()
                .collection("REGISTERED USERS").document(USER_ID)
                .collection("CART PRODUCT").orderBy("productTime", Query.Direction.ASCENDING);

        options = new FirestoreRecyclerOptions.Builder<PharmacyCart_DataModel>()
                .setQuery(query, PharmacyCart_DataModel.class)
                .build();

        myAdapter = new FirestoreRecyclerAdapter<PharmacyCart_DataModel, myViewHolderCart>(options) {
            @SuppressLint("SetTextI18n")
            @Override
            protected void onBindViewHolder(@NonNull myViewHolderCart holder, int position, @NonNull PharmacyCart_DataModel model) {

                holder.mCartTitle.setText(model.getProductCartName());
                holder.mCartPrice.setText("RM" + model.getProductCartPrice());
                holder.mCartQuantity.setText(model.getProductCartQuantity());

                int oneTypeProductPrice = Integer.valueOf(model.getProductCartPrice()) * Integer.valueOf(model.getProductCartQuantity());
                overAllTotalPrice = overAllTotalPrice + oneTypeProductPrice;
                mCartTotal.setText("RM " + String.valueOf(overAllTotalPrice));

                holder.mDeleteProductCart.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        _deleteCartItemNow(holder);

                        int oneTypeProductPrice = Integer.valueOf(model.getProductCartPrice()) * Integer.valueOf(model.getProductCartQuantity());
                        overAllTotalPrice = overAllTotalPrice - oneTypeProductPrice;
                        mCartTotal.setText("RM " + String.valueOf(overAllTotalPrice));
                    }
                });

            }

            @NonNull
            @Override
            public myViewHolderCart onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cart_product, parent, false);
                return new myViewHolderCart(v);
            }

        };
        mShopping_RecyclerView.setAdapter(myAdapter);
    }
}

private void _deleteCartItemNow(myViewHolderCart holder) {
    _deleteCartItem(holder.getAdapterPosition());

}

private void _deleteCartItem(int position) {
    myAdapter.getSnapshots().getSnapshot(position).getReference().delete();
}

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

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

}


text:
Q: where to store the xml parsing file in an android app I am a new developer. In my app I am trying to parse two xml files. The first xml file contains some list of data as follows:
<?xml version="1.0"?>
<Subjects>
    <Chapter>
        <chapter-name>A</chapter-name>
        <packs><pack><packname>B</packname>
        </packs>
    </Chapter>
</Subjects>

The data will be showed in a listview manner. When I touch A it moves to B, and when I touch B it moves over to the next XML file:
<?xml version="1.0"?>
<flash>
<card>
<question>shbsbdvbjj</question>
<answer>dsbvbs</answer>
<card>
<flash>

Here I want to do a flip order; the question must be one side and the answer must be of other side.
Now the problem is that I am getting the first XML file correctly but the later one is not visible, it seems to be a black screen. I have placed both the xml files in res->raw
and its beeen mentioned in the coding as:
//getting the path of xml to parse
        inputstream = this.getResources().openRawResource(R.raw.list);
resID = getResources().getIdentifier(name, "raw", "com.gis.flash");

Can anyone explain me what errors I have committed?

A: put it in your asset folder and access it
like file:///android_asset/yourxml.xml
i think you should see this

A: I don't know if its the best way to do this, but here's how you can do it. Put your xml files in the res/xml directory (you need to create it). Assuming your xml file is list.xml and it resides inside res/xml/, you can access your xml file by using getResources() like this,
getResources().getXml(R.xml.list);


text:
Q: Python 3.x: Trying to compare current element with previous and next (without built-in functions) I'm trying to write code that adds to a count if the current list element is greater than both the previous list element and the next list element. So, for example, in a list: [1, 3, 5, 7, 2]... 1 and 2 are not evaluated because they only have one number to the side. So 3 is the first to be compared and 3 is not greater than 1 and 5, 5 is not greater than 3 and 7, and 7 is greater than 5 and 2 so count = 1.
This is for homework so I can't use built-in functions. List is of random length and may contain positive and negative numbers.
I tried two variations...
In this version, the i value never goes up. Why is this? How do I get it to go to the next number?
a = [int(i) for i in input().split()]
b = a[0]
count = 0

for i in a[1:]:
    for j in a[2:]:
        if i > j and i > b:
            count +=1
        b = i

print(count)

In the second version, I get Index Error: list index out of range. How can I fix such an error?
a = [int(i) for i in input().split()]
prev = nxt = 0
b = a[1]
count = 0

for i in range(1, len(a)):
    prev = a[i-1]
    nxt = a[i+1]
    if b > prev and b > nxt:
        count +=1
    prev = b
    b = nxt

print(count)

Thank you for any help. I would like to know where I'm going wrong.

A: In the code you have written you are trying to access the index which is not on the list.You are trying to access the next element for the last element in the list, which is not there!
Just change the for loop range
for i in range(1,len(a)-1)

Here is the code I have written:
 count = 0
 for i in range(1,len(a)-1):
     if a[i+1] < a[i] > a[i-1] :
          count += 1

A: You can check without the first and last:
my_list = my_list[1:-1]
res=0
for ndx,el in enumerate(my_list):
  if my_list[ndx-1] > el and my_list[ndx+1] > el:
    res+=el


text:
Q: Do I really need drawRect() in custom UIView? I am new to iOS and trying to understand the use for drawRect() in custom UIViews, so I have simple custom view which I initialize from code.I want to update its colors for instance and I see two approaches as shown below. Which one should I use and why?
//VController
CustomView *cv = [[CustomView alloc] initWithFrame:...]
...
[cv updateColors];

//CustomView
-(id) initWithFrame {}
-(id) initWithCoder  {}
-(void) updateColors(UIColor *color){  ----(1)
  ...Draw here with new color ...
   view1.backgroundColor = color;
   view2.backgroundColor = color;

 }
- (void) drawRect{
 ... draw here with new color ... ---------(2)
   view1.backgroundColor = color;
   view2.backgroundColor = color;
 }

A: If all you want to do is change the background color of this view or some of its subviews, you absolutely should not misuse drawRect: for this. drawRect: is for when you want to draw the view (i.e. its content) when the system believes its needs refreshing; it is called at many and unpredictable times, and you don't need that - you just need to change the background color, a feature of the view, on demand. Similarly drawRect: is not the place to perform management of subviews.
But if you are going to draw the view's content (e.g. the view displays a circle and you need to draw that circle to portray the view) then you must use drawRect: for that; it is the only place where the view gets a chance to draw itself.


text:
Q: How do I use the rug function for an exponential distribution in R? I am just starting out in R. I want to plot interval of times (the distribution is exponential) on x axis, with a tick mark in place every time the interval ends. If I have a string of times say (0.2, 0.8, 0.9 , 1.0) then the tick marks on the x axis would be on 0.2, 0.8, 0.9 and 1 respectively. With big data samples, I want my graph to look something like:

So after using,
set.seed(1)
x <- rexp(50, 0.2)

How can I go about it further, might I have to use rug function (which I am trying to learn how to use)? Can I also put time stamps on this graph?
Edit
So I have modified my command and used:
x <- c(cumsum(rexp(50, 0.2)))
y <- rep(0, length(x))
plot(x,y)
rug(x)

and I have been able to get this:

This result does the work, if it's just about that. However, is there a line of command I can use to edit this result as shown in the second picture, and get a result as shown in the first picture? I would like to just get these tick marks on a horizontal line instead of the whole plot. Or it's not possible?

A: With ggplot you can use geom_rug() to .add a rug to the plot. First the data need to be made into a data.frame
library("tidyverse")
set.seed(1)
x <- rexp(50, 0.2)

ggplot(data.frame(x), aes(x = x)) + geom_rug()

The rug is rather short (it seems to be a proportion of the graph height and not controllable).
The opposite would be to use geom_vline which will give lines the full length of the y-axis
#ggplot(data.frame(x), aes(xintercept = x)) + geom_vline() #doesn't work
ggplot(data.frame(x)) + geom_vline(aes(xintercept = x))

A: rug() requires only a vector of values that describes where to draw the tickmarks (rugs). In case of plotting values x on the x-axis, those form the input data for the rug function. Type ?rug to get further help.
# generate y values
y <- rexp(50, 0.2)
# split plotting area into two columns - optional
par(mfrow = c(1, 2))
plot(x, y)
rug(x)
# plot with both axes in log scale to show that rug adjusts to axes scale
plot(x, y, log = "xy")
rug(x)


text:
Q: override func prepare(for segue: UIStoryboardSegue, sender: Any?) not working I have a table view controller that works like a news feed of images where each image has been retrieved from firebase. I want to be able to tap on each image and perform a segue to another view controller that has a table view with its own unique data of the tapped image.
With the code I have, the override func prepare(for:sender) is not being called and there is no error. The unique post id is being printed in the console when the image is tapped but the Show Segue is not being performed.
Here is my code in the HomeTableViewCell:
protocol HomeTableViewCellDelegate {
    func goToSiteVC(postId: String)

}

class HomeTableViewCell: UITableViewCell {
    @IBOutlet weak var siteImageView: UIImageView!
    var delegate: HomeTableViewCellDelegate?

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.siteImageView_TouchUpInside))
        siteImageView.addGestureRecognizer(tapGesture)
        siteImageView.isUserInteractionEnabled = true
        // Configure the view for the selected state
    }

    @objc func siteImageView_TouchUpInside() {
        print("siteImageView_TouchUpInside")
        print(post?.id)
        if let id = post?.id {
            delegate?.goToSiteVC(postId: id)
        }
    }
}

Here is my code in HomeViewController:
class HomeViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    var posts = [Post]()
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        loadPosts()
    }

        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "SiteSegue" {
                let siteVC = segue.destination as! SiteViewController
                let postId = sender as! String
                siteVC.postId = postId
                print("segue")
            }
        }
    }

extension HomeViewController: HomeTableViewCellDelegate {
    func goToSiteVC(postId: String) {
        performSegue(withIdentifier: "SiteSegue", sender: postId)
    }
}

A: The function should be out of viewDidLoad it must be in class scope
class HomeViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    var posts = [Post]()
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        loadPosts()

    }

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "SiteSegue" {
                let siteVC = segue.destination as! SiteViewController
                let postId = sender as! String
                siteVC.postId = postId
                print("segue")
            }
        }

}


text:
Q: Converting jagged lines to splines in ggplot2 I'm using ggplot2 to plot a data series - performance vs. number of threads, for several different numbers of loop iterations. I've gotten the data points to show up where I need them, and I've used geom_line() to connect the points.
I want to get smooth lines, rather than jagged lines, connecting these points. Not lines of fit / trend lines - just nice-looking splines similar to what you'd get with Excel or Google Sheets when you create a smooth line graph.
I'm pretty sure the best way to do this is to use the spline() function in combination with geom_line(), but I'm stumped on how exactly to do it. At some point I got one spline to show up for the entire graph, but I seem to have broken that. At no point have I been able to get multiple splines in place of the multiple jagged lines shown in the image below.
ggplot seems the shortest path to what I'm trying to achieve, but I'm open to suggestions that don't use it.
Here's what I've got right now in my R script, creating the jagged lines:
#!/usr/bin/Rscript

# Read from stdin (pipe from runProj2 output) and write to txt before mod
data <- read.table('stdin', header=TRUE)
write.table(data, "data.txt", sep="\t", row.names=FALSE)
# Get rid of volume field to analyze performance vs. threads and nodes
data$Volume <- NULL

# Organize data by both threads and nodes & output for PDF incorporation
dataByThreads <- reshape(data, idvar = "Threads", timevar = "Nodes", direction = "wide")
dataByNodes   <- reshape(data, idvar = "Nodes", timevar = "Threads", direction = "wide")

write.table(dataByThreads, "dataByThreads.txt", sep="\t", row.names=FALSE)
write.table(dataByNodes, "dataByNodes.txt", sep="\t", row.names=FALSE)

# Plot
library(ggplot2)
library(reshape2)

# Melt data back into long format for ggplot
threads_long <- melt(dataByThreads,  id="Threads")
nodes_long   <- melt(dataByNodes, id="Nodes")

ggplot(data=threads_long,
       aes(x=Threads, y=value, color=variable)) +
       geom_point() +
       geom_line() +
       labs(y='MegaHeights per Second', x='Threads', color='Nodes') +
       ggtitle('Performance vs. Threads')

ggplot(data=nodes_long,
       aes(x=Nodes, y=value, color=variable)) +
       geom_point() +
       geom_line() +
       labs(y='MegaHeights per Second', x='Nodes', color='Threads') +
       ggtitle('Performance vs. Threads')

Here's what I've got so far:


text:
Q: How to enable option to keep app's data on uninstall prompt? There seems to be a new option on Android 10 to allow the user to save an app's data before they uninstall it, I assume it'll be saved on the user's Google drive account along with other apps' data.
Going through all the new Android 10 features and APIs I didn't find any reference to this. Does anyone know how to enable it?

A: Add the following declaration in the application element of manifest XML:
android:hasFragileUserData="true"
The documentation is for this declaration is:

If true the user is prompted to keep the app's data on uninstall

A: i believe this is actually the same feature that existed from android 6 and up trough
android:allowBackup
android:fullBackupContent

but in earlier android versions it was done without promting the user, while in android 10 the user needs to confirm that the data is stored.


text:
Q: Proper testing method for function in go I'm new to go and started to play around with testing.
My method returns a []byte with a md5 hash in it.
func myHash(s string) []byte {
    h := md5.New()
    io.WriteString(h, s)
    return h.Sum(nil)
}

It's working and the hashes look ok, but when I'm testing it with this method:
func TestMyHash(t *testing.T) {
    s := "linux"
    bf := ("e206a54e97690cce50cc872dd70ee896")
    x := hashor(s)
    if !bytes.Equal(x, []byte(bf)) {
        t.Errorf("myHash ...")
    }
}

It will always fail. First I thought it could be some issue with the casting of a string to []byte or vice versa, but after trying ot over and over again I just need to ask here.
Can you give me an example how to test my function? Do I miss something necessary?
Thanks in advance.

A: You are probably comparing the raw bytes of the hash with the hexadecimal formatted version of  a hash. You might want to do something like this:
got := fmt.Sprintf("%034x", myHash("linux"))
want := "00e206a54e97690cce50cc872dd70ee896"
if got != want {
    t.Errorf("got %q, want %q", got, want)
}


text:
Q: I have been getting IOException in my Android App I have been getting IOException in my Android App,but i cannot find why this exception has occured.I am trying to make connection to a blog,and will later parse the JSON.StackTrace shows it is unable to resolve URL,but when i open the URL in browser it is working perfectly.I am getting java.net.unknownhostexception unable to resolve host error
Here is the code:
package blogreader.com.example.android.blogreader;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainListActivity extends ListActivity {
    protected String[] mAndroidNames;
    public static final int NUMBER_OF_POSTS=20;
    public static final String TAG=MainListActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main_list);
        GetBlogPostClass getBlogPostClass=new GetBlogPostClass();
        getBlogPostClass.execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    private class GetBlogPostClass extends AsyncTask<Object,Void,String>{

        @Override
        protected String doInBackground(Object... arg0) {
            int responseCode=-1;
            try {
                URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=" + NUMBER_OF_POSTS);
                HttpURLConnection connection =(HttpURLConnection) blogFeedUrl.openConnection();
                connection.connect();
                responseCode =connection.getResponseCode();
                Log.i(TAG, "Code" + responseCode);

            }
            catch (MalformedURLException e)
            {
                Log.e(TAG,"MalformedException Caught",e);
            }
            catch (IOException e)
            {
                Log.e(TAG,"IOException Caught",e);
            }
            catch (Exception e)
            {
                Log.e(TAG,"Exception Caught",e);
            }

            return "Code:"+responseCode;
        }
    }
}

Here is the Logcat:
09-18 12:52:50.609    1848-1848/blogreader.com.example.android.blogreader I/art﹕ Not late-enabling -Xcheck:jni (already on)
09-18 12:52:51.335    1848-1855/blogreader.com.example.android.blogreader W/art﹕ Suspending all threads took: 161.519ms
09-18 12:52:51.367    1848-1872/blogreader.com.example.android.blogreader D/OpenGLRenderer﹕ Render dirty regions requested: true
09-18 12:52:51.368    1848-1848/blogreader.com.example.android.blogreader D/﹕ HostConnection::get() New Host Connection established 0xae1d4d40, tid 1848
09-18 12:52:51.381    1848-1848/blogreader.com.example.android.blogreader D/Atlas﹕ Validating map...
09-18 12:52:51.481    1848-1872/blogreader.com.example.android.blogreader D/﹕ HostConnection::get() New Host Connection established 0xa6c3f080, tid 1872
09-18 12:52:51.762    1848-1872/blogreader.com.example.android.blogreader I/OpenGLRenderer﹕ Initialized EGL, version 1.4
09-18 12:52:51.785    1848-1855/blogreader.com.example.android.blogreader W/art﹕ Suspending all threads took: 178.024ms
09-18 12:52:51.805    1848-1872/blogreader.com.example.android.blogreader D/OpenGLRenderer﹕ Enabling debug mode 0
09-18 12:52:51.851    1848-1872/blogreader.com.example.android.blogreader W/EGL_emulation﹕ eglSurfaceAttrib not implemented
09-18 12:52:51.851    1848-1872/blogreader.com.example.android.blogreader W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6c420a0, error=EGL_SUCCESS
09-18 12:52:51.930    1848-1871/blogreader.com.example.android.blogreader E/MainListActivity﹕ IOException Caught
09-18 12:52:53.747    1848-1855/blogreader.com.example.android.blogreader W/art﹕ Suspending all threads took: 27.251ms
09-18 12:53:25.143    1848-1872/blogreader.com.example.android.blogreader W/EGL_emulation﹕ eglSurfaceAttrib not implemented
09-18 12:53:25.143    1848-1872/blogreader.com.example.android.blogreader W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6c420a0, error=EGL_SUCCESS
09-18 12:53:25.902    1848-2045/blogreader.com.example.android.blogreader E/MainListActivity﹕ IOException Caught

StackTrace:
09-18 14:04:48.483    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ java.net.UnknownHostException: Unable to resolve host "blog.teamtreehouse.com": No address associated with hostname
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:457)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at java.net.InetAddress.getAllByName(InetAddress.java:215)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at blogreader.com.example.android.blogreader.MainListActivity$GetBlogPostClass.doInBackground(MainListActivity.java:60)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at blogreader.com.example.android.blogreader.MainListActivity$GetBlogPostClass.doInBackground(MainListActivity.java:51)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-18 14:04:48.484    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at java.lang.Thread.run(Thread.java:818)
09-18 14:04:48.485    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
09-18 14:04:48.485    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at libcore.io.Posix.android_getaddrinfo(Native Method)
09-18 14:04:48.485    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
09-18 14:04:48.485    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:438)
09-18 14:04:48.485    1852-2058/blogreader.com.example.android.blogreader W/System.err﹕ ... 17 more
09-18 14:04:51.815    1852-1859/blogreader.com.example.android.blogreader W/art﹕ Suspending all threads took: 21.107ms
09-18 14:06:29.117    1852-1859/blogreader.com.example.android.blogreader W/art﹕ Suspending all threads took: 11.632ms
09-18 14:12:30.127    1852-1859/blogreader.com.example.android.blogreader W/art﹕ Suspending all threads took: 11.489ms

A: Perhaps a duplicate of the following -
Unable to resolve host "<insert URL here>" No address associated with hostname
Please check your manifest if you have given the necessary permissions.

A: Try the below code for sending http request with HttpUrlconnection class
    String url = "http://blog.teamtreehouse.com/api/get_recent_summary/?count=" + NUMBER_OF_POSTS;

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("User-Agent", USER_AGENT);

    int responseCode = con.getResponseCode();
    System.out.println("Response Code : " + responseCode);


text:
Q: Create a "form" inside a sheet or transfer data permanently onto a new tab I would like to find a way where for example I have sheet1 and sheet2:
Sheet 1 is where I write my data, lets say from A1:E10.
Is there a script that I can press or run after I am done inputting all the data for it to transfer it definitively onto sheet 2?
It has to be able to stay there regardless of what happens in Sheet1 after I submitted the data.
The other function I need is the data in Sheet1 can be longer (A1:E15) or sometimes less but it has to transfer and stay in sheet 2, every time below the last input.
I would like to avoid using Google Forms as it's quite basic and within the said A1:E15 I have formulas that calculate, so I can't really use Google Forms.

A: Let's assume your input is in input!A1:E and your output is in output!A:E.
In the menu bar, select Script editor and type in the following script:
function writeData () {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var inSheet = ss.getSheetByName("input");
  var input = inSheet.getRange(1, 1, inSheet.getLastRow(), 5)
    .getValues;
  var outSheet = ss.getSheetByName("output");
  var outStartRow = outSheet.getLastRow() + 1;

  for (var i = 0; i < input.length; i++) {
    for (var j = 0; j < input[i].length; j++) {
      outSheet.getRange(outStartRow + i, j + 1)
        .setValue(input[i][j]);
    }
  }
}

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var menuEntries = [];
  menuEntries.push({name: "Write data", functionName: "writeData"});
  ss.addMenu("Custom functions", menuEntries);
}

Save everything, refresh the spreadsheet. When you want to transfer the data permanently, just go to your menu bar, select Write data under the Customer functions menu.


text:
Q: What does this mean? "Content Security Policy: Directive 'frame-src' has been deprecated. Please use directive 'child-src' instead" I always see this in my waterfox console. Is it bad? I am not a coder or dev. So this kinda of thing doesn't make sense if it isn't in layman's terms. Thanks

A: If you're not a developer, then this will mean very little to you in general. This is a relatively vague error message regarding some security policies on websites you use. If you're not having any issues with the website that gives you this error, then you don't need to worry about it.
This answer is probably a vast oversimplification.
HTTP Requests
When the browser downloads a website for display, it sends an HTTP request and gets a response in two pieces: headers and content/body. The content/body of the request is generally what the browser will use to render the website. The headers are a way for the browser to receive extra information about the request.
frame-src and child-src
frame-src and child-src are part of the Content-Security-Policy header, which tells your browser what websites are allowed to be displayed in a <frame> or <iframe> element. (These elements essentially embed one page within another.)
Examples
Example 1: YouTube or Vimeo videos that you see shared on websites that aren't youtube.com or vimeo.com are embedded using an <iframe> element. If the Content-Security-Policy header doesn't allow this, then those videos won't show up.
Example 2: facebook.com might allow only other pages from facebook.com to be embedded. If a malicious script then tried to load google.com somewhere inside the page, the browser would not allow that.
Deprecation
The frame-src directive was deprecated in Content-Security-Policy level 2 in favor of child-src (which was introduced in level2). It was then undeprecated in level 3 to replace child-src again (although child-src is still available and not deprecated.
Features are often deprecated when they are being queued for removal. That is, when you upgrade a software from version 1.0 to version 2.0, you may see deprecation notices. When you then upgrade to version 3.0, those deprecation messages may turn into fatal errors, meaning you can't run your application.
In this case, websites may use frame-src and child-src for backwards compatibility with older browsers and therefore you may see an error message about whichever one isn't supported.


text:
Q: Maven Dependency - NoSuchMethodError on org.hibernate.engine.spi.SessionFactoryImplementor.getProperties()Ljava/util/Properties I'm following this blogpost to set up the Hibernate Persistence layer.
My current pom.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>projectname</artifactId>
<packaging>jar</packaging>
<version>0.1.0</version>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.1</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <transformers>
                            <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>selfserve.Main</mainClass>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.7.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>1.5.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <version>1.5.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.11.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-annotations</artifactId>
        <version>3.5.6-Final</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.9.9</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>23.1-jre</version>
    </dependency>
</dependencies>

I'm getting the following error:
Caused by: java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionFactoryImplementor.getProperties()Ljava/util/Properties;
at org.hibernate.jpa.internal.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:124)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:890)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
... 21 more

It looks like some of my dependencies conflict with one another, but I'm really not sure which one. Nothing online indicates any conflicts.
Any help or direction would greatly be appreciated!

A: Your class - org.hibernate.engine.spi.SessionFactoryImplementor - is resolved from dependency.
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.11.Final</version>
</dependency>

And this class doesn't contain the getProperties() method. Please take a look at the source code.
Get rid of this dependency. Then your class will be resolved from the dependency - hibernate-core: 5.0.12.Final and org.hibernate.engine.spi.SessionFactoryImplementor class present in this jar contains the getProperties() method.

Please let us know if you run into any issues.

A: I had the same problem using EhCache. Apparently the EhCache dependency depends on a different version of hibernate-core, causing the conflict. Changing it back to a corresponding version solved the problem:
// https://mvnrepository.com/artifact/org.hibernate/hibernate-ehcache
compile group: 'org.hibernate', name: 'hibernate-ehcache', version: '5.0.12.Final'

Given that hibernate-core version 5.0.12 is the version that is depended on by spring-boot-starter-data-jpa of course (which it is!).

A: Only use hibernate 5.2
use hibernate-core:5.2.x.Final and exclude hibernate-entitymanager as it is deprecated.


text:
Q: Android - Retro Squash Game - racket/screen sides collision I am reading "Learning Java by Building Android Games" and in a Retro Squash Game example I don't know how to implement collision detection for the racket. The movement of the racket uses onTouchEvent. I have tried to implement an if statement but it deosn't get checked until the next touch event- so it doesn't work properly. Please help.
    //Event that handles in which direction is the racket moving according to where is the user touching the screen
    @Override
    public boolean onTouchEvent(MotionEvent motionEvent) {
        //gets the movement action without the pointers(ACTION_MASK) ??? -U: handles multitouch

        switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
            //what happens if user touches the screen and holds
            case MotionEvent.ACTION_DOWN:
                //if the screen was touched on the right side of the display than move the racket right
                if (motionEvent.getX() >= (screenWidth / 2) && racketPosition.x <= screenWidth) {
                    racketIsMovingLeft = false;
                    racketIsMovingRight = true;
                } else if (motionEvent.getX() < (screenWidth / 2) && racketPosition.x >= 0) {
                    racketIsMovingLeft = true;
                    racketIsMovingRight = false;
                } else {
                    racketIsMovingLeft = false;
                    racketIsMovingRight = false;
                }

                break;
            //when the user lets go of the screen the racket immediately stops moving
            case MotionEvent.ACTION_UP:
                racketIsMovingLeft = false;
                racketIsMovingRight = false;
                break;
        }
        return true;
    }

A: Ok. I have found the solution. I wasn't looking at the right piece of code - sorry. I have edited the piece which is responsible for changing the racketPoint.x of the racket. Here it is:
    public void updateCount() {
        //change the racket position according to the movement
        if (racketIsMovingRight && (racketPosition.x+racketWidth/2)<=screenWidth) {
            racketPosition.x += racketSpeed;
        }

        if (racketIsMovingLeft && (racketPosition.x-racketWidth/2)>=0) {
            racketPosition.x -= racketSpeed;
        }

//rest of the code


text:
Q: MongoDB Show Current User How do I show the current user that I'm logged into the mongo shell as? This is useful to know because it is possible to change the user that you are logged in as—e.g. db.auth("newuser", "password")—while in the interactive shell. One can easily lose track.
Update
Using the accepted answer as a base, I changed the prompt to include user, connection, and db:
Edit .mongorc.js in your home directory.
function prompt() {
    var username = "anon";
    var user = db.runCommand({connectionStatus : 1}).authInfo.authenticatedUsers[0];
    var host = db.getMongo().toString().split(" ")[2];
    var current_db = db.getName();

    if (!!user) {
        username = user.user;
    }

    return username + "@" + host + ":" + current_db + "> ";
}

Result:
MongoDB shell version: 2.4.8
connecting to: test

anon@127.0.0.1:test> use admin
switched to db admin

anon@127.0.0.1:admin> db.auth("a_user", "a_password")
1

a_user@127.0.0.1:admin>

A: The connectionStatus command shows authenticated users (if any, among some other data):
db.runCommand({connectionStatus : 1})

Which results in something like bellow:
{
    "authInfo" : {
            "authenticatedUsers" : [
                    {
                            "user" : "aa",
                            "userSource" : "test"
                    }
            ]
    },
    "ok" : 1
}

So if you are connecting from the shell, this is basically the current user
You can also add the user name to prompt by overriding the prompt function in .mongorc.js file, under OS user home directory. Roughly:
prompt = function() {
    user = db.runCommand({connectionStatus : 1}).authInfo.authenticatedUsers[0]
    if (user) {
        return "user: " + user.user + ">"
    }
    return ">"
}

An example:
$ mongo -u "cc" -p "dd"
MongoDB shell version: 2.4.8
connecting to: test
user: cc>db.auth("aa", "bb")
1
user: aa>


text:
Q: Devex Ribbon control prevents applicetion start - entry point was not found It does work on some machine's but wold not start on other computers.
from the code line's I see the problem is related to devex components.
this is the message I get:

A: We have reviewed your old posts and here is what we have found:
It seems, you were asked about Delphi interop, but Delphi creates x86 applications.  Also, it seems, that your application fails on x64 systems.  Since, VS creates ANY CPU applications, this most likely the cause of the problem.  Try to build the application in VS for x86 platform, this should fix the problem.

A: I fixed the problem by using gacutil -i to add the dll to the assembly cache.


text:
Q: Transaction processing - Lookup millions of documents to validate transactions - Cost effective approach We recently made a shift from a relational to NoSQL (Couchbase). We are facing challenges scaling our backend to handle increasing number of users(reps). One of our product masters has over 50+ million documents and more than a million documents get modified on a day-to-day basis. There are few transactions that are processed daily which have product details in them, roughly 100,000 such transactions are processed with about 50 products in them. There is a need to check if these products are available in the product master which is a validation against 50+ million documents in Couchbase.
Our existing approach to lookup against 50+ million documents is not cost effective and increases the overall runtime of our service. We are exploring options to cache this locally or find an alternate way to perform this operation in a more efficient way.
Here is an overview of our existing data models.
Data structure 1 – Products authorized for a rep

RepID
ProductId
Prod Start Dt
Prod End Dt

1001
1
2022-05-15
9999-12-25

1001
2
2022-05-15
9999-12-25

1001
3
2022-05-15
9999-12-25

1001
4
2022-05-15
9999-12-25

1002
1
2022-05-15
9999-12-25

1002
2
2022-05-15
9999-12-25

1002
5
2022-05-15
9999-12-25

1002
6
2022-05-15
9999-12-25

1003
1
2022-05-15
9999-12-25

1003
2
2022-05-15
9999-12-25

1003
8
2022-05-15
9999-12-25

1003
9
2022-05-15
9999-12-25

Similarly, 15,000 reps have an average of 3000-4000 documents totally to 50 million documents.
Transaction document model

Order
RepID
ProductId

1234
1001
1

1234
1001
2

1234
1001
3

1234
1001
4

1234
1001
5

100
1002
1

100
1002
2

100
1002
3

1111
1003
1

1111
1003
2

1111
1003
3

1111
1003
4

In the above example, rep 1001 isn't authorized to sell product 5. Rep 1002 is not authorized to sell product 3 and rep 1003 is not authorized to sell products 3,4.
What is the most efficient way to validate these products in the order transaction comparing against millions of documents for Authorized products
One approach suggested was to use a HashMap with a list of reps and then another map for each of the reps' authorized products. This would be in-memory cache and updated as and when new products are added to product master.
Second approach suggested was to use GraphQL or Postgres SQL as it might be effective for this kind of operation.
This is a simple problem, and the only challenge is to accomplish this in a cost-effective way without multiple DB calls or even eliminate all DB calls when transactions are processed by keeping this detail in memory. I would really appreciate if someone who has already tackled similar problems could share their experience on the technology stack, tools used.

A: You might try thinking about using a pure KV solution leveraging Couchbase eventing. I think you will find that this real time solution essentially coding up a lambda or a trigger will be very performant across 10's of millions of documents. To this end I will give a concrete example below:
You seem to have two types of documents
First a sales rep authorization list here is essentially your data as JSON docs
  KEY  auth:1003
  {
    "Products": [
      {
        "EndDt": "9999-12-25",
        "ProductId": 1,
        "StartDt": "2022-05-15"
      },
      {
        "EndDt": "9999-12-25",
        "ProductId": 2,
        "StartDt": "2022-05-15"
      },
      {
        "EndDt": "9999-12-25",
        "ProductId": 8,
        "StartDt": "2022-05-15"
      },
      {
        "EndDt": "9999-12-25",
        "ProductId": 9,
        "StartDt": "2022-05-15"
      }
    ],
    "id": 1003,
    "type": "auth"
  }

  KEY  auth:1002
  {
    "Products": [
      {
        "EndDt": "9999-12-25",
        "ProductId": 1,
        "StartDt": "2022-05-15"
      },
      {
        "EndDt": "9999-12-25",
        "ProductId": 2,
        "StartDt": "2022-05-15"
      },
      {
        "EndDt": "9999-12-25",
        "ProductId": 5,
        "StartDt": "2022-05-15"
      },
      {
        "EndDt": "9999-12-25",
        "ProductId": 6,
        "StartDt": "2022-05-15"
      }
    ],
    "id": 1002,
    "type": "auth"
  }

  KEY  auth:1001
  {
    "Products": [
      {
        "EndDt": "9999-12-25",
        "ProductId": 1,
        "StartDt": "2022-05-15"
      },
      {
        "EndDt": "9999-12-25",
        "ProductId": 2,
        "StartDt": "2022-05-15"
      },
      {
        "EndDt": "9999-12-25",
        "ProductId": 3,
        "StartDt": "2022-05-15"
      },
      {
        "EndDt": "9999-12-25",
        "ProductId": 4,
        "StartDt": "2022-05-15"
      }
    ],
    "id": 1001,
    "type": "auth"
  }

Second a bunch of orders coming in that you want to validate here is essentially your data as JSON docs (I took the liberty of adding one more to get a success)
  KEY: order:1234
  {
    "ProductIds": [
      1,2,3,4,5
    ],
    "RepID": 1001,
    "id": 1234,
    "type": "order"
  }

  KEY: order:1111
  {
    "ProductIds": [
      1,2,3,4
    ],
    "RepID": 1003,
    "id": 1111,
    "type": "order"
  }

  KEY: order:2222
  {
    "ProductIds": [
      8,9
    ],
    "RepID": 1003,
    "id": 2222,
    "type": "order"
  }

  KEY: order:100
  {
    "ProductIds": [
      1,2,3
    ],
    "RepID": 1002,
    "id": 100,
    "type": "order"
  }

Now here is an Eventing function (it will run in 6.X and 7.X mode although 7.X will be much faster if you take advantage of bucket backed caching)
// Need two buckets (if 7.0+ keyspaces of _default._default)
//     "eventing"
//     "data"
// Need one bucket binding
//     alias = src_col bucket = data mode = r+w
// For performance set workers to 2X VCPUs for large data sets
// or for very fast mutation rates.

function OnUpdate(doc, meta) {
    // only process and validate orders (might add more filters here).
    if (doc.type !== "order") return;

    // level 1 is what you want, else to look at issue just raise the #
    var DEBUG = 1;
    // Use bucket backed caching to speed up loading of check document by 25X
    var VERSION_AT_702 = false;

    if (DEBUG > 1) log("checking order", meta.id);

    // load the rep's authorized products fromthe bucket binding.

    var auths;
    if (VERSION_AT_702 == false) {
        auths = src_col["auth:" + doc.RepID];
    } else {
        // use bucket backed caching.  Will only read KV at most once per
        // second per each Eventing node. Costs  just 1/25th of a std. Bucket Op.
        var result = couchbase.get(src_col,{"id": "auth:" + doc.RepID}, {"cache": true});
        if (!result.success) {
            auths = null;
        } else {
            auths = result.doc;
        }
    }
    if (!auths) {
        if (DEBUG > 0) log("no auth record found for RepID", doc.RepID);
        return;
    }
    if (DEBUG > 4) log(auths);

    // since I save the lists this isn't an optimal check
    var is_authed = [];
    var is_not_authed = [];
    // now make sure the rep is authorized to sell all products
    for (var k = 0; k < doc.ProductIds.length; k++){
        var prod = doc.ProductIds[k];
        if (DEBUG > 1) log("checking product",prod);
        var okay = false;
        for (var j = 0; j < auths.Products.length; j++){
            var auth = auths.Products[j];
            if (DEBUG > 6) log("\t1.",auth);
            if (auth.ProductId == prod) {
                if (DEBUG > 8) log("\t\t2.",auth.ProductId," === ", prod, "GOOD");
                okay = true;
            } else {
                if (DEBUG > 8) log("\t\t2.",auth.ProductId," === ", prod, "BAD");
            }
        }
        if (okay === false) {
            is_not_authed.push(prod);
        } else {
            is_authed.push(prod);
        }
        if (DEBUG > 5) log("prod",prod,"authed",okay);
    }

    // =====================================================
    // we have an issue id is_not_authed.length > 0
    //======================================================
    if (is_not_authed.length > 0) {
            if (DEBUG > 0) log("BAD illegal order", meta.id, "rep", doc.RepID, "can sell products", is_authed, "but can't sell products", is_not_authed);
    } else {
            if (DEBUG > 0) log("VALID legal order", meta.id, "rep", doc.RepID, "can sell products", is_authed);
    }
    // =====================================================
    // we could move the document or modify it but that's
    // you business logic.  Typically we might do something like:
    // 1. update the document with a new tag.
    //     doc.verify_status = (is_not_authed.length == 0)
    //     src_col[meta.id] = doc;
    // 2. at the top of the Function add another filter to
    //    prevent redoing the same work.
    //     if (doc.verify_status) return;
    //======================================================
}

Running the above Eventing function against the above data I get the following log messages.
2022-08-03T19:14:50.936+00:00 [INFO] "BAD illegal order" "order:1111" "rep" 1003 "can sell products" [1,2] "but can't sell products" [3,4]

2022-08-03T19:14:50.848+00:00 [INFO] "BAD illegal order" "order:100" "rep" 1002 "can sell products" [1,2] "but can't sell products" [3]

2022-08-03T19:14:50.812+00:00 [INFO] "VALID legal order" "order:2222" "rep" 1003 "can sell products" [8,9]

2022-08-03T19:14:50.797+00:00 [INFO] "BAD illegal order" "order:1234" "rep" 1001 "can sell products" [1,2,3,4] "but can't sell products" [5]

Of course you want to do something other than log a message perhaps you want to move the document, add or update a property in the document, or do other actions after all your working with pure JavaScript with KV (or Data Service) access to your data in Couchbase.
Note in the above code I kept lists of what "can" and "cannot" be sold, but if you don't need that you can optimize the loop via breaks (JavaScript v8 is fast) but I do see that at your scale efficiency is key.
Maybe break out the Products into three arrays then you could do the following:
KEY  auth:1001
{
  "id": 1001,
   "type": "auth",
  "Product": [ 1, 2, 3, 4 ],
  "StartDt": [ "2022-05-15", "2022-05-15", "2022-05-15", "2022-05-15" ],
  "StartDt": [ "9999-12-25", "9999-05-15", "9999-12-25", "9999-12-25" ]
}

The eliminate the for loops:
const includesAll = (arr, values) => values.every(v => arr.includes(v));
log(meta.id,includesAll(auths.Product, doc.ProductIds));

If the intersection "work" is too lengthy look into things like FastBitSet.js to lower the analysis time.
The easiest way to increase the performance is to enable the bucket backed cache (requires version 7.0.2 or greater), however if you don't have reuse this won't help.  BTW emitting log messages will also slow things down too so avoid that.
IMHO you should be able to process 100K docs/second on a small cluster and up to 1M docs/sec on a large tuned cluster.
If you are not familiar with the Eventing Service you should run a few "step by step" examples first to get a basic understanding.
If for some reason you need more performance (I don't think you will) there are a few advanced Eventing tricks that I can share to speed things up even no - just DM me and we'll schedule some time to talk.


text:
Q: JavaScript net.connect() - explicitly set local endpoint IP address I can't find a way to set the local endpoint field in the net.connect() function. I need to explicitly set the local endpoint to a specific IP address.
I am using the node-ads library to connect a node process to a PLC device.
In my example:
ads.tcpClient = net.connect(
    ads.options.port,
    ads.options.host,
    function () {
      ads.connected = true
      cb.apply(ads.adsClient)
    }
  )

The connect() function does not offer a parameter for this. The returning socket object also does not seem to have a field for the endpoint at all. What am I doing wrong?
The reason for this is that I am connecting to a Beckhoff PLC where the connection requires a differnt host IP address if another connection already exists on the same computer. The problem is mentionend here.
I know for a fact that it is possible in the Beckhoff-ADS C# implementation, as this code works:
 var socket = new AmsSocket(targetip, amsport)
 {
     LocalEndPoint = new IPEndPoint(IPAddress.Parse(sourceip), 0)
 };

A: UPDATE Solved the issue by doing the following:

*

*Change your ads.js file to set the source IP address explicitly

*It's better to not do this in node_modules, but to just copy the ads.js file somewhere where it does not get overwritten

Locate in ads.js:
var connect = function (cb) {
  var ads = this
  ads.tcpClient = net.connect({
    port: ads.options.port,
    host: ads.options.host,
    localAddress: ads.options.sourceIp,   // the part you have to add
  },

Pass the sourceIp in your options for the ADS connection:
 public options = {
        host: "192.168.100.1",
        amsNetIdTarget: "192.168.100.1.1.1",
        amsNetIdSource: "192.168.100.105.1.1",
        sourceIp: "192.168.100.105",
    };

Connect to your PLC:
const client = ads.connect(this.options, () => {
            console.log("Trying to connect.");
            client.readDeviceInfo((err, result) => {
                if (err) {
                    console.log("Error: " + err);
                }
                console.log("Connection result: " + JSON.stringify(result));
                client.end();
            });
        });

Simple enough, but unfortunately not supported in node-ADS.