How many ways to permute rows of a matrix without any all-zero columns, and why is the answer a hypergeometric function?

Question: I'm looking for an intuitive explanation for the answer I found to this question I came up with:
I have a matrix B with $m$ rows and $k$ columns, with entries taken from the set ${0,1, \ldots, n}$ (but these could be any set of $n+1 $ symbols instead of numbers). Numbers may be repeated.
I can permute any of the rows, i.e. swap any entry with any entry on the same row, but not with an entry on another row. The only restriction is that I may not have any column containing only zeroes.
Here's some notation.
Let $z_r$ count the number of zeroes on the $r$'th row.
Further, for $c=1, \ldots n$ let $T_{rc}$ count the number of $c$'s in the $r$'th row.
Without the restriction, it's easy to see that the number of permutations is
$$P = \frac{k!^m}{\prod_{r=1}^m \prod_{c=0}^n T_{rc}!}.$$
Apparently the final answer is to multiply this number by the following hypergeometric function:
$$_mF_{m-1} [-z_1 -z_2 \ldots -z_m; -k -k \ldots -k](1).$$
I found this through a fairly brute force approach and some simplifying with Mathematica, but I don't really understand why it should be true. It can also be expressed as a finite sum of falling factorials.
Is there some combinatorical property of hypergeometric functions that explains this? Or is there a simpler way to express the answer? Or maybe my problem is a special case of a more general problem?
Answer: There was a very similar question a little while ago. I came across a more general solution when working on sequence shuffling.
A more general version of your problem may arise as an iterated hypergeometric distribution: let $X_0=n_0$ and then $X_r\sim\text{Hypergeom}(X_{r-1},n_r,N_r)$.
Basically, your problem is that in each of the $m$ rows, $z_r$ out of the $k$ columns are picked at random: ie the zeroes. Let $X$ be the number of columns picked in all rows.
Let's compute the expected number of ways to pick $q$ out of the $X$ columns: ie $q$ all-zero columns.
First, there are $\binom{k}{q}$ ways to pick $q$ columns. Now, let's assume we look at one selection of $q$ columns. In row $r$, the chance of including all $q$ amongst the $z_r$ picked is $\binom{k-q}{z_r-q}/\binom{k}{z_r}$. Thus, the expected number of ways to pick $q$ out of the $X$ columns is
$$
\text{E}\left[\binom{X}{q}\right]
= \binom{k}{q}\cdot\prod_{r=1}^m \frac{\binom{k-q}{z_r-q}}{\binom{k}{z_r}}
= \binom{k}{q}\cdot\prod_{r=1}^m \frac{\binom{z_r}{q}}{\binom{k}{q}}.
$$
Now, let's express the $\text{E}[\binom{X}{q}$ a different using the probability generating function
$$
P_X(t) = \text{E}\left[t^X\right] = \sum_{i=0}^k \Pr[X=i]\, t^i.
$$
This makes
$$
P_X(1+u) = \text{E}\left[(1+u)^X\right]
= \sum_{q=0}^k \text{E}\left[\binom{X}{q}\right]\, u^q
= \sum_{q=0}^k
    \frac{\prod_{r=1}^m z_r!/(z_r-q)!}{[k!/(k-q)!]^{m-1}}
    \cdot\frac{u^q}{q!}\\
={}_mF_{m-1}(-z_1,\ldots,-z_m;-k,\ldots,-k;-u).
$$
Now, you can retrieve all of $P_X(t)$ by setting $u=t-1$ and doing a power expansion. In particular, the likelihood that no columns remain, $X=0$, is found by setting $t=0$, or $u=-1$, which gives your result.
Comment: This is very helpful but I'm a bit confused about what $X$ is supposed to be. What do you mean by "the number of columns picked in all rows"?
Comment: There are three small mistakes in your last equation, I think it should be
$$
P_X(1+u) = \text{E}\left[(1+u)^X\right]
= \sum_{q=0}^k \text{E}\left[\binom{X}{q}\right]\, u^q
= \sum_{q=0}^k
    \frac{\prod_{r=1}^m z_r!/(z_r-q)!}{[k!/(k-q)!]^{m-1}}
    \cdot\frac{u^q}{q!}\\
={}_mF_{m-1}(-z_1,\ldots,-z_m;-k,\ldots,-k;-u).
$$
Comment: When you compute the expected number of ways to pick $q$ out of the $X$ columns, it seems like you're including the possibility that there may be more than $q$ all-zero columns? But maybe it just seems that way because I don't know what $X$ is.
Comment: A row "picks" a column if the value is zero. And $X$ may both be more or less than $q$: if $Xq$ there are many ways. Point is, these expected numbers can be more easily computed than the individual probabilities. And thanks for pointing out the error in the formula: corrected it now.


Comparing two lists of objects with lists of strings and ensuring no overlap

Question: I have an object that contains multiple lists.
Public Class aObject
    Public Property title
    Public Property aList As List(Of String)
    Public Property bList As List(Of String)
    Public Property cList As List(Of String)
    Public Property dList As List(Of String)
End Class

I have another object where I store all the aObjects.
Public Class bObject
 Private _LocalCollection As List(Of aObject)
 Private _RemoteCollection As List(Of aObject)
End Class

Each list in aObject is a different setting. If I add a new setting, I want to be able to make sure that all the combinations never cross. So, if I was storing letters in aList and numbers in bList and had an object with {1,6,7} and {a,d,z}, I would not want to add another setting with lists {2,6,8} and {a,f,g}. However, I would want to add the lists {1,6,7} and {b,c,f}. All four lists are the same way. I need to check the combination of the four. I can use a recursive algorithm and check all the values, but I was wondering if there was some other way.
I used the following suggested answer and implemented it:
Public Function checkDuplicates(ByVal strChampions As List(Of String), ByVal strSummonerSpells As List(Of String), ByVal strModes As List(Of String), ByVal strMaps As List(Of String)) As Boolean
    Dim booDuplicates As Boolean = False
    For Each setting In _LocalSettings
        Dim l1 = setting.champions.Intersect(strChampions)
        If l1.Count() > 0 Then
            Dim l2 = setting.summonerspells.Intersect(strSummonerSpells)
            If l2.Count() > 0 Then
                Dim l3 = setting.modes.Intersect(strModes)
                If l3.Count() > 0 Then
                    Dim l4 = setting.maps.Intersect(strMaps)
                    If l4.Count() > 0 Then
                        booDuplicates = booDuplicates Or True
' I am going to create the duplicate settings here to know where to overwrite.
                    End If
                End If
            End If
        End If
    Next
    Return booDuplicates
End Function

Answer: What if you check the intersection of the lists to see if there are common elements?
https://msdn.microsoft.com/en-us/library/bb460136(v=vs.110).aspx

The intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B, but no other elements.

Sub Main()
    Dim a As New List(Of String) From {"1", "6", "7"}
    Dim b As New List(Of String) From {"a", "d", "z"}
    Dim c As New List(Of String) From {"2", "6", "8"}

    Console.WriteLine(String.Format("a intersects b: {0}", a.Intersect(b).Count > 0))
    Console.WriteLine(String.Format("a intersects c: {0}", a.Intersect(c).Count > 0))
    Console.WriteLine(String.Format("b intersects c: {0}", b.Intersect(c).Count > 0))

    Console.ReadLine()
End Sub

Outputs:
a intersects b: False
a intersects c: True
b intersects c: False

Comment: Sounds great. I have to reiterate through all the objects, but I realized it's actually important what intersects as well. That way, I can overwrite or not. Now, I just have to figure out how to overwrite the objects. Thank you.


How to observe contentprovider change? android

Question: I'v created a Contentprovide and implements it's update() method like this:
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    final SQLiteDatabase db = mHelper.getWritableDatabase();
    int count = db.update(InslideDB.FOLDER_TABLE, values, selection, selectionArgs);

    /* To notify the observer */
    this.getContext().getContentResolver().notifyChange(URI, null);
    return count;
}

How can I get notified in my appwidget? Thanks!
I'm trying this Resolver but no Log (--------------------Date Changed) print:
class DataProviderObserver extends ContentObserver {
    private AppWidgetManager mAppWidgetManager;
    private ComponentName mComponentName;

    DataProviderObserver(AppWidgetManager mgr, ComponentName cn, Handler h) {
        super(h);
        mAppWidgetManager = mgr;
        mComponentName = cn;
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);  //NOTE: Have to call this. dwy.

        // The data has changed, so notify the widget that the collection view needs to be updated.
        // In response, the factory's onDataSetChanged() will be called which will requery the
        // cursor for the new data.

        Log.d("PresenterWidgetProvider", "--------------------Date Changed");

        mAppWidgetManager.notifyAppWidgetViewDataChanged(
                mAppWidgetManager.getAppWidgetIds(mComponentName), R.id.inslide_grid);
    }
}

public class PresenterWidgetProvider extends AppWidgetProvider{

    private static final String AUTHORITY = "com.apps.slide";

    static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/folder");

    public static final String EXTRA_INSLIDE_PATH = "EXTRA_WIDGET_PATH";
    private static HandlerThread sWorkerThread;
    private static Handler sWorkerQueue;
    private static DataProviderObserver sDataObserver;

    public PresenterWidgetProvider () {

        // Start the worker thread to update Content Provider.
        sWorkerThread = new HandlerThread("PresenterWidgetProvider worker");
        sWorkerThread.start();
        sWorkerQueue = new Handler(sWorkerThread.getLooper());

    }

    @Override
    public void onEnabled(Context context) {
        // Register for external updates to the data to trigger an update of the widget.  When using
        // content providers, the data is often updated via a background service, or in response to
        // user interaction in the main app.  To ensure that the widget always reflects the current
        // state of the data, we must listen for changes and update ourselves accordingly.
        final ContentResolver r = context.getContentResolver();
        if (sDataObserver == null) {
            final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
            final ComponentName cn = new ComponentName(context, PresenterWidgetProvider.class);
            sDataObserver = new DataProviderObserver(mgr, cn, sWorkerQueue);
            r.registerContentObserver(CONTENT_URI, true, sDataObserver);
            Log.d("PresenterWidgetProvider", "--------------------onEnabled. sDataObserver = " + sDataObserver);
        }
    }

So, I finally solved it by 4 steps:

Add
this.getContext().getContentResolver().notifyChange(URI, null);

to ContentProvider's updat() insert() delete() callbacks.

Create a new Observer and new Thread to handle it.
Call notifyAppWidgetViewDataChanged() in Observer's onChange().
Delete the widget and place a new one.

That's it.
Comment: Thanks for sharing this. I think it is not enough to register the observer in onEnabled, since onEnabled is not called again after device is restarted. I'd put it into onReceive.
Answer: You can use the ContentObserver class. You just have to implement that class and use the getContentResolver().registerContentObserver() method to register the observer.
Comment: I think you cannot register the observer inside your `AppWidgetProvider`. Instead, start a service from your `AppWidgetProvider`, and register your `ContentObserver` from there.
Comment: @Ctristian Thanks! And I've use the ContentObserver but it didn't call callback onChange(). I've update the code to questions. I'm get a little cofused about how to use Observer and how to update widget then. Thanks again!
Comment: I have solved it. The complete code is updated above. Thank you.
Comment: @Cristian I have similar query. In my application I am using content provider :-android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI to list the image files. Now I want that whenever this content provider data gets changed, I want to Toast a message to user. How can I do that. Please help


Monotouch iPhone Project not appearing in MonoDevelop

Question: I have just installed Mono 2.10.1_3, MonoDevelop 2.4.2, and MonoTouch 4.0.3.  In the order outlined on the website.  Now I am trying to walk through some of the tutorials for developing on the iPhone using MonoTouch.  However, I am stuck right at the start on the HelloWorld tutorial:
http://monotouch.net/Tutorials/MonoDevelop_HelloWorld
When creating a new solution and selecting C# then iPhone and iPad:

iPhone Window-based Project
iPhone OpenGL Project
iPhone Navigation-based Project
iPhone Utility Project
MonoTouch Library Project
Empty MonoTouch Project
iPad Window-based Project
Universal Window-based Project

There is no iPhone MonoTouch Project displayed in this list as shown in the Tutorial.  So I guess my question is this:  should there be an option for iPhone MonoTouch Project in the list or is this a newer version and this project template has been replaced by one of the options shown above?  If so, which one?
Comment: It seems that these are the new options for this version of MonoTouch.  I found this site: [knowing.net](http://www.knowing.net/index.php/monotouch-navigation-controller-tutorial/) and it shows the same options I am seeing in MonoDevelop.  It would appear the tutorial needs to be updated.
Answer: iPhone Window-based Project is your friend
(it shows an small C# indicating the usage of MonoTouch)


Trying to understand "smaller" in 334.15 Exposed Work and across joists

Question: I'm trying to understand 334.15 Exposed Work:
"Where cable is run at angles with joists in unfinished basements and crawl spaces, it shall be permissible to secure cables not smaller than two 6 AWG or three 8 AWG conductors directly to the lower edges of the joists. Smaller cables shall be run either through bored holes in joists or on running boards".
Question:

When they say smaller do they mean in diameter or by gauge number? I want to run 6/3 with ground NM on the ceiling of an unfinished basement.
Are they also saying that I can run 6/3 perpendicular to the joists attached to their underside without running boards?
Answer: It means actual size, not designator number.
6/3 is larger than 8/3 or 6/2, you do not need to bore holes or use running boards on the ceiling. Running down a wall requires protection.
Comment: The OP says it's an unfinished basement. If there is any chance the OP or subsequent owner would want to finish it, that cable would be in the way.   If practical, I'd consider running thru holes in the joists, just to keep it out of the way and well supported. Not a big deal, just trying to help future-proof it.
Comment: @GeorgeAnderson Sometimes I wish to provide an alternative to some tldr answers and just try to answer the question asked. The NEC allows things that aren't always best practice. If practical I would definitely make drilling the joists my first option. Second option would be installing with a (secured) extra loop providing slack to provide it could be repulled later if desired.
Comment: Yes, it's sometimes just a judgement call when to just "answer the question" or go on with additional advice. That's why I didn't post this as answer, just a comment.   I agree with your answer, BTW, I just wanted to offer my suggestion to potentially save some pain later! +


Python code for removing column with pandas,os,glob changes values of entire table

Question: I have this code that removes a column from a csv file. It works, but when it saves it adds decimal places (seemingly at random) to some of my values in other columns. For example, when I run the code, the value in another column changes from the original 1.815 to 1.8159999999999998, or 1.783 to 1.7830000000000001. Is there a way for me to prevent this from happening? I don't understand why it changes some values in other columns if I'm just removing column [0]. Thanks!
import pandas as pd
import os
import glob

def main():
    path = os.getcwd()
    csv_files = glob.glob(os.path.join(path, "*.csv"))
    for f in csv_files:
        df = pd.read_csv(f)
        first_column = df.columns[0]
        df = df.drop([first_column], axis=1)
        df.to_csv(f, index=False)
main()

Comment: Does this answer your question? [float64 with pandas to\_csv](https://stackoverflow.com/questions/12877189/float64-with-pandas-to-csv)
Answer: That's how computers work! They cannot exactly represent floating point numbers.
https://docs.python.org/3.9/tutorial/floatingpoint.html
You can round them again when writing back to your file using float_format
df.to_csv(f, index=False, float_format="%.f3")

Or use "%.g3" to remove trailing zeroes.


Delegate problem with NSTextField

Question: I am just starting with OSX development, and I am trying to get delegate notifications from a NSTextField. I've got the following code so far:
This is where I set the delegate:
- (void) awakeFromNib {
    NSLog(@"Setting delegate");
    [amountField setDelegate: [[TextfieldController alloc] initWithLog]];
}

And this is my TextfieldController:
- (TextfieldController *) initWithLog {
    self = [super init];
    NSLog(@"TextfieldController initialized");
    return self;
}

- (void)textDidChange:(NSNotification *)aNotification {
    NSLog(@"textdidChange");
}

- (void)keyUp:(NSNotification *)aNotification {
    NSLog(@"keyUp");
}

However, neither textDidChange nor keyUp is ever called... Not sure what I'm missing here, because the same way works just fine when I use it for my main window with the windowDidMiniaturize notification...
Anyone able to help? :)
Answer: The delegate should implement -controlTextDidChange:, not -textDidChange:. The -textDidChange: method is a method on NSTextField which causes it to post a notification and call [self.delegate controlTextDidChange:]. As for -keyUp:, that's part of NSControl's event-handling behaviour. If you want your delegate to receive a message when the textfield handles a key up event, you'll need to arrange that yourself by subclassing NSTextField.

Delegate problem with NSTextField


Dynamic array in java

Question: What i am trying to do is
...
int sum[];
...
for(int z.....){
   ...
   sum[z] = some_random_value;
   ...
}

But it gives an error at line sum[z]=ran; that variable sum might not have been initialized.
I tried int sum[] = 0; instead of int sum[]; but even that gave an error.
(I am basically a C programmer)
Comment: okay this problem is relatively simple one. First initialize an array with some length and populate it. always keep a check if array is full or not. If it's full create a new array instance with double the size. keep on doing it.
Answer: An array of dynamic size isn't possible in Java - you have to either know the size before you declare it, or do resizing operations on the array (which can be painful).
Instead, use an ArrayList<Integer>, and if you need it as an array, you can convert it back.
List<Integer> sum = new ArrayList<>();
for(int i = 0; i < upperBound; i++) {
    sum.add(i);
}
// necessary to convert back to Integer[]
Integer[] sumArray = sum.toArray(new Integer[0]);

Answer: This is for getting rid of compile-time error:
int sum[] = null;

However, to prevent runtime-errors I strongly suggest you to initialize your array like this:
int[] sum = new int[10];

The number in brackets denotes the array size.
And if your size is dynamic, then use a List implementation, such as ArrayList.
Answer: int sum[]= new int[length];

You haven't initialized. As of now , you just declared.
And do not for get that the length of the array should decide at the time of initialization.
Even if you do int sum[] = null; you'll end up with an NullPointerException while you do  sum[z]=ran;

Can't i just keep it dynamic? the length is variable

No. Arrays lenght should be fixed while initializing it. Look into Collection's in java. More specifically A List interface with ArrayList implementation, which is

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null.

By writing int[] anArray = new int[10];  you are telling that

Allocate an array with enough memory for 10 integer elements and assigns the array to the anArray variable.

Seems you are new to array's and even for java. The tutorial may help you better to understand.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Comment: Can't i just keep it dynamic? the length is variable
Comment: No, In java you cannot. That is fixed. You may want to  look at Collections framework.
Comment: why int sum[]= new int[length];
and not int sum[length];
Comment: @DakshShah That's the syntax of how can an array declared :) .It is good to know that there are many ways to initialize an array too.
Answer: If you're talking about dynamic arrays, the class can be represented as -
public class DynArray {
    private int size; // The current size of the array (number of elements in the array)
    private int maxSize; // Size of memory allocated for the array
    private Object[] array; // size of array == maxSize

    /**
     * An array constructor
     * Argument specifies how much memory is needed to allocate for elements
     *
     * @param sz
     * @throws IndexOutOfBoundsException
     */
    public DynArray(int sz) throws IndexOutOfBoundsException {
        // Here called another more general constructor
        this(sz, sz, null);
    }
    /**
     * Call the constructor, in which indicated how much memory is allocated
     * for the elements and how much memory is allocated total.
     *
     * @param sz
     * @param maxSz
     * @throws IndexOutOfBoundsException
     */
    public DynArray(int sz, int maxSz) throws IndexOutOfBoundsException {
        // Here called another more general constructor
        this(sz, maxSz, null);
    }
    /**
     * Additional argument contains an array of elements for initialization
     *
     * @param sz
     * @param maxSz
     * @param iniArray
     * @throws IndexOutOfBoundsException
     */
    public DynArray(int sz, int maxSz, Object[] iniArray) throws IndexOutOfBoundsException {
        if((size = sz) < 0) {
            throw new IndexOutOfBoundsException("Negative size: " + sz);
        }

        maxSize = (maxSz < sz ? sz : maxSz);
        array = new Object[maxSize]; // memory allocation

        if(iniArray != null) { // copying items
            for(int i = 0; i < size && i < iniArray.length; i++) {
                array[i] = iniArray[i];
                // Here it was possible to use the standard method System.arraycopy
            }
        }
    }
    /**
     * Indexing
     *
     * @param i
     * @return
     * @throws IndexOutOfBoundsException
     */
    public Object elementAt(int i) throws IndexOutOfBoundsException {
        if (i < 0 || i >= size) {
            throw new IndexOutOfBoundsException("Index" + i +
                    " out of range [0," + (size - 1) + "]");
        }
        return array[i];
    }
    /**
     * Changing the current size of the array. argument delta specifies
     * direction of change (positive - increase the size;
     * negative -  decrease the size)
     *
     * @param delta
     */
    public void resize(int delta) {
        if (delta > 0) enlarge(delta); // increasing the size of the array
        else if (delta < 0) shrink(-delta); // decreasing the size of the array
    }
    /**
     * Increasing the size of the array
     *
     * @param delta
     */
    public void enlarge(int delta) {
        if((size += delta) > maxSize) {
            maxSize = size;
            Object[] newArray = new Object[maxSize];

            // copying elements
            for(int i =0; i < size - delta; i++)
                newArray[i] = array[i];

            array = newArray;
        }
    }
    /**
     * Decreasing the size of the array
     *
     * @param delta
     */
    public void shrink(int delta) {
        size = (delta > size ? 0 : size - delta);
    }
    /**
     * Adding a new element
     * (with a possible increasing the size of the array)
     *
     * @param e
     */
    public void add(Object e) {
        resize(1);
        array[size-1] = e;
    }
    /**
     * Removing the given value - shifting elements and subsequent
     * reduction the size of the array
     *
     * @param e
     */
    public void remove(Object e) {
        int j;
        for(j = 0; j < size; j++) {
            if(e.equals(array[j])) {
                break;
            }
        }

        if(j == size) {
            return false;
        } else {
            for(int k = j; k < size; k++)
                array[k] = array[k + 1];

            resize(-1);
            return true;
        }
    }
}

Comment: I don't disagree, but this is not one of those times.  Also note, your copying of elements in the originating array is inefficient; reference [ArrayList's code](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/util/ArrayList.java#ArrayList) to see more performant behavior.
Comment: The only time I can think of needing to re-implement such a type [over ArrayList] is for specialized types, such as `int[]` as a backing, but this is not doing that (and even those already exist) .. also, for the love of nominative typing, implement List.
Answer: You still need to initialize your array after it's declared: int sum[]= new int[length];.
Now you can assign values in the array up to the size specified when you initialized it.
If you want to have a dynamically sized array, use ArrayList and call toArray at the end to convert it back to a regular array.

Dynamic array in java


openlayers 3 ol.proj.transform is converting dynamic geolocation points to zero

Question: I am trying to use an example from stackoverflow to insert dynamic data into map using openlayers 3.* .
the problem is : the code is running OK when I insert the numbers direct to the statement like this:
<code> geometry: new ol.geom.Point(ol.proj.transform([-72.0704,46.678],'EPSG:4326','EPSG:3857')),
</code>
but when I tried to simulate json data as the following code: then some magic happened :

When substituting only the longitude I got the marker on the right
location,
When substituting only the latitude then the latitude will be converted to zero,
When substituting longitude and latitude, the marker will not show
up.
<code>function AddMarkers() {
var iconFeatures=[];
data  = [{"longitude":"-72.0704","latitude":"46.678"},{"longitude":"-73.1234","latitude":"45.678"},{"longitude":"46.738586","latitude":"24.774265"}];

var iconFeature = new ol.Feature({
  geometry: new ol.geom.Point(ol.proj.transform([data[0].longitude,46.678], 'EPSG:4326',
  'EPSG:3857')),
  name: 'Null Island',
  population: 4000,
  rainfall: 500
});

var iconFeature1 = new ol.Feature({
  geometry: new ol.geom.Point(ol.proj.transform([28.7753927 , data[1].latitude], 'EPSG:4326',
  'EPSG:3857')),
  name: 'Null Island Two',
  population: 4001,
  rainfall: 501
});
var iconFeature2 = new ol.Feature({
  geometry: new ol.geom.Point(ol.proj.transform([data[2].longitude,data[2].latitude], 'EPSG:4326',
  'EPSG:3857')),
  name: 'Null Island Two',
  population: 4002,
  rainfall: 502
});
iconFeatures.push(iconFeature);
iconFeatures.push(iconFeature1);
iconFeatures.push(iconFeature2);

var vectorSource = new ol.source.Vector({
  features: iconFeatures //add an array of features
});

var iconStyle = new ol.style.Style({
  image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
    anchor: [0.5, 46],
    anchorXUnits: 'fraction',
    anchorYUnits: 'pixels',
    opacity: 0.75,
    src: 'images/icon.png'
  }))
});

var vectorLayer = new ol.layer.Vector({
  source: vectorSource,
  style: iconStyle
});

return vectorLayer;
</code>
}

So, why this magic happened only when using data from a json array, but is not happening when the numbers inserted directlty to the statement.
Answer: I am using php json encoding json_encode() and adding quotation marks to data , So Remove (trim) the quotation marks from the longitude and latitude values.


Can't install Gvim

Question: I've installed Gvim and synaptic package manager on 12.04, Gvim had a warning each time I ran it from terminal. So I removed it and tried to install again but came with the following error from software center:
<code>The following packages have unmet dependencies:

vim-gnome: Depends: vim-gui-common (= 2:7.3.429-2ubuntu2) but 2:7.3.429-2ubuntu2.1 is to be installed
       Depends: vim-common (= 2:7.3.429-2ubuntu2) but 2:7.3.429-2ubuntu2.1 is to be installed
       Depends: vim-runtime (= 2:7.3.429-2ubuntu2) but 2:7.3.429-2ubuntu2.1 is to be installed
</code>
I disabled repositories from software center and just enabled the "main" and the error is still present, software center crashes sometimes too.
What should I do so?
Comment: I guess the problem is unsuccessful remove of gvim because when I try to install the gvim, it's icon appears on the launcher, but the error comes after that, the other opportunity is incompatibility of synaptic.
Comment: there is a common warning with gvim due to not supporting the global menubar.  There's a way to get rid of it, but it's not something to worry about.
Comment: @MartyFried: I've got these: "(gvim:5122): Gnome-WARNING **: Accessibility: failed to find module 'libgail-gnome' which is needed to make this application accessible

(gvim:5122): GLib-GObject-WARNING **: cannot retrieve class for invalid (unclassed) type `'". Is it that?
Comment: No, I'm pretty sure that's a different error message; sorry, I don't remember the exact one I used to get - I use Gnome classic, not Unity, now.
Answer: Try to remove "vim-common":
<code>$ sudo apt-get autoremove vim-common
</code>
And then install "vim" with:
<code>$ sudo apt-get install vim
</code>
This will install correct version of "vim-common", and later you can install GVim through the software package manager.
Answer: I think you need to also enable the update source.
This look like it try to install a old version of gvim while there is a newer version of some components installed, and a strict version checking.
Comment: what can I do that Ubuntu forgets everything about Gvim?
Comment: It looks to me like it's trying to install the same version, not an old version.  Just look at the versions in the error message - they are the same.
Comment: But not the same release : 2:7.3.429-2ubuntu2 and 2:7.3.429-2ubuntu2.1 , note the .1 in the end, so this was a update. See http://packages.ubuntu.com/precise-updates/vim and http://packages.ubuntu.com/precise/vim
Comment: I see - same files, same version, but from an updated repository, I assume.  I thought it was a different problem, probably because I don't pay that much attention to the update process.  I just update what it tells me to, and haven't needed to know the details (fortunately).

Can't install Gvim


Why I can't printout value from main method?

Question: //I'd like to now why I can;t printout the return value in below java code
public class client08 {
public static void main(String[] args) {

    String w=test();
    System.out.println(w);**// I'd like to print out the return value here but it now work**
}
public String test() {
    String result="";
    String[] words=new String[5];
    words[0]="Amy";
    words[2]="Tom";
    words[4]="Jane";

    for(int i=0; i<words.length;i++) {
        if(words[i]!=null) {
            result=words[i].toUpperCase();
        }else {
            result="null";
            }
    }
    return result;

}

Comment: You'll have to be more specific about the problem. Is it the one about calling non-static methods from a static context?
Answer: First of all class names should start with an upper case character. Learn and follow Java conventions.
Next:

Your code doesn't compile.

You can't invoke a method from your "client08" class unless you create an instance of the class or make the method static.

So the code should be:
//String w=test();
client08 client = new client08();
String w= client.test();

Or you need to make the method static:
public static String test() {

Then you would invoke the method using:
String w = client08.test();
System.out.println(w);


How to modify order of tabbed windows in XMonad?

Question: I'm using tabbed and I would like to change behavior so that the new window is created on the right side (like browser tabs).
I see no easy way to do this. Do I need to write a new layout?
Answer: http://hackage.haskell.org/package/xmonad-contrib-0.13/docs/XMonad-Hooks-InsertPosition.html
You need to set this on your config's manageHook:
import XMonad.Hooks.InsertPosition

... manageHook = insertPosition End Newer <+> myManageHook

The type signature of insertFunction is Position -> Focus -> ManageHook. In plain English:  it is a function that takes a Focus and Position (in this case End and Newer), and it returns a ManageHook.
Comment: Awesome! I recalling visiting that page, but couldn't figure out what any of those enums mean. If you happen to know, can you please expand the answer?
Comment: Sorry my bad it should be `End Newer` instead of `Master Newer`.


Broken Tile Repair

Question: Is there a way to replace a toothbrush holder tile?  This is ceramic or porcelain crica 1948.
The attempt to glue made the situation worse.
Answer: Yes, but it will require a hammer, chisel and a grinder. Expect a lot of dust. The brush holder is still available, so you will be able to get a replacement. Once the old one is out, it is held in place with grout.
You will need to start with a grout saw to remove the grout in the joint between the holder and surrounding tile, it will lessen the chance of chipping the neighboring tile.
Comment: If you have never handled tile it may be best for the pros, Tile removal without chipping other tiles requires a bit of expertise. The task could easily expand into a tile repair as well.
Comment: Pretty much depends on the DIY-er. It's do-able, but (like many other things) if you're not comfortable doing it, it may be advisable to hire someone - but check references carefully, some folks do tile professionally but not very well.
Comment: Is it a DIY job or best left to the pros?

Broken Tile Repair


bootstrapVue radio-button-group are rendered in stacked mode instead in default inline mode

Question: I use bootstrapVue version 2.21.2 with bootstrap version 5.1.3.
This bootstrapVue version in  tag default generates inline radio inputs,
https://bootstrap-vue.org/docs/components/form-radio#inline-or-stacked-radios
But in my project are generated in stacked mode:

     ignora
     non in regola
     in regola

browser render
How to render inline? Have any idea?
Answer: After few step I resolved question.
It is a problem of plugin version .
BootstrapVue v.2.21.x was designed to interoperate with bootstrap v4.5.3, setting up my project folder, the installer, for default, have downloaded last version 5.x of bootstrap which is incompatible.
Step for resolving...

change file "package.json" substituting "bootstrap": "^5.x" in dependencies object with

"dependencies": {
    "bootstrap": "4.5.3",
...
}

in folder project run

npm update


constexpr static member before/after C++17

Question: As far as I can see, a very common situation is something like
template<int i> class Class
{
public:
    static constexpr int I = i;
    static constexpr int J = constexprFunction(i);
    // further Class implementation
};

Almost as common I see the mistake (in fact most of my questions here are because I forgot it and did not know, what the proper question had been) to forget the additional definition if the member are odr-used:
template<int i> constexpr int Class::I;
template<int i> constexpr int Class::J;

Now I read cppreference: Definitions and ODR and cppreference: static members, which state, that this is deprecated for C++17. This seems great to me, because it avoids a lot of errors. But there are other questions, that came up:
1) Has this change other reasons than making the additional definitions useless? (See also last paragraph of this question)
2) In the last example of cppreference: static members it seems also to apply on const static member - but the rule states only the constexpr member. Will it apply on const static member or not?
3) All examples I found were using a simple definition like Class::I - does it all hold also for the situation at Class:J with constexpr functions?
A brief state what the best practices are before C++17 and with C++17 would be great. All in all this seems a very tricky change to me, because it will make a lot of code, which was "ill-formed non diagnostic required" before, to good code (as far as I understand...). And consequently there will be code produced, that is still "ill-formed non diagnostic required" with older (pre 17) compiler - but these will not complain, as long as no odr-use is required.
Edit: Corrected the text, suggested by Aaron McDaid.
Comment: I think the last example on static data members was an editing error (now fixed): 220.127.116.11[class.static.data]p3 says, for "non-volatile non-inline const static data member", "The member shall still be defined in a namespace scope if it is odr-used"
Comment: I'm confused by the text in the question currently:  *"mistake  ... to give a definition if the members are odr-used"*. Surely you mean, in C++11 for example, that it is a mistake to *fail* to give a definition? Did you forget a negation? (Sorry if this seems very pedantic, but I genuinely don't know this well enough to be sure of the intention here )
Comment: @AaronMcDaid Yes, that it is true. I fixed it. I clearly meant that it is necessary  to give the additional definition in C++11, but this is no longer true in C++17. Therefore I tried to explain my confusion in the purpose of downwards compatibility in the last paragraph.
Comment: @Cubbi: Is is possible, that this feature is not implemented to the gnu compiler yet? I tried it with the MWE of [this question](http://stackoverflow.com/questions/39642434/template-and-constexpr-deduction-at-compiletime-dependent-on-compiler-and-optimi), compiling with `g++-6` and `-std=C++17`. It still complains about the lack of a definition! Or am I thinking something stupid?
Comment: @marlam This feature is not even listed in the gcc [compliance status table](https://gcc.gnu.org/projects/cxx-status.html#cxx1z). It is available in [clang 3.9](http://clang.llvm.org/cxx_status.html#cxx17). It is also available in MSVC 2015 (though in this case beause of a lack of Standardness)
Comment: If the definitions should be present under C++11 (and C++14), but are not needed (or even forbidden) under C++17, is there a simple `#ifdef` that could be wrapped around the definitions? Perhaps the standard should specify a macro `_CONSTEXPR_STATIC_DEFNS_NOT_NEEDED` or something monstrous like that :-)
Comment: @mariam try gcc HEAD 7.0.0 on http://melpon.org/wandbox/
Comment: @Cubbi: This also does not work without the additional definition. Seems to be like metalfox suggests. Only the clang HEAD does work properly with this feature.
Answer: This change is due to the inline variables proposal (P0386). static constexpr will imply inline, making definitions redundant.

In Annex D, add a new subclause, "Redeclaration of static constexpr data members", D.X, with the following content:
  For compatibility with prior C++ International Standards, a constexpr static data member may be redundantly redeclared outside the class with no initializer. This usage is deprecated.
[Example:
struct A {
static constexpr int n = 5; // definition (declaration in C++2014)
};
const int A::n; // redundant declaration (definition in C++2014)

—end example]

Regarding to your questions:

Has this change other reasons than making the additional definitions useless?

In essence, no. Yet it has additional uses besides the one you noted (see this question). This proposal was controversial because it might encourage the use of a mutable global state.

Will it apply on const static member or not?

No. Unless you annotate it as inline.

does it all hold also for the situation at Class:J with constexpr functions?

Yes. The proposal deals with linking but does not affect initialization rules.
Comment: I know it is a quote, but isn't it a bit confusing to declare a `constexpr` and to define it as `const`? Because this seems to me to be not the same...
Comment: @marlam It surprised me too. I think it is a typo.
Comment: It was really difficult to understand the OP's questions, the English wording is confusing. Maybe this wasn't asked directly, but: Does `static constexpr` mean the same as `constexpr` in C++17? It's always confused me why I'd use one or the other in a class declaration for constant member variables. If it's `constexpr`, it can't be changed, so isn't `static` redundant? Also now if `constexpr` means `inline`, isn't it the same as saying `static inline` which makes no sense?
Comment: @void.pointer `static constexpr` is the same as `static inline constexpr` in C++17, but `constexpr` alone does not imply `inline constexpr`. Use `static constexpr` for member variables ([example in the standard](http://eel.is/c++draft/atomics.types.generic#atomics.types.operations-5)). Use `inline constexpr` for global variables ([example in the standard](http://eel.is/c++draft/pair.piecewise)).


threshold to determine Haar Feature

Question: I try now to understand the Viola-Jones algorithm and I get confused about the threshold to determine if a block a Haar feature or not. The intensity of a pixel is in the range of 0->255.
When we have an ideal Haar feature then the delta value is 255 (like the image on the left)
but in a real image, for example on the right, delta is 146, is that a Haar feature?
my question is: which value is the threshold value to determine if a block a Haar feature or not? Or it is simply 255/2=127,5? When delta > 127.5 -> Haar feature, when delta < 127.5 -> no Haar feature?
Answer: I would like to point on some details that might help you understand Viola-Jone's algorithm.
According to the original article of Paul Viola and Michael Jones, the algorithm contains 4 main steps:

Haar Feature Selection
Creating an Integral Image
Adaboost Training
Cascading Classifiers

What you describe relates to the third stage. There is no one uniform threshold that determines if a block is a Haar feature or not. Instead, the algorithm uses Adaboost (machine learning algorithm) on training data to determine the desired value of the threshold.

"Stages in the cascade are constructed by training classifiers
using AdaBoost and then adjusting the threshold to
minimize false negatives."(End of page 4 in the above article)

After that in stage 4, the algorithm uses the threshold from stage 3 to classify the image.

threshold to determine Haar Feature


How to add my action to standard edit tableView button iOS

Question: I have UITableViewController with navigation bar. In viewDidLoad I added edit button:
<code> self.navigationItem.rightBarButtonItem = self.editButtonItem()
</code>
How can I show dialog before edit mode enabled? In what place can I do it?
Comment: You can use delegate methods after setting your controller delegate of UITableView. Delegate methods are mentioned here https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/index.html#//apple_ref/occ/intfm/UITableViewDelegate/tableView:willBeginEditingRowAtIndexPath:
Answer: you can use the method
<code>- (void)setEditing:(BOOL)editing animated:(BOOL)animated</code>
 This method will be called when you click on edit button. Now you can put your functionality inside this method.


How to resolve integer overflow?

Question: I have created a matrix (matA) of 1000 rows and 1000 columns, and I want to calculate powers of this matrix. It works very well up to calculating the third power of the matrix. But when I ask to calculate its fourth power, it gives a warning message saying,

In matA * matA * matA * matA : NAs produced by integer overflow

How can I resolve this problem?
Comment: You want elemetwise power or matrix power as in t(mat)%*%mat?
Comment: Convert the integer to numeric?
Comment: Need the matrix power. I tried numeric conversion. but it gives the same warning.
Answer: Since you didn't give an example:
set.seed(101)
z <- matrix(rnorm(1e6),1e3)
z2 <- round(z)*1000000
storage.mode(z2) <- "integer"

If you really want a matrix power (as in z2 %*% z2 %*% z2 %*% z2), it's best to use the Matrix or expm package.
library(expm)
z4C <- z2 %^% 4

On the other hand, if you really want the elementwise product
z4D <- z2*z2*z2*z2
## Warning message "NAs produced"

All you need to do is convert to numeric.
storage.mode(z2) <- "numeric"
z4E <- z2*z2*z2*z2  ## fine

How to resolve integer overflow?


For a set $B\subset [0,1]$, how to show that If $\nu(B)=0$, then $\mu(B)=0$?

Question: Define two measures on the real line as
$$
\mu(A)=\int_A 1_{[0,1]}(x)dx
$$
and
$$
\nu(A)=\int_A x^2 1_{[0,1]}(x)dx
$$
for all Borel sets $A$. Show that $\mu$  and $\nu$  are equivalent.

For all sets $A$ outside $[0,1]$, we have $\mu(A)=\mu(A)=0$. But for a set $B\subset [0,1]$, how to show that $\mu(B)=0$, then $\nu(B)=0$? Also, how to show the converse statement? If $\nu(B)=0$, then $\mu(B)=0$?
Comment: Have you tried establishing an analogue of the Cauchy-Schwarz inequality?
Comment: In one direction, you can show one measure is always greater than or equal to the other.
Comment: @leslietownes How to use this inequality? Can you give details? Thanks.
Answer: If $\lambda$ is the Lebesgue measure then $\mu(A)=\lambda(A\cap[0,1])$. Thus $\mu(B)=0$ means that $B$ is of Lebesgue measure zero on $[0,1]$ and thus the integral for $\nu(B)$ should be zero no matter what your integrand is.
Comment: @Hermi If $B$ has positive measure, it contains a compact subset also of positive measure. Now on this compact set $x^2$ has its minimum $m$, which is positive. Thus the integral is larger than $m\mu(B)>0$.
Comment: Why $\nu(B)=0$ for a Leb null set $B$?
Comment: How about the inverse statement? If $\nu(B)=0$, then $\mu(B)=0$?
Comment: @Hermi The inverse is basically that since $x^2$ is positive a.e. if you get $\mu(B)>0$ then the integral of $x^2$ over $B$ must be positive, which is a contradiction. For your first question you can eg. note that $\nu(B)\leq \int_B 1dx=\lambda(B)=0$.
Comment: Sorry, I am still confused about the second question. If $\nu(B)=0$, then $\int_B x^2 1_{[0,1]}dx=0$. If $\mu(B)=\int_B 1dx>0$, why $\int_B x^2 1_{[0,1]}dx>0$?


Why wont this command work in minecraft pe 1.1

Question: Why wont this command work
<code>/execute @e[type=arrow.skeleton] ~ ~ ~ tp @p @e[type=arrow.skeleton]
</code>
It's in a repeating command block
Answer: This is because the entity name in the selector (@e/p/r/a) is wrong. There is no arrow.skeleton, just arrow.
Apart from that, this command can be simplified by taking away the entire execute portion. I'd also recommend entering a range. You can even use execute to move the range to the player, and the commandblock should be in the world spawn.
Command without anything:
<code>/tp @p @e[type=arrow]
</code>
Command with range
<code>/tp @p @e[type=arrow,r=100]
</code>
Command with relative range:
<code>/execute @p ~ ~ ~ /tp @p @e[type=arrow,r=100]
</code>
To set the world spawn to the place where the command block is (to make sure it's always running also when you walk far away from it:
<code>/setworldspawn
</code>
<-- Greetings -->


Stolen 3ds before Nintendo ID update: can I get my games back?

Question: Maybe this is a bit late, but is there any way to get my old purchased games back? My 3ds was stolen in 2012, and had purchased some eShop games on it. Only the 3ds itself was stolen, not the box/charger/manual.
Comment: [This thread](https://www.reddit.com/r/3DS/comments/1d9e6n/if_you_ever_get_your_3ds_stolen_heres_what_to_do/) may be helpful, but given this incident it 2 years old, you may have issues.  Either way, you should contact [Nintendo Customer Service](https://www.nintendo.com/consumer/index.jsp)
Answer: If I am correct, the only way would be to make sure the account that you have for eShop is on the new one that you have. If not, contact the support team, explain what happened, and hope for the best.


File Extension in Matlab

Question: Is there any way to get extension of a file from its filename ??
The only algo I could develop to do the above task is to find last '.' and rest all string to end..
But not too sure how to get index of final '.' from the given string..
Any new idea or suggestion for the same ??
I'm actually trying to develop a filter which only does processing on all image files rather than other non image file... Is there any other way of doing the same using any inbuilt function ???
Answer: Use the built in function "fileparts".
Answer: You can use the regexp function with the split parameter
output = regexp(your_string, '\.', 'split')

The output is a cell array that you can pull the value you want out of.
http://www.mathworks.com/help/techdoc/ref/regexp.html
Comment: A '.' matches any character in a regexp. You need to escape it as '\.'.

File Extension in Matlab


pass parameter to taskkill() in matlab?

Question: Suppos there are many matlab.exe running on a windows PC, I am trying to terminate all of them, except the one I am working on. I did the following:
curPID = feature('getpid')
%say curPID return 10000.
%then follow:
system('taskkill /F /FI "PID ne 10000" /IM matlab.EXE');
%the above works fine.

But since every time, when I run
curPID = feature('getpid')

in different matlab GUI or m-file, the value of curPID will change, so I tried to pass curPID to the system() function as below:
system('taskkill /F /FI "PID ne curPID"/IM matlab.EXE');
% or
system('taskkill /F /FI "PID ne str2num(curPID)"/IM matlab.EXE');

but they do not work.
How can I pass curPID to taskkill?
Answer: You can use sprintf to format your call to sys:
curPID = feature('getpid');
syscall = sprintf('taskkill /F /FI "PID ne %u" /IM matlab.EXE', curPID);
system(syscall);

Comment: Thanks! This works. By the way, what is the equivalent on a Linux cluster?
Comment: @XAM I don't know. Probably a better question for SuperUser, not SO.

pass parameter to taskkill() in matlab?


VS 2010 Database Project - Different Connections

Question: I have an application that I'm developing in Visual Studio 2010 that utilizes a SQL Server database.  As such, I am using a VS SQL Server 2008 Database Project.
The database project requires a target connection for which is used to build the database.
Problem:
This project is under source control for a team of developers and a build server.  Some of the developers have their '08 SQL Server instance named whereas others have a default instance.  The idea of just using 'local' syntax will not suffice.
I need the ability to configure the database project connection outside of source control.  I see that the database project offers a SQL command variables files, is this what I'm after?
What is the best practice approach on accommodating this problem?
I'm using MSBuild as part of my build server - how might this approach fit in with MSBuild?
Answer: The Visual Studio 2010 database project properties "Deploy" tab contains a drop down labeled "Configure deployment settings for:".  This drop down supplies two options "My project settings" and "My isolated development environment".  This setting allows
for isolation between your local development settings and the project settings which will be persisted to the .dbproj file.
In you scenario clearing the "Target connection" currently assigned to "My project Settings" followed by submission to repository will relieve the shared connection setting.
You could also clear the "Target database name:" setting leaving the build process in control of specifying the value for it.  Once this is done developers are free to select "My isolated development environment" and configure connection
settings without them being committed to the repository, but deploying therein.
The build process would then take control by doing something like the following:
msbuild.exe {projectName}.dbproj /target:Deploy /property:TargetDatabase={targetDatabaseName};TargetConnectionString="{targetConnectionString}"
Optionally you may opt to remove the "TargetDatabase" property favoring the project to supply this value.
Comment: The "My isolated development environment" saves to {projectName}.dbproj.user.
Answer: You can setup an alias for any instance of your SQL Server. That way everyone can target 'Alias' instead of just 'local'.
You can find some information on how to configure the alias here:
https://serverfault.com/questions/60738/how-to-create-an-alias-for-a-named-sql-server-instance
Comment: Live and learn, that had passed me by - very useful info, thanks
Comment: Interesting answer - I hadn't thought of this.  If I'm unable to get a clear response back regarding the SQL Command variables file, I may take this approach.


Equivalence of two statements regarding distributive lattices

Question: I've two statements.

$(i)$   A lattice L is distributive if and only if it has
no sublattice isomorphic to $M_3$ and $N_5$
$(ii)$   L is distributive if and only if $z ∧ x = z ∧ y$ and $z ∨ x = z ∨ y$ imply that $x = y$.

Why are these two statements equivalent?
Comment: They're equivalent because they're both true. If two sentences have the same logical value, then they're equivalent. If you want a proof of each of those two equivalences, that's something else.
Comment: if they are said to be equivalent, then obviously they are. my question is how they are equivalent.
Comment: The statements are equivalences. Equivalences are either true or false. If they're both true or both false, then they are equivalent. You asked how are these equivalent, not why are these true, which would be to prove each of the statements.
Comment: ok... edited.. thanks @amrsa
Comment: Again, do you really want to know why two true statements are equivalent? That's rather obvious. Perhaps you'd like to know why are they true, instead?
Comment: I want to know why these two statements are equivalent. Meaning I want a proof that each implies the other.
Answer: First, consider to prove, or check some known proof, of the first statement.
You can find it (among many other places) in this book, Theorem 3.6, in the first chapter.
Now, you can easily find elements both in $N_5$ and in $M_3$ which violate that implication (you don't have to search much since they only have five elements each).
For the converse, it will be enough to prove that for every distributive lattice $L$, if for every $a,b,c \in L$, we have $a \wedge b = a \wedge c$ and $a \vee b = a \vee c$, then we also have that $b = c$.
Now, under the conditions,
\begin{align}
b
&= b \wedge (a \vee b)\\
&= b \wedge (a \vee c)\\
&= (a \wedge b) \vee (b \wedge c)\\
&= (a \wedge c) \vee (b \wedge c)\\
&= (a \vee b) \wedge c\\
&= (a \vee c) \wedge c\\
&= c,
\end{align}
where I suppose you can justify each step.
Comment: this book is really helpful. thanks...


Improving Performance of SQL Server Query - Static Values in Filter vs Joining to Other Table for Values

Question: I have very simple logic to extract data from two tables, actually two views in SQL Server.
One way of doing this is (#1 to extract specific ID values from table A; #2 to take those values from query 1 and query for records having those same IDs from table B).  When i do this, it takes less than a second for query #1 to complete, and less than 3 seconds for query #2 to complete)
The preferred way is to either join the two tables above, or have the first table look in the second table via SQL (i.e. select * from table B where ID in (select ID from table A where .....).  This preferred way takes too long - let's say over 5 minutes, and it's not acceptable.
I have read only access.  Is there another way to get the preferred way to run and complete in a reasonable amount of time?
Tried joining two tables, tried setting second query as the filter to the first query
Comment: Is the database read only, or just your access? If the latter, then talk to your DBA; it's their job to performance time and they can help you write *good* queries. If the former is it a replica? If so, then perhaps you should ensure your using SQL Server 2022, which now has Query Store available on read-only replicas.
Comment: It's very hard to answer this type of question without at a minimum: the query, the table *and index* definitions, and please share the query plan via https://pastetheplan.com. This question is not answerable otherwise
Comment: Do you have access to create a stored procedure - if not, do you have access to the source code for both views?  I would recommend getting that source code and seeing if it is possible to write a single query to pull the data as needed instead of relying on joining two separate views.
Answer: You can try your query that way:
<code>select *
from table B
where
    exists (
        select 1
          from A
         where A.ID = B.ID
    )
</code>
But all attempts here are not more than guessing.
Query "speed" depends heavily on DBMS, its optimization, table structure, indexes and so on.
Go to you DBA, ask them to get query plan and help you optimize it.


How to forward internet from mobile modem into router

Question: I had problem after I bought huawei E3372, because I tried to connect it with my openWRT based router and openWRT didn't support it in standard. I tried to install vendor drivers but on my primitive router there wasn't enough space to install them. So I was thinking about scenario to forward internet from my laptop by eth0 interface to my router (to connect openWRT to internet and made operation in internet (share file, mount file disc etc) On My Laptop modem works and I have internet access
So my question is how to achieve this connection:
<code> MobileModeb(USB saw as wired connection) -> Laptop ->(ethernet cable) -> Linux Router
</code>
Is this bridge or IP forwarding? Or something different?
I'm sorry but I am noob in internet administration issues.
Answer: It's IP forwarding, you can implement that with a couple of commands:
In the file /etc/sysctl.conf, add or uncomment the following line using your preferred text editor (vim, gedit, etc):

net.ipv4.ip_forward = 1

To enable the changes in sysctl.conf you need to run the command:

sudo sysctl -p /etc/sysctl.conf

You may also want to configure IPTables with the commands:

sudo iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
sudo iptables -A FORWARD -i eth1 -o eth0 -m state -–state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT

Substitute eth1 by your internet interface (the modem, as called in your system) and substitute eth0 by the interface connected to the router (probably it's really eth0).
To make it permanent, run:

sudo iptables-save > /etc/iptables.rules

Try that and report back any problems.
Comment: after type Your command everything pass but when I connect second laptop by ethernet cable i didn't have internet connection or even ip address. The same is with my router I didn't have internet access
Comment: Have you connected the first Laptop (with the Modem) to the "WAN" port of your router? You should do so and, on the router, configure the WAN port to fixed IP address and give it an address in the same network of the cable port of the first notebook (eg. 192.168.10.1 for laptop and 192.168.10.2 for router, netmask 255.255.255.0), and also set the default gateway in the router to laptop IP, if available.
Comment: My ruter, and in example other laptop didn't get IP-address after calbe connection inside port I dont know maybe dhcp  addresses didn't work fine for me


SQL How to compare DateTime to minutes

Question: I have two different set of DateTime in database.
How do i select time to minutes. I want to select User if his InTime and OutTime is same up to minutes and NOT seconds. So in this case it should select User1 and User2. . The seconds are ignored. How to create such SQL query?
Table: DailyTimeAttendance

User: 1
InTime: 2018-01-01 05:01:07
OutTime: 2018-01-01 05:01:05

User: 2
InTime: 2018-01-01 02:02:04
OutTime: 2018-01-01 02:02:09

User: 3
InTime: 2018-01-01 09:04:05
OutTime: 2018-01-01 09:06:10

Expected Output SQL:
User1 InTime 2018-01-01 00:01 compared to OutTime 2018-01-01 00:01 is TRUE

Comment: Which dbms are you using? (You've got some product specific answers. Don't waste people's time writing answers for "wrong" dbms.)
Answer: You can use DATEDIFF functions if you are using the Microsoft SQL Server, This function returns the count (as a signed integer value) of the specified datepart boundaries crossed between the specified startdate and enddate.  EXAMPLE (if are in same minute)
SELECT * FROM DailyTimeAttendance
WHERE DATEDIFF(MINUTE,InTime,OutTime)=0

Answer: In mysql:
select User, Intime, OutTime,
case when date_format(Intime, '%Y-%m-%d %k:%i') = date_format(OutTime, '%Y-%m-%d %k:%i')
then 'TRUE' else 'FALSE' end
from DailyTimeAttendance

Answer: This should serve your purpose.
select * from
DailyTimeAttendance where
 CONVERT(DATE_FORMAT(InTime,'%Y-%m-%d-%H:%i:00'), DATETIME) =
 CONVERT(DATE_FORMAT(OutTime,'%Y-%m-%d-%H:%i:00'), DATETIME)

Comment: Product specific answer to a question with no dbms specified. At least tell us which dbms this is for.

SQL How to compare DateTime to minutes


Suggestions for open source aspect-oriented library for c#

Question: Any suggestions for open source aspect-oriented library for c#. Thanks
Answer: Post Sharp
Comment: unfortunately Post Sharp is not FOSS
Answer: Spring.NET
Comment: Abandoned by now. Don't waste your time like I did.
Answer: I am using Castle Windsor and Dynamic Proxy, which together provide a simple way to apply your standard AOP method interception through external XML configuration.
If you have more advanced AOP needs, Aspect# might be useful (also relies on Dynamic Proxy) - but I have found that Windsor fulfills my needs perfectly.
Please note that Dynamic Proxy provides only runtime AOP. There are solutions out there that can mix in your aspects at compile time (although I can't recall the name of any of them).
Comment: +1 DynamicProxy, but Aspect# is dead
Answer: DynamicProxy from CastleProject is probably the most lightweight and powerful solution regarding dynamic interception.
Answer: I would suggest Spring.NET as well, but only because that's the only one I have experience with.  Spring.NET offers so much more (IoC, transaction management, nice validation framework) but you can use just what you need from it.
Answer: Spring.NET is great in general, and so is its AOP support.
No idea why people are saying to avoid it. Infact it is one of the most stable and reliable frameworks in the .NET world.
Dev progress is slow, but that is fine because it is already feature rich and stable.


Average and standard deviation equation system

Question:
Every exam has 100 points. Student's average of 3 exams is 88 points and standard deviation is 3. How many points should he get on fourth and fifth exam so that average is 90 and standard deviation stays same (=3).

I tried solving equations $(x_1+x_2+x_3)/3=88$ and $(x_1+x_2+x_3+x_4+x_5)/5=90$. Since $x_1+x_2+x_3=264$ it means that $(264+x_4+x_5)/5=90$ so $x_4+x_5=186$. Then I tried to use equations for standard deviation but I haven't managed to get anything useful.
Comment: What if I told you there is no solution?
Comment: How to proof that?
Comment: See my answer.${}$
Comment: Is the std defined by the population or sample formula ?
Comment: I think by the population
Answer: We have
$$\sqrt{\frac{(x_1-88)^2+(x_2-88)^2+(x_3-88)^2}3}=3$$
$$(x_1-88)^2+(x_2-88)^2+(x_3-88)^2=27$$
How do we get from $(x-88)^2=x^2-176x+88^2$ to $(x-90)^2=x^2-180x+90^2$? We add $-4x+356$.
$$-4x_1+356-4x_2+356-4x_3+356=-4(x_1+x_2+x_3)+1068=-4(3\cdot88)+1068=12$$
$$(x_1-90)^2+(x_2-90)^2+(x_3-90)^2=27+12=39$$
Now
$$\sqrt{\frac{39+(x_4-90)^2+(x_5-90)^2}5}=3$$
$$(x_4-90)^2+(x_5-90)^2=6$$
Let $z_4=x_4-90$ and $z_5=x_5-90$. Then $z_4+z_5=6$ while $z_4^2+z_5^2=6$. Squaring the first equation and subtracting the second from it and halving gives $z_4z_5=15$.
Thus we may form the polynomial $x^2-6x+15$, whose roots should be $z_4$ and $z_5$. However, we find that the polynomial has no real roots. So there is no solution to the original problem – the average and standard deviation cannot be changed by the further two tests to the given values.
Answer: From the averages,
$$x_4+x_5=5\cdot 90-3\cdot 88=186$$
and from the variances,
$$x_4^2+x_5^2=5(3^2+90^2)-3(3^2+88^2)=17286.$$
Then
$$(x_4-x_5)^2=2(x_4^2+x_5^2)-(x_4+x_5)^2=-24.$$ (!)


Can I get the index of an inserted node in a treeview?

Question: In my treeview I want to remember which nodes were expanded and redraw that state after I delete or insert a node. I solved that with remembering the index of an expanded node. If a node is removed, I decrement all indeces that were afterwards.
That works because I can access the deleted node with treeView.SelectedNode, but how can I get the new Index of the inserted node?
I can not solve it with saving a reference to the node or a name or a tag, because when I redraw the tree the nodes are created completely new - and I think I can not get a reference to the newly created node anyway
Best regards, Expecto
Answer: My way: use your own declared class:
class TreeNodeEx : TreeNode
{
    public void Remove()
    {
        base.Remove();
        // what you want to do
        UpdateNode(this.Parent);
    }
}

Answer: You could bind an observableCollection to your TreeNode Then :
        var obd =  Observable.FromEvent<NotifyCollectionChangedEventArgs>(
            ev => obdCollection.CollectionChanged += CheckChanges,ev=> obdCollection.CollectionChanged -= CheckChanges);

   private void CheckChanges(object sender, NotifyCollectionChangedEventArgs e)
    {
        Console.WriteLine("new Starting index : "+e.NewStartingIndex);
        Console.WriteLine("Old Starting index : " + e.OldStartingIndex);
        Console.WriteLine("new Items : " + e.NewItems);
        Console.WriteLine("Old Items : " + e.OldItems);

    }

That way you can check what has changed in the collection.
Answer: The answers were not really what I was looking for, but after I found out that after an insert the "AfterSelect" Event fires, I did it this way:
private void treeViewProduct_AfterSelect(object sender, TreeViewEventArgs e)
    {

        if (insertMode)
        {

            treeViewProduct.NotifyAboutInsert(e.Node.Index);
        }
...
}

My treeview then handles the changed indices for the nodes after that and perfectly redraws the tree.


Simple example to apply the SLLN

Question: I'm trying to find concrete examples of the SLLN theorem. Before, let's see the statement of this theorem precisely from this book, page 81:

Definition: We say that $X_n$ converges almost surely to $X$, written $X_n\xrightarrow{a.s.} X$, if
$$\mathbb{P}(\{s:X_n(s)\to X(s)\})=1$$
Theorem (The Strong Law of Large Numbers). Let $X_1,\ldots X_n$ be IID. If $\mu=\mathbb E|X_1|\lt \infty$ then
$$\bar X_n\xrightarrow{a.s.}\mu$$

I'm thinking about for example the $X\sim Bern(1/2)$, such as the coin experiment where we can define as $X(T)=0$ and $X(H)=1$.
The way I understand the theorem is it states for every $s$ in the outcome from the experiment (except the ones with $P(s)=0$), we have $\bar X_n(s)\to \mu$.
I can't see this in my example. Let's start with $s=H$. Since we already know $\mu =1/2$, we have:
$$\bar X_n(H)=\frac{X_1(H)+\ldots+X_n(H)}{n}=\frac{1+\ldots+1}{n}=1\nrightarrow 1/2$$
as $n$ goes to infinity.
Where am I wrong?
Comment: The event of getting all Heads in an infinite number of i.i.d tosses has probability $0$. So what you proved does not contradict SLLN.
Comment: @KaviRamaMurthy yes, but first I'm taking a finite number $n$ of heads and only after I will take $n$ to go to infinity. It's different, no?
Comment: @user42912 : if you take $n=10$ the probability of getting 10 H is $\frac{1}{2^{10}}\approx 0$
Comment: @tommik could you give me an example that works in this context?
Comment: @tommik another question, following the statement of the theorem, aren't there only two possible situations? for $s=H$ and $s=T$, both with probability 0 as $n\rightarrow \infty$?
Comment: I think the logical modifiers may be mixed up in your interpretation. You say that theorem "states for every $s$ in the outcome from the experiment (except the ones with $P(s)=0$), we have $\bar{X}_n(s)\rightarrow \mu$." My interpretation of the theorem is that for all the outcomes $s$ such that $X_n(s) \rightarrow \mu = 1/2$, the probability of getting such an outcome is one. The sample space being used is already the one on infinite draws, and the $\bar{X}_n(s)$ are using information from the first $n$ of them.
Comment: You're thinking of $s$ as being a single outcome for a single toss of a coin. The $s$ here is the outcome of infinite tosses.
Comment: @YacoubKureh I see, this is not clear at all for me from the statement of the theorem
Comment: @user42912 I definitely agree it's not clear or obvious as written...the book you're citing is horrificly terse! I hope it's clear now though :)
Comment: @YacoubKureh let me see, if I got it. We cannot take an specific example as I did, because it's gonna have probability $0$. The $s$ there it's a random event with infinite outcomes in this case, as you said, infinite draws in a coin. Thank you very much to help me
Answer: Given that the proof of SLLN is well known and you can find it in a lot of books (Here, for example, you can find a very basic proof) I would like to make you think about an intuitive reasoning:
SLLN in your example can be stated in the following way: For $n$ large, calculate the following probability
$$\mathbb{P}\Bigg[\lim\limits_{n}\overline{X}_n=\frac{1}{2}\Bigg]=?$$
Say: toss the fair coin $10,000,000$ times: what is the probability you observe a numbers of H $\rightarrow 5,000,000$?
...I think it is intuitive that this probability is 1.
SLLN provides a proof of this intuition

Simple example to apply the SLLN


Set Variable In a Pentaho Loop

Question: I tried looking at this: loop-for-pentaho-where-i-redefine-a-variable-on-each-execution, but it's not exactly what I need.
I am using an API to grab results, but I can only grab 100 records at a time. No big deal, I can set the "after" query parameter.
What I need to do is something like this:

Start
Run transformation that Runs API Initially and grabs the last ID value
Run Transformation again but set the "after" query parameter based on the variable in the previous run.
If the variable is NULL then move to the next part of the job, if it's not, loop through and run part 3 again.

Any suggestions?
Answer: Figured out how to do this. There might be a better way to do this, but this worked for me.
Here is how I accomplished this:

Create a job.
This job will have start -> transformation -> transformation.
In the 2nd transformation, choose to "Execute every input row" on the "transformation options" menu that is accessible by double clicking on the transformation step.
Create a sql table that has 1 row and 1 column in it. This value will be our variable.
In your transformation, use this value from the table if you want.
At the end of your 2nd transformation, update this value.
When the transformation runs again, it will use the updated value from the table.
This is how you can use changing "variables" in your transformation.

Set Variable In a Pentaho Loop


"Access denied" error when trying to enumerate drives on remote computers

Question: I am trying to run a PowerShell command to get the total disk space of all drives for all our remote servers. When I run the command I am getting the error below. I have a text file which has names of the servers and I have also confirmed that WinRM is configured and is running.
<code>$Servers = Get-Content "C:\users\anorris\desktop\DR\servers1.txt"
foreach ($s in $Servers) {
  Invoke-Command -ComputerName $s {Get-PSDrive}
}
</code>
Error:
[ahv-a2acortst02] Connecting to remote server failed with the following error
message : Access is denied.
For more information, see the about_Remote_Troubleshooting Help topic.
        + CategoryInfo          : OpenError: (:) [], PSRemotingTransportException
        + FullyQualifiedErrorId : PSSessionStateBroken
Comment: The error message looks straight forward. You don't, or the process doesn't, have rights to access the drives. Have you looked into that?
Comment: The error specifically mentions the [`about_Remote_Troubleshooting`](https://technet.microsoft.com/en-us/library/hh847850.aspx) help topic. Did you look into that? What were your findings?
Answer: Agreed that the message 'Access is denied' is a dead giveaway that you don't have access.
I would create a credential variable and make sure it is a credential that has rights to the remote system.
$Creds = Get-Credential
then change your code to the following (I added the -scriptblock and the bolded text
$Servers = Get-Content "C:\users\anorris\desktop\DR\servers1.txt"
foreach ($s in $Servers) {
  Invoke-Command -ComputerName $s -ScriptBlock {Get-PSDrive} -Credential $creds
}


tkinter splash screen code doesn't show image

Question: I'm trying to show a splash screen image when i start my program. It appears to import the size of the splash screen image but not actually show the image of the splash screen. I've tried using the image in various formats (.png, .gif, .jpeg, etc.) but and a few other sample code blocks i found but i'm thinking its something obvious i'm not seeing considering its importing the size of the image. Appreciate any help you can provide.
import tkinter as tk
from tkinter import *

root = tk.Tk()
root.overrideredirect(True)
width = root.winfo_screenwidth()
height = root.winfo_screenheight()

image_file = 'splash.gif'
image = tk.PhotoImage(rootFolder, file=image_file)

x = int((width / 2) - (image.width() / 2))
y = int((height / 2) - (image.height() / 2))
geometry = '{}x{}+{}+{}'.format(image.width(), image.height(), x, y)

root.geometry(geometry)
canvas = tk.Canvas(root)
canvas.create_image(0,0, image=image, anchor='nw')

root.after(3000, root.destroy)
root.mainloop()

Answer: You have to call pack, place, or grid on the canvas so that it will be visible.


Making master pdf editor default for .pdf files

Question: I have followed the answer posted by Moderator Mitch user 59676 and created mpe.desktop file, right clicked on the file and 'open with other application' - 'show other applications' did not list master PDF editor so unable to make as default.
Answer: Add %f at last  in Exec of Desktop file (and put it in /usr/share/applications). So-that it is available as open-with-other-applications.

If MasterPdfEditor.desktop is placed in /usr/share/applications, then
Open sudo gedit /etc/gnome/defaults.list
And Replace:-
application/pdf=evince.desktop with application/pdf=MasterPdfEditor.desktop
This will set Master Pdf Editor as default for pdf files.
For instance, You can replace all evince.desktop with MasterPdfEditor.desktop by Ctrl+H.


Partial string match between two columns for large dataset R

Question: I have two columns and I want to create a binary column for if there is a partial match between the two columns.
For example:
X             Y        Match
hello         hello     1
hi hello      hi        1
NA            bye       NA
bye           hi bye    1
good          bad       0

I used following code,
df['Match'] <- ifelse(with(df, str_detect(x, y)|str_detect(y, x)), 1, 0)

which worked for the first few rows but when I used it on the whole dataset (n=14000), I keep getting this error:
Error in stri_detect_regex(string, pattern, opts_regex = opts(pattern)) :
Incorrectly nested parentheses in regexp pattern. (U_REGEX_MISMATCHED_PAREN)

How should I go about solving this problem?
Comment: Your example is working fine `with(df, +(str_detect(X, Y)|str_detect(Y, X)))
[1]  1  1 NA  1  0`
Answer: You probably have parentheses in your data or special characters that cause this error.
Try a loop like so:
for(i in 1:nrow(df)) {
  print(i)
  str_detect(df$x[i], df$y[i])
}

the last i printed will tell you which row the problem is in.


Are alternative roofing types, such as rubber roll, usable for a typical residential sloped roof?

Question: I'm wondering specifically, if rubber-roll roofing, such as this can be used on a sloped roof.
Or maybe if there is something akin to the stretch-and-seal tape but in large sheets that would be weather resistant and suitable for roofing applications. That way the seams would be self-sealing.
Essentially I'm wondering about some sort of rubber or silicon roofing that ultimately will turn itself into one single coating, as opposed to typical shingles which have a million seams in them. Can you tar a sloped roof?
Comment: But do note that while shingles have 'seams' they are all overlapped, so shed water just fine. (In other words, the seams have no bearing on their ability to shed water)
Comment: I honestly have done little roof work - other than rip shingles off -  so I won't offer an answer.  But I did see a Holmes on Homes about 2 months ago where they did install "tar rolls" (sorry not sure of the name or brand or even if they were tar) and heat them together to form a seamless roof.  It was a peaked residential roof.  The rolls were ordered based on the measurements of the roof too.
Comment: Hmm, that sounds like it would be perfect. Then you can just melt a layer over the peak too and be done with it. I'll have to look that up.
Comment: They had a cap for the peak.  That is one place you don't have to worry about a seam as long as the cap hangs over.
Comment: I have that over my car port, roofers came in a laid foam down first because it was a flat roof and laid strips down directly over that. Used a heat gun to make the seals. Mine came w/ 10 yr warranty, I'm about 2 yrs in. The foam and rubber are more than though enough for wet leaves to sit on for a few months and my weight when I go to sweep them off. Had a ~1" branch come down and puncture it (which apparently wasn't covered) they wanted a few hundreds buck so I just filled it with silicone.
Comment: Roll roofing, also called double coverage, ends up being a seamless layer.
Comment: Thanks for the tip @Mike, looks like that is primarily for flat or nearly flat roofs though.
Comment: What are you trying to do exactly?  If it has a steep pitch you can put a rubber roof on it but that may be overkill.  Why won't regular shingles work?
Comment: @eldylon - what leads you to say that?
Comment: @mike, just from reading the websites about it. they all seem to refer strictly to flat or nearly flat rooves.
Comment: @fry.pan , i'm just looking for alternatives that might be easier to install, and - not having any seams - theoretically have fewer potential points of failure.
Comment: @eldylon - are your websites saying anything close to 'do not install on sloped roofs'?
Comment: What is your intention to this type of roofing? Are you looking to reduce labor cost, or some other goal?
Answer: I think one could feasibly cover a sloped roof with that stuff, but it would be very odd.  Most HOAs and neighborhood associations would reject it.  You neighbors would be annoyed.  If snow or ice accumulations are possible for the climate, it probably would cause random ice sheet falls, which is not an issue for its intended use on level roofing.
As some comments hint, a properly installed composite roof becomes a single, seamless sheet of roofing.  It only takes one warm day for the shingles to soften and then seal together.  Even before self-sealing, the shingle and seam overlap makes the roof rainproof.
Anyway, the danger of a roof leaking is not the integrity of the initial installation's seams and whatnot.  It is the decades of abuse wrought by the weather (sun, hail, wind, snow), moss, leaves, tree branches, animals pecking or running, maintenance people walking across it, using shovels, picks, rakes, and brooms to clean it, blasting it with a power washer, etc.  Any of those can poke holes, cut slits, move flashing, or lift up edges.  That's the most likely cause of leaks.
Comment: I'm not opposed to this answer but I am also not opposed to a roofing option that comes in large rolls or sections that overlaps a bit too.


Why reference's type is class in Java

Question: In java, Book c =  new Book()
here c is reference. Why reference's type be a class name. What is the special reason.?
Comment: Because a reference is not a long or an int.  But of course, if you declare a String you're declaring a reference.
Comment: (A reference is equivalent to a pointer in C/C++.  It is not the thing itself but rather the address of the thing.)
Comment: because it provides compile time check
Comment: And Java is a strongly typed language, meaning that references must carry the type of the object they represent.
Answer: Book c =  new Book(); // c points to a Book object. Now, if you declare c as an int, it means that c points to an int.

Why reference's type is class in Java


CDI : inject two generics from the same template

Question: My problem is that I cannot inject multiple templates instances from GenericManagerJPA<>.
That's to say that in this code, both projectManager and userManager will contains the same  GenericManagerJPA<User> instance. I don't know why...
@Stateless
public class UserFacadeJPA implements Serializable {

@Inject private GenericManagerJPA<Project> projectManager;
@Inject private GenericManagerJPA<User> userManager;

@PostConstruct
public void init() {
    projectManager.setEntityClass(Project.class);
    userManager.setEntityClass(User.class);
}
....

From this class :
@Dependent
@Stateless
public class GenericManagerJPA<T> implements Serializable {
...

How can I inject differents instances of a generic object with CDI ?
Can you help me about this issue? Thank's a lot.
PS: I have read this thread ( https://community.jboss.org/blogs/scott.stark/2012/08/21/a-generic-producer-method ) that presents how to create it (I think) but I assume it's a bit to complicated to understand for me. So if you have another solution or if you can explain me the principle more clearly...
Answer: What you're running into is an EJB issue, not really a CDI issue.  The problem will go away if you remove @Stateless from the class GenericManagerJPA.  EJB doesn't deal with generics too well, unfortunately.
Comment: To clarify a bit further.  One problem is that you only end up with a single EJB reference created.  CDI is simply looking up that reference and injecting it into the field.  With pure CDI beans, you'll end up with two different injection points (since it doesn't delegate down to the EJB container to find the instance).
Comment: OK, I understand a little what you mean but how can I keep my Stateless annotation because here, my class becomes stateful isn't it ? And it doesn't work without the `@New` annotation between `@Inject` and private... It creates a problem of performance... Is there a pretty way to make that. In all cases, thank's a lot!
Comment: The problem with EJBs (not stateless, stateful, singleton specific) is that they don't deal with generics all that well from a spec standpoint.  They use interfaces to bind.  In CDI, to use generics you need to be dependent scoped.
Comment: Yes but how (with ejb or with cdi) can I use generics and being stateless. Do you have any idea about that? thx.
Comment: So, I finally decide to use the solution that you can find [here](http://stackoverflow.com/questions/11138625/generics-and-cdi-clash)


Input-Output error when reading directory

Question: I have a problem with reading folders/files of a curlftpfs-mounted folder:
The server is using FTPES with explicit TLS/SSL and I have only reading permissions on it.
My system is using Mint15 (Ubuntu 13.04), curlftpfs 0.9.2, libcurl 7.29.0, fuse 2.9
My used command is:
curlftpfs -r -v -o ssl_control,cacert=~/serverzertifikat.pem,no_verify_peer,allow_other,tlsv1 username:firstname.lastname@example.com:990/efz_out ~/mount

This produces the following output:

Couldn't find host hostname.com in the .netrc file; using defaults
  About to connect() to hostname.com port 990 (#0)
     Trying X.X.X.X...
  Connected to hostname.com (X.X.X.X) port 990 (#0)
  SOME HOST INFORMATIONS
  AUTH SSL
  234 Proceed with negotiation.
  error reading ca cert file ~/serverzertifikat.pem (Error while reading file.)
  server certificate verification SKIPPED
  compression: NULL
  cipher: AES-128-CBC
  MAC: SHA1
  USER username
  331 Please specify the password.
  PASS password
  230 Login successful.
  PBSZ 0
  200 PBSZ set to 0.
  PROT C
  200 PROT now Clear.
  PWD
  257 "/"
  Entry path is '/'
  CWD efz_out
  250 Directory successfully changed.
  Remembering we are in dir "efz_out/"
  Connection #0 to host hostname.com left intact

When I now go into my mounted directory and want to list all files with
ls -al

I get the following error message:

ls: reading directory .: Input/output error
  total 0

I already googled a long time and tried a lot of different options, but none of them changed sth.
Maybe one of you has experience with it and can help me?
My opinion is, that the problem has to do with FTPES (I found some post, where other users had the same problem with their servers, but that couldn't help me, because the used the option: no_verify_hostname, which isn't actually no more supported because of security issues)
Answer: We have recently faced the same issue and found out that the passive mode of the FTP server has been disabled. In order to tell curlftpfs to connect in active mode, run with -o ftp_port=- option.
$> curlftpfs -o user=<username>:<password>,ftp_port=- ftp://<FTP_IP> /mnt/ftp.
Comment: Works for me. How do I set that option in the fstab instead than using the command line program ?
Answer: Comment 12 here fixed it for me on RHEL 7
https://bugzilla.redhat.com/show_bug.cgi?id=1183409
Short version, run this first:
export NSS_STRICT_NOFORK=DISABLED


dual boot 14.04 / 17.04 lost grub menu

Question: I had ubuntu14.04LTS running and installed ubuntu 17.04 making a partition. So I got 2 choices at startup. This worked fine until a couple of weeks. I assume after a 14.04 update, the initial menu (grub?) disapeared, and notebook starts directly on 14.04.
I tryed boot-repair with this result: GPT detected. Please create a BIOS-Boot partition (>1MB, unformatted filesystem, bios_grub flag). This can be performed via tools such as Gparted. Then try again. Alternatively, you can retry after activating the [Separate /boot/efi partition:] option.
Things from there are too complicated in forums, I am not an expert, just a user.
Partitions are still there with all the content.
bootinfo from boot-repair: http://paste.ubuntu.com/25575784/
Hope someone can help. Thanks.
Comment: You have installed in UEFI mode (correct) but booted Boot Repair in Legacy (incorrect twice, Boot Repair isn't even for this cases). Now: 1. You can boot either from the UEFI boot settings, probably, or 2. Just do `sudo update-grub` and it should find both again and recreate the boot entries (if you prefer 17.04's Grub to be in charge, then boot it and do the same).
Comment: You have an UEFI system with UEFI installs. But if Boot-Repair is asking for a bios_grub partition then you must have booted the Ubuntu live installer in BIOS mode as that would then want to install a BIOS boot version of grub. Only boot system & any live installer in UEFI mode. Many with Secure Boot have to specifically allow USB boot in UEFI as that is not considered "Secure".  Probably easiest to boot in UEFI mode, add Boot-Repair and in advanced mode do the total reinstall of grub.
Comment: @MichaelBay I did sudo update-grub, many lines about found things, but still boots directly to 14.04
Comment: @oldfred I think I am in UEFI mode now, how can I check that without going to BIOS menu? and boot-repair gives me this "GPT detected. Please create a BIOS-Boot partition" message
Comment: @oldfred  recent bootinfo http://paste.ubuntu.com/25589056/
Comment: I just filed bug report in Boot-Repair. You have UEFI installs, and Boot-Repair says you even have UEFI Secure boot on. Adding bios_grub partition and installing the BIOS boot version of grub will not work. You need UEFI version. If you boot your 14.04 install you can see your /boot/efi/EFI/ubuntu folder. And in it is a 3 line grub.cfg. It will have UUID and partition number of 14.04 install and you should be able to change to UUID & partition for new install. Back up file first just in case you make a typo and have to restore old version.
Comment: @oldfred Thank you. I am sorry not to be capable to follow you. Almost user level new to ubuntu. Maybe I can manage to locate de cfg file but the rest... I can't get what does "change to UUID & partition for new install" mean.
Comment: by the way, I boot 14.04 as it's where it goes and I have no chance.
Comment: Post these in first post and preserve formatting. `cat /boot/efi/EFI/ubuntu/grub.cfg`
Answer: Your grub.cfg should be this:
cat /boot/efi/EFI/ubuntu/grub.cfg
search.fs_uuid 94ce33db-7654-4e3e-a9be-a3063bb155cf root hd0,gpt4
set prefix=($root)'/boot/grub'
configfile $prefix/grub.cfg

You get UUID from this(I got it from the Boot-Repair report).
sudo blkid -c /dev/null -o list

And you want to change first line to UUID of sda4 & gpt4 to gpt6, copy & paste UUID from above command. Orcopy this line & paste. Best to also add # to existing line as first char changing to a comment. Then easier to revert if required.
search.fs_uuid 00aee336-b9ae-4c75-8edc-a19adb0b5451  root hd0,gpt6

sudo nano /boot/efi/EFI/ubuntu/grub.cfg

It should end up like this:
search.fs_uuid 00aee336-b9ae-4c75-8edc-a19adb0b5451  root hd0,gpt6
#search.fs_uuid 94ce33db-7654-4e3e-a9be-a3063bb155cf root hd0,gpt4
set prefix=($root)'/boot/grub'
configfile $prefix/grub.cfg

Comment: how do you copy and paste here terminal lines in their original format?
Comment: 4 spaces make a command & one of the icons will make multiple lines as commands by indenting them the 4 spaces.
Comment: Ok. I will study the procedure and try. Not a simple thing to me.
Comment: should just be a copy & paste. nano is old style editor, you have to use arrow keys to move pointer, but still can copy & paste.
Comment: SOLVED !!!! Thank you @oldfred... if you can, tell me what whe did....
Comment: We just changed which grub.cfg to use. When UEFI boots, then grubx4.efi loads and finds the 3 line grub.cfg in the ESP - efi system partition to find the full grub config in your install. You could have done the same by totally reinstalling grub which would then create a new grub.cfg in the ESP. The configfile is a load another file in another location. If it is working you can accept answer.
Comment: It's working. How can grub be totally reinstalled?
Comment: If it is working, I would not reinstall. But newer users find the advanced mode of Boot-Repair easiest as it walks you thru  it. But you have to always boot live installer in correct mode for your system either always UEFI or always BIOS.

dual boot 14.04 / 17.04 lost grub menu


Issue in spliting data in Txt file while converting from RDD to DataFrame in Spark using Scala

Question: I reading data from a text file as RDD and converting into DataFrame but I am not getting the desired output.
Code -
val myFile = sc.textFile("car.txt")
val df = myFile.map(_.split(" ")).map(line => Text(line(0))).toDF()
df.show()

where Text is the case class
case class-
case class Text(field: String)

Data in the car.txt file -
hyundai honda
honda maruti
maruti honda

Output when executing -
+-------+
|  field|
+-------+
|hyundai|
|  honda|
| maruti|
+-------+

Why am I not getting all the data from the text file in the DataFrame?
Answer: It's because you are splitting the data on spaces and then only outputting the first element of that (first word) -> line(0)
If you just want the lines, then you can cut out the .map(_.split(" ")) and then just use the line (no (0))


Get id product when using dropzone to upload multiple images laravel

Question: I'm a new Laravel.
Now, I want to create product and I'm using dropzone.js to upload multiple images.
I have Product table (name, sku, barcode,price, main_image,...) to store product and Product_images to store images of product.

model_id is idProduct. But I don't know store it when I create a new product
My Routes
Route::post('/products/upload/dropzone', 'ProductController@uploadDropzone')->name('be.upload.dropzone');
Route::post('/products/store', 'ProductController@store')->name('be.product.store');

My Controllers - Upload Images
public function uploadDropzone(Request $request) {
        $image = $request->file('others_image');
        if ($image) {
            $dropzone = new ProductImage;
            $imageName = $image->getClientOriginalName();
            $dropzone->image_name = $imageName;
            $image->move(realpath(public_path('uploads/images/product/product')), $imageName);
            $dropzone->image_path = 'uploads/images/product/product/'.$imageName;
            $dropzone->model = 'Product';
            $dropzone->model_id = ??;

            $dropzone->save();
        }

        return response()->json(['message' => 'Images uploaded successfully!']);
    }

Script Dropzone
Dropzone.autoDiscover = false;
        var myDropzone = new Dropzone("div#dropzone_images", {
            url: "{{ route('be.upload.dropzone') }}",
            sending: function(file, xhr, formData){
                formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
            },
            paramName: 'others_image',
            addRemoveLinks: true,
            acceptedFiles: 'image/*',
            dictRemoveFile: 'Xóa ảnh',
        });

I have saved product information and product images but idProduct did not (model_id).
All comments are respected
Thanks so much!
Comment: upload images and response with the `product_image_ids`, post the product with these id, after create product, update the images' `model_id`
Comment: Thanks TsaiKoga, you can description details for this?
Answer: Using session you can solve this problem.
just put imageId in session then when you create product update that

Controller
 public function uploadDropzone(Request $request) {
            $image = $request->file('others_image');
            if ($image) {
                $imageName = $image->getClientOriginalName();
                $image->move(realpath(public_path('uploads/images/product/product')), $imageName);
                $path = 'uploads/images/product/product/'.$imageName;

                $productImage = ProductImage::create([
                    'model' => 'Product',
                    'image_name' => $imageName,
                    'image_path' => $path
                ]);

                $request->session()->put('imageId', $productImage->id);
            }
            return response()->json(['message' => 'Images uploaded successfully!']);
        }

now in create.blade.php
 $productImageId = session()->get('imageId');

        $productImage = ProductImage::find($productImageId);

        $productImage->update([
            'model_id' => $id
        ]);

session()->forget('imageId');

https://laravel.com/docs/6.x/session
Comment: Thanks, Paul. But error: `Undefined variable: productId`. Any solution?
Comment: $productId u have to put based upon you product page ^_^ . check somewhere you may print product name or description on that page simillar you have to print product id
Comment: In my blade: `create.blade.php` ?
Comment: i thoght it's in edit.blade.php . do one thing whenever you are uploding image add an array in seesion that will contain ids of ProductImage then creating product update all model_id
Comment: Thanks, Paul, but error `Call to a member function update() on null`. Sorry, because I'm a new Laravel :(
Comment: @HoangDinh check some tutorial about update delete and create