text:
Q: How to dynamically do filtering in Java 8? I know in Java 8, I can do filtering like this :
List<User> olderUsers = users.stream().filter(u -> u.age > 30).collect(Collectors.toList());

But what if I have a collection and half a dozen filtering criteria, and I want to test the combination of the criteria ?
For example I have a collection of objects and the following criteria :
<1> Size
<2> Weight
<3> Length
<4> Top 50% by a certain order
<5> Top 20% by a another certain ratio
<6> True or false by yet another criteria

And I want to test the combination of the above criteria, something like :
<1> -> <2> -> <3> -> <4> -> <5>
<1> -> <2> -> <3> -> <5> -> <4>
<1> -> <2> -> <5> -> <4> -> <3>
...
<1> -> <5> -> <3> -> <4> -> <2>
<3> -> <2> -> <1> -> <4> -> <5>
...
<5> -> <4> -> <3> -> <3> -> <1>

If each testing order may give me different results, how to write a loop to automatically filter through all the combinations ?
What I can think of is to use another method that generates the testing order like the following :
int[][] getTestOrder(int criteriaCount)
{
 ...
}

So if the criteriaCount is 2, it will return : {{1,2},{2,1}}
If the criteriaCount is 3, it will return : {{1,2,3},{1,3,2},{2,1,3},{2,3,1},{3,1,2},{3,2,1}}
...

But then how to most efficiently implement it with the filtering mechanism in concise expressions that comes with Java 8 ?

A: We could add a counter with a map so we know how many elements we have after the filters. I created a helper class that has a method that counts and returns the same object passed:
class DoNothingButCount<T> {
    AtomicInteger i;
    public DoNothingButCount() {
        i = new AtomicInteger(0);
    }
    public T pass(T p) {
        i.incrementAndGet();
        return p;
    }
}

public void runDemo() {
    List<Person>persons = create(100);
    DoNothingButCount<Person> counter = new DoNothingButCount<>();

    persons.stream().filter(u -> u.size > 12).filter(u -> u.weitght > 12).
            map((p) -> counter.pass(p)).
            sorted((p1, p2) -> p1.age - p2.age).
            collect(Collectors.toList()).stream().
            limit((int) (counter.i.intValue() * 0.5)).
            sorted((p1, p2) -> p2.length - p1.length).
            limit((int) (counter.i.intValue() * 0.5 * 0.2)).forEach((p) -> System.out.println(p));
}

I had to convert the stream to list and back to stream in the middle because the limit would use the initial count otherwise. Is all a but "hackish" but is all I could think.
I could do it a bit differently using  a Function for my mapped class:
class DoNothingButCount<T > implements Function<T, T> {
    AtomicInteger i;
    public DoNothingButCount() {
        i = new AtomicInteger(0);
    }
    public T apply(T p) {
        i.incrementAndGet();
        return p;
    }
}

The only thing will change in the stream is:
            map((p) -> counter.pass(p)).

will become:
            map(counter).

My complete test class including the two examples:
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Demo2 {
    Random r = new Random();
    class Person {
        public int size, weitght,length, age;
        public Person(int s, int w, int l, int a){
            this.size = s;
            this.weitght = w;
            this.length = l;
            this.age = a;
        }
        public String toString() {
            return "P: "+this.size+", "+this.weitght+", "+this.length+", "+this.age+".";
        }
    }

    public List<Person>create(int size) {
        List<Person>persons = new ArrayList<>();
        while(persons.size()<size) {
            persons.add(new Person(r.nextInt(10)+10, r.nextInt(10)+10, r.nextInt(10)+10,r.nextInt(20)+14));
        }
        return persons;
    }

    class DoNothingButCount<T> {
        AtomicInteger i;
        public DoNothingButCount() {
            i = new AtomicInteger(0);
        }
        public T pass(T p) {
            i.incrementAndGet();
            return p;
        }
    }

    class PDoNothingButCount<T > implements Function<T, T> {
        AtomicInteger i;
        public PDoNothingButCount() {
            i = new AtomicInteger(0);
        }
        public T apply(T p) {
            i.incrementAndGet();
            return p;
        }
    }

    public void runDemo() {
        List<Person>persons = create(100);
        PDoNothingButCount<Person> counter = new PDoNothingButCount<>();

        persons.stream().filter(u -> u.size > 12).filter(u -> u.weitght > 12).
                map(counter).
                sorted((p1, p2) -> p1.age - p2.age).
                collect(Collectors.toList()).stream().
                limit((int) (counter.i.intValue() * 0.5)).
                sorted((p1, p2) -> p2.length - p1.length).
                limit((int) (counter.i.intValue() * 0.5 * 0.2)).forEach((p) -> System.out.println(p));
    }

    public void runDemo2() {
        List<Person>persons = create(100);
        DoNothingButCount<Person> counter = new DoNothingButCount<>();

        persons.stream().filter(u -> u.size > 12).filter(u -> u.weitght > 12).
                map((p) -> counter.pass(p)).
                sorted((p1, p2) -> p1.age - p2.age).
                collect(Collectors.toList()).stream().
                limit((int) (counter.i.intValue() * 0.5)).
                sorted((p1, p2) -> p2.length - p1.length).
                limit((int) (counter.i.intValue() * 0.5 * 0.2)).forEach((p) -> System.out.println(p));
    }

    public static void main(String str[]) {
        Demo2 demo = new Demo2();
        System.out.println("Demo 2:");
        demo.runDemo2();
        System.out.println("Demo 1:");
        demo.runDemo();

    }
}

A: Interesting problem. There are several things going on here. No doubt this could be solved in less than half a page of Haskell or Lisp, but this is Java, so here we go....
One issue is that we have a variable number of filters, whereas most of the examples that have been shown illustrate fixed pipelines.
Another issue is that some of the OP's "filters" are context sensitive, such as "top 50% by a certain order". This can't be done with a simple filter(predicate) construct on a stream.
The key is to realize that, while lambdas allow functions to be passed as arguments (to good effect) it also means that they can be stored in data structures and computations can be performed on them. The most common computation is to take multiple functions and compose them.
Assume that the values being operated on are instances of Widget, which is a POJO that has some obvious getters:
class Widget {
    String name() { ... }
    int length() { ... }
    double weight() { ... }

    // constructors, fields, toString(), etc.
}

Let's start off with the first issue and figure out how to operate with a variable number of simple predicates. We can create a list of predicates like this:
List<Predicate<Widget>> allPredicates = Arrays.asList(
    w -> w.length() >= 10,
    w -> w.weight() > 40.0,
    w -> w.name().compareTo("c") > 0);

Given this list, we can permute them (probably not useful, since they're order independent) or select any subset we want. Let's say we just want to apply all of them. How do we apply a variable number of predicates to a stream? There is a Predicate.and() method that will take two predicates and combine them using a logical and, returning a single predicate. So we could take the first predicate and write a loop that combines it with the successive predicates to build up a single predicate that's a composite and of them all:
Predicate<Widget> compositePredicate = allPredicates.get(0);
for (int i = 1; i < allPredicates.size(); i++) {
    compositePredicate = compositePredicate.and(allPredicates.get(i));
}

This works, but it fails if the list is empty, and since we're doing functional programming now, mutating a variable in a loop is declassé. But lo! This is a reduction! We can reduce all the predicates over the and operator get a single composite predicate, like this:
Predicate<Widget> compositePredicate =
    allPredicates.stream()
                 .reduce(w -> true, Predicate::and);

(Credit: I learned this technique from @venkat_s. If you ever get a chance, go see him speak at a conference. He's good.)
Note the use of w -> true as the identity value of the reduction. (This could also be used as the initial value of compositePredicate for the loop, which would fix the zero-length list case.)
Now that we have our composite predicate, we can write out a short pipeline that simply applies the composite predicate to the widgets:
widgetList.stream()
          .filter(compositePredicate)
          .forEach(System.out::println);

Context Sensitive Filters
Now let's consider what I referred to as a "context sensitive" filter, which is represented by the example like "top 50% in a certain order", say the top 50% of widgets by weight. "Context sensitive" isn't the best term for this but it's what I've got at the moment, and it is somewhat descriptive in that it's relative to the number of elements in the stream up to this point.
How would we implement something like this using streams? Unless somebody comes up with something really clever, I think we have to collect the elements somewhere first (say, in a list) before we can emit the first element to the output. It's kind of like sorted() in a pipeline which can't tell which is the first element to output until it has read every single input element and has sorted them.
The straightforward approach to finding the top 50% of widgets by weight, using streams, would look something like this:
List<Widget> temp =
    list.stream()
        .sorted(comparing(Widget::weight).reversed())
        .collect(toList());
temp.stream()
    .limit((long)(temp.size() * 0.5))
    .forEach(System.out::println);

This isn't complicated, but it's a bit cumbersome as we have to collect the elements into a list and assign it to a variable, in order to use the list's size in the 50% computation.
This is limiting, though, in that it's a "static" representation of this kind of filtering. How would we chain this into a stream with a variable number of elements (other filters or criteria) like we did with the predicates?
A important observation is that this code does its actual work in between the consumption of a stream and the emitting of a stream. It happens to have a collector in the middle, but if you chain a stream to its front and chain stuff off its back end, nobody is the wiser. In fact, the standard stream pipeline operations like map and filter each take a stream as input and emit a stream as output. So we can write a function kind of like this ourselves:
Stream<Widget> top50PercentByWeight(Stream<Widget> stream) {
    List<Widget> temp =
        stream.sorted(comparing(Widget::weight).reversed())
              .collect(toList());
    return temp.stream()
               .limit((long)(temp.size() * 0.5));
}

A similar example might be to find the shortest three widgets:
Stream<Widget> shortestThree(Stream<Widget> stream) {
    return stream.sorted(comparing(Widget::length))
                 .limit(3);
}

Now we can write something that combines these stateful filters with ordinary stream operations:
shortestThree(
    top50PercentByWeight(
        widgetList.stream()
                  .filter(w -> w.length() >= 10)))
.forEach(System.out::println);

This works, but is kind of lousy because it reads "inside-out" and backwards. The stream source is widgetList which is streamed and filtered through an ordinary predicate. Now, going backwards, the top 50% filter is applied, then the shortest-three filter is applied, and finally the stream operation forEach is applied at the end. This works but is quite confusing to read. And it's still static. What we really want is to have a way to put these new filters inside a data structure that we can manipulate, for example, to run all the permutations, as in the original question.
A key insight at this point is that these new kinds of filters are really just functions, and we have functional interface types in Java which let us represent functions as objects, to manipulate them, store them in data structures, compose them, etc. The functional interface type that takes an argument of some type and returns a value of the same type is UnaryOperator. The argument and return type in this case is Stream<Widget>. If we were to take method references such as this::shortestThree or this::top50PercentByWeight, the types of the resulting objects would be
UnaryOperator<Stream<Widget>>

If we were to put these into a list, the type of that list would be
List<UnaryOperator<Stream<Widget>>>

Ugh! Three levels of nested generics is too much for me. (But Aleksey Shipilev did once show me some code that used four levels of nested generics.) The solution for too much generics is to define our own type. Let's call one of our new things a Criterion. It turns out that there's little value to be gained by making our new functional interface type be related to UnaryOperator, so our definition can simply be:
@FunctionalInterface
public interface Criterion {
    Stream<Widget> apply(Stream<Widget> s);
}

Now we can create a list of criteria like this:
List<Criterion> criteria = Arrays.asList(
    this::shortestThree,
    this::lengthGreaterThan20
);

(We'll figure out how to use this list below.) This is a step forward, since we can now manipulate the list dynamically, but it's still somewhat limiting. First, it can't be combined with ordinary predicates. Second, there's a lot of hard-coded values here, such as the shortest three: how about two or four? How about a different criterion than length? What we really want is a function that creates these Criterion objects for us. This is easy with lambdas.
This creates a criterion that selects the top N widgets, given a comparator:
Criterion topN(Comparator<Widget> cmp, long n) {
    return stream -> stream.sorted(cmp).limit(n);
}

This creates a criterion that selects the top p percent of widgets, given a comparator:
Criterion topPercent(Comparator<Widget> cmp, double pct) {
    return stream -> {
        List<Widget> temp =
            stream.sorted(cmp).collect(toList());
        return temp.stream()
                   .limit((long)(temp.size() * pct));
    };
}

And this creates a criterion from an ordinary predicate:
Criterion fromPredicate(Predicate<Widget> pred) {
    return stream -> stream.filter(pred);
}

Now we have a very flexible way of creating criteria and putting them into a list, where they can be subsetted or permuted or whatever:
List<Criterion> criteria = Arrays.asList(
    fromPredicate(w -> w.length() > 10),                    // longer than 10
    topN(comparing(Widget::length), 4L),                    // longest 4
    topPercent(comparing(Widget::weight).reversed(), 0.50)  // heaviest 50%
);

Once we have a list of Criterion objects, we need to figure out a way to apply all of them. Once again, we can use our friend reduce to combine all of them into a single Criterion object:
Criterion allCriteria =
    criteria.stream()
            .reduce(c -> c, (c1, c2) -> (s -> c2.apply(c1.apply(s))));

The identity function c -> c is clear, but the second arg is a bit tricky. Given a stream s we first apply Criterion c1, then Criterion c2, and this is wrapped in a lambda that takes two Criterion objects c1 and c2 and returns a lambda that applies the composition of c1 and c2 to a stream and returns the resulting stream.
Now that we've composed all the criteria, we can apply it to a stream of widgets like so:
allCriteria.apply(widgetList.stream())
           .forEach(System.out::println);

This is still a bit inside-out, but it's fairly well controlled. Most importantly, it addresses the original question, which is how to combine criteria dynamically. Once the Criterion objects are in a data structure, they can be selected, subsetted, permuted, or whatever as necessary, and they can all be combined in a single criterion and applied to a stream using the above techniques.
The functional programming gurus are probably saying "He just reinvented ... !" which is probably true. I'm sure this has probably been invented somewhere already, but it's new to Java, because prior to lambda, it just wasn't feasible to write Java code that uses these techniques.
Update 2014-04-07
I've cleaned up and posted the complete sample code in a gist.


text:
Q: How to compute IOU(overlaps) using 2 pandas DataFrames In object detection, IOU(intersection over union) is a value between 0 and 1 that represents the percentage of overlap between 2 boxes drawn on an object in a certain image.
To help you understand what that is, here's an illustration:

The red frame is the real value with coordinates x1(top left), y1(bottom left), x2(top right), y2(bottom right).
The purple frame is the predicted value with coordinates x1_predicted, y1_predicted, x2_predicted, y2_predicted.
The yellow shaded square is the iou, if it's value is greater than a certain threshold(0.5 by convention) the prediction evaluates as True, otherwise it's a False.
Here's the code that calculates IOU for 2 boxes:
def get_iou(box_true, box_predicted):
    x1, y1, x2, y2 = box_true
    x1p, y1p, x2p, y2p = box_predicted
    if not all([x2 > x1, y2 > y1, x2p > x1p, y2p > y1p]):
        return 0
    far_x = np.min([x2, x2p])
    near_x = np.max([x1, x1p])
    far_y = np.min([y2, y2p])
    near_y = np.max([y1, y1p])
    inter_area = (far_x - near_x + 1) * (far_y - near_y + 1)
    true_box_area = (x2 - x1 + 1) * (y2 - y1 + 1)
    pred_box_area = (x2p - x1p + 1) * (y2p - y1p + 1)
    iou = inter_area / (true_box_area + pred_box_area - inter_area)
    return iou

I have the predictions and the actual data contained in 2 csv files which I read into 2 pandas DataFrame objects and go from there.
For every image, I extract detections of a certain object type (ex: car) and the actual data, here's an example for 1 object(car) in 1 image(Beverly_hills1.png)
Actual:
              Image Path Object Name  X_min  Y_min  X_max  Y_max
3842  Beverly_hills1.png         Car    760    432    911    550
3843  Beverly_hills1.png         Car    612    427    732    526
3844  Beverly_hills1.png         Car    462    412    597    526
3845  Beverly_hills1.png         Car    371    432    544    568

Detections:
                  image object_name   x1   y1   x2   y2
594  Beverly_hills1.png         Car  612  422  737  539
595  Beverly_hills1.png         Car  383  414  560  583

Here's how I would compare:
def calculate_overlaps(self, detections, actual):
    calculations = []
    detection_groups = detections.groupby('image')
    actual_groups = actual.groupby('Image Path')
    for item1, item2 in zip(actual_groups, detection_groups):
        for detected_index, detected_row in item2[1].iterrows():
            detected_coordinates = detected_row.values[2: 6]
            detected_overlaps = []
            coords = []
            for actual_index, actual_row in item1[1].iterrows():
                actual_coordinates = actual_row.values[4: 8]
                detected_overlaps.append((
                    self.get_iou(actual_coordinates, detected_coordinates)))
                coords.append(actual_coordinates)
            detected_row['max_iou'] = max(detected_overlaps)
            x1, y1, x2, y2 = coords[int(np.argmax(detected_overlaps))]
            for match, value in zip([f'{item}_match'
                                     for item in ['x1', 'y1', 'x2', 'y2']],
                                    [x1, y1, x2, y2]):
                detected_row[match] = value
            calculations.append(detected_row)
    return pd.DataFrame(calculations)

For every object type this will run which is inefficient.
The end result will look like this:
                     image object_name    x1  ...  y1_match  x2_match  y2_match
594     Beverly_hills1.png         Car   612  ...       427       732       526
595     Beverly_hills1.png         Car   383  ...       432       544       568
1901   Beverly_hills10.png         Car   785  ...       432       940       578
2015  Beverly_hills101.png         Car   832  ...       483      1240       579
2708  Beverly_hills103.png         Car   376  ...       466      1333       741
...                    ...         ...   ...  ...       ...       ...       ...
618    Beverly_hills93.png         Car   922  ...       406       851       659
625    Beverly_hills93.png         Car  1002  ...       406       851       659
1081   Beverly_hills94.png         Car   398  ...       426       527       559
1745   Beverly_hills95.png         Car  1159  ...       438       470       454
1746   Beverly_hills95.png         Car   765  ...       441       772       474

[584 rows x 14 columns]

How to simplify / vectorize this and eliminate for loops? can this be done using np.where()?

A: First, I noticed your get_iou function has a condition: x2 > x1, y2 > y1, x2p > x1p, y2p > y1p. You should make sure that condition holds for both data frames.
Second, the actual has columns Image Path and Object Name, while detections has image and object_name. You may want to change the corresponding columns to one single name.
That said, here's my solution with merge:
def area(df,columns):
    '''
    compute the box area
    @param df: a dataframe
    @param columns: box coordinates (x_min, y_min, x_max, y_max)
    '''
    x1,y1,x2,y2 = [df[col] for col in columns]
    return (x2-x1)*(y2-y1)

# rename the columns
actual = actual.rename(columns={'Image Path':'image', 'Object Name':'object_name'})

# merge on `image` and `object_name`
total_df = (actual.merge(detections, on=['image', 'object_name'])

# compute the intersection
total_df['x_max_common'] = total_df[['X_max','x2']].min(1)
total_df['x_min_common'] = total_df[['X_min','x1']].max(1)
total_df['y_max_common'] = total_df[['Y_max','y2']].min(1)
total_df['y_min_common'] = total_df[['Y_min','y1']].max(1)

# valid intersection
true_intersect = (total_df['x_max_common'] > total_df['x_min_common']) & \
                 (total_df['y_max_common'] > total_df['y_min_common'])

# filter total_df with valid intersection
total_df = total_df[true_intersect]

# the various areas
actual_areas = area(total_df, ['X_min','Y_min','X_max','Y_max'])
predicted_areas = area(total_df, ['x1','y1','x2','y2'])
intersect_areas = area(total_df,['x_min_common','y_min_common','x_max_common', 'y_max_common'])

# IOU
iou_areas = intersect_areas/(actual_areas + predicted_areas - intersect_areas)

# assign the IOU to total_df
total_df['IOU'] = iou_areas

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to insert a column at a specific position in JTable I have a JTable with a predefined model
how to ask the model to insert a specific column in a specific position ?
so i want something like : DefaultTableModel.insertRow(int,Object[]) for columns

A: There is no insertColumn method like DefaultTableModel.insertRow() for inserting rows. In order to insert a column at a particular position, you must append the column using DefaultTable.addColumn() and then move the new column into the desired position.
    JTable table = new JTable(rows, cols);
    table.setAutoCreateColumnsFromModel(false);

    DefaultTableModel model = (DefaultTableModel)table.getModel();
    TableColumn col = new TableColumn(model.getColumnCount());

    col.setHeaderValue(headerLabel);
    table.addColumn(col);
    model.addColumn(headerLabel.toString(), values);
    table.moveColumn(table.getColumnCount()-1, vColIndex);

A: Is it really necessary to add the column in your TableModel at a specific index ? You can more easily adjust the column order in the view (the JTable) as documented in the class javadoc of JTable

By default, columns may be rearranged in the JTable so that the view's columns appear in a different order to the columns in the model. This does not affect the implementation of the model at all: when the columns are reordered, the JTable maintains the new order of the columns internally and converts its column indices before querying the model.

This is achieved by using the JTable#moveColumn method.
Adding a column to your DefaultTableModel is done calling the DefaultTableModel#addColumn method

A: With DefaultTableModel:
At the end one has to call fireDataChanged. There is only an addColumn with several overloads. This is no hindrance as the order of display is independent. One may move a column to another position, and has to take care of view index != column index. To get the correct view index immediately after adding the column, one has to access the JTable and call moveColumn.
I found it at times easier to create a new TableModel and assign that. Or not use the DefaultTableModel.

A: this link may help
http://www.roseindia.net/java/example/java/swing/InsertColumn.shtml
public void positionColumn(JTable table,int col_Index) {
 table.moveColumn(table.getColumnCount()-1, col_Index);
  }


text:
Q: Working with duplicated nested SVG elements I came across following problem while working with snap.svg.
I would like to use nested SVG elements inside a main one. Let's say one of this nested one has a structure like this:
<svg width="71" height="101" viewBox="0 0 71 101">
<defs>
    <rect id="a" width="70" height="100" rx="5"/>
    <mask id="d" width="70" height="100" x="0" y="0" fill="#fff">
    <use xlink:href="#a"/>
    </mask>
    <rect id="b" width="70" height="100" rx="5"/>
    <mask id="e" width="70" height="100" x="0" y="0" fill="#fff">
    <use xlink:href="#b"/>
    </mask>
    <pattern id="f" width="6" height="5" x="-6" y="-5" patternUnits="userSpaceOnUse">
    <use transform="scale(.5)" xlink:href="#tipstercard-c"/>
    </pattern>
    <image id="c" width="12" height="10" xlink:href="data:image/png;base64,..."/>
</defs>
<g fill="none" fill-rule="evenodd" transform="translate(.338 .194)">
    <use fill="#212120" stroke="#FFF" stroke-width="4" mask="url(#tipstercard-d)" xlink:href="#a"/>
    <use fill="url(#f)" fill-opacity=".1" stroke="#FFF" stroke-width="4" mask="url(#e)" style="mix-blend-mode:luminosity" xlink:href="#b"/>
    <path fill="#FFF" d="M20.22 47.784v1.53h-1.344v2.923c0 .593.013.937.04 1.035a.42.42 0 0 0 .174.241c.091.064.2>...

I tried to do sth like fragments['card'].select('svg').clone();, but this results in: TypeError: Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
I tried also following fragments['card'].select('svg').toDefs();, but this results in: DOMException: Failed to execute 'appendChild' on 'Node': The new child element contains the parent.
What would be a possible way to do it with snap?
EDIT
Seems like I needed to use:
  Surface.append(fragments['card']);
  const Card = Surface.select('#card');
  Card.toDefs();
  const CardDef = Surface.select('#card');
  CardDef.use().attr({...});

Now the question is why this doesn't work fragments['card'].select('svg').toDefs(); and the above code does? Why cannot I use fragments['card'].select('svg') directly?

A: A fragment has no notion of Snap methods, so methods like clone() will not work. First they need to be appended to the DOM. Also a fragment isn't fully in the DOM, so there are issues with some common svg methods that would be available to DOM SVG elements.
So something like fragment.select('svg').clone() wouldn't work (as clone is a Snap method). First you need to 'Snapify' it (turn it into a Snap element, a wrapper around the svg element).
So you would need to do something like the following..first add it to the DOM...
Surface.append( fragment.select('svg') );

Now that its in the DOM, you can Snapify it and clone it (as we now have the Snap methods available to this element).
Surface.select('someId').clone();

Note, if you have a DOM element somewhere, you can also turn it into a Snap element, by doing
var snapElement = Snap( someDomElement );

This keeps the DOM element as it is, but just adds a Snap wrapper around it, and returns this as the Snap element.
So you found the right code yourself, and the main answer is that your element wasn't a Snap element when trying to call methods on it (or appended to the DOM).
Note: You can kind of Snapify a fragment without adding it to the DOM, but it doesn't bring you any new methods unless it's in the main DOM I think, but could be handy for just storing a reference to an element that will get appended later.


text:
Q: How to obtain graph feature values for multiple rna sequences at once? I need to obtain graph feature values (like maybe around 20) for multiple rna sequences at once.
So if I input the file containing rna sequences the output file should contain these 20 features per line for each sequence. I have looked into GraPPLE but it gives feature values only for one at a time. Similar case for igraph.
I have a 500 sequence file for which I need to obtain these feature values and then further training it.

A: You may want to have a look at recent articles citing GraPPLE:
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2685108/citedby/
Specifically, RNAcon is also graph-based approach:
https://www.ncbi.nlm.nih.gov/pubmed/24521294
Lastly, this review may be of interest:
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5153550/


text:
Q: Are fgetpos() and fsetpos() only for text mode? What location/offset data is the fpos_t object filled with if not number of bytes? I understand the workings of ftell() and fseek() in C, but for this question I couldn't find any precise answer anywhere, including from the closest post on StackOverflow(LINK).
So can you please answer the following:

*

*Can it be concluded that fgetpos() and fsetpos() are relevant only for text files opened in text mode, and not for files opened in binary mode?

*What kind of position information is the fpos_t object filled with by fgetpos(), given that it is not a long integer offset etc. like the one given by ftell()? The site cplusplusreference only tells the following:

The function fills the fpos_t object pointed by pos with the information needed from the stream's position indicator to restore the stream to its current position

A: fgetpos() and fsetpos() are relevant for both text and binary mode.
The advantage of fgetpos() is that is keeps the full position in the stream, including its internal state,  so that you can restore is later.  This works whether you are in text mode or not.  This is especially important if you are using wide oriented streams or mix fgetc() and fgetwc() in the same file, because some locale use a state dependent multibyte encoding (state depends on previous reads).
fseek() and ftell() can also work with text and binary mode.  However there is an important restriction in text mode: you should only use fseek() with 0 or a value previously returned by ftell() (in binary mode you can use whatever value you want). This is because the text mode reading can change the number of bytes returned from  reading compared to the bytes effectively in the file (typical example, the 2 CR+LF bytes in a windows file which are converted to a signe LF byte).
As ftell() only returns a long int offset, it can't keep track of the multibyte state if this would be needed. So using fseek() might loose this state.

A: Not quite. Clues can be found from Beej:

On virtually every system (and certainly every system that I know of),
  people don't use these functions, using ftell() and fseek() instead.
  These functions exist just in case your system can't remember file
  positions as a simple byte offset.

And Linux man pages:

On some non-UNIX systems, an fpos_t object may be a complex object and
  these routines may be the only way to portably reposition a text
  stream.

And on Windows:

It assumes that any \n character in the buffer was originally a \r\n
  sequence that had been normalized when the data was read into the
  buffer.

That is to say, files that aren't (Windows-linebreak) text files go wrong in Windows when opened in text mode because fsetpos is assuming the file really was a (Windows-linebreak) text file and therefore cannot contain a \n with no \r.
The C11 standard says (my emphasis):
7.21.2/6:

Each wide-oriented stream has an associated mbstate_t object that
  stores the current parse state of the stream.  A successful call to
  fgetpos stores a representation of the value of this mbstate_t object
  as part of the value of the fpos_t object. A  later successful call to
  fsetpos using the same stored fpos_t value restores the value of the
  associated mbstate_t object as well as the position within the
  controlled stream.

Note that fseek and ftell have nothing to say about the mbstate_t object: they do not report or restore it. So on wide-oriented streams (that is to say, streams on which you've used wide-oriented I/O functions) they only reset the file position, not (if the implementation actually has more than one possible value of a mbstate_t object) the whole state of the stream.
Wide-oriented streams aren't the same thing as text streams, it's just that reading wide text files is the common use for them. Actually fseek and ftell are documented to be able to reset the file position on text files, provided you use them correctly. So I believe (I might be wrong) that fsetpos and fgetpos are only required when using wide I/O functions on the stream.

A: Besides the reasons mentioned in the other answers, it might be necessary to use fgetpos and fsetpos if you are working with very large files, files that contain more than LONG_MAX bytes.  This is a real concern on systems where LONG_MAX is 231 − 1; files with more than two billion bytes in them are not that uncommon nowadays.
If you are on a system that implements POSIX.1-2001, there is a better alternative, which is to #define _FILE_OFFSET_BITS 64 before including any system header files, and then use fseeko and ftello. These are just like fseek and ftell except that they take/return an off_t quantity, which, provided you have made the above #define, is guaranteed to be an integer type that can represent 263 − 1, which ought to be enough for anybody.  This is better because you can do arithmetic on off_t; you can't use fpos_t to go somewhere you haven't already been.  But if you're not on a POSIX system, fgetpos and fsetpos might be your only option.
(Note that some systems will give you an fpos_t that can't represent a file offset greater than LONG_MAX bytes. On some of those, applying the same #define _FILE_OFFSET_BITS 64 setting will help.  On others, you're just completely out of luck if you want a huge file.)


text:
Q: How to insert a jquery listview populated from a json file to mysql using php I am working on a jquery mobile app to allow recruitment agent to interact with job seekers through a mobile app. On the job link I decided to enter different vacant jobs on the app dynamically using json and I am able to enter jobs in json file and it uploads them to the app without any problem.
But I am trying to allow the current logged user to select a job that is where I need to use php to help insert data from the listview to mysql database. I am attaching the files to get any assistance from you.thanks in advance
my json code
[
 {"jobtype":"IT project manager",
  "city":"Johannesburg",
  "message":"We are looking for a manager at go fish company to manage the IT departments",
  "details":"We are looking for a manager at go fish company to manage the IT department and thank you",
  "jobid":"IT1"
  },

  {"jobtype":"Geologist",
  "city":"Captown",
  "message":"We are looking for an experienced Geologist to join a mining comapy established in congo.",
   "details":"We are looking for a manager at go fish company to manage the IT department,but it will be more beneficial for soemone who has done engineering,even those who have not finished yet but have enough experience in the trade they are welcome as long as they can do the job,the position is widely open for you to apply.so for any question contact patrick at 063167888.good luck",
    "jobid":"GE1"
  },
   {"jobtype":"Librarian",
  "city":"Johannesburg",
  "message":"We are looking for an experienced librarian to handle the library in sandton city.",
   "details":"We are looking for a manager at go fish company to manage the IT department",
    "jobid":"LI1"
  }
]

my jquery mobile codes

Services

        <?php  echo 'Welcome '.$_SESSION['name'];

        echo "
Logout"; ?> ...

©2016 • Genesis M&C Holdings Pty

my php codes
<?php //data.php
include_once 'Dbconnect.php';
if (isset($_POST['appbtn'])){
    // Get values from form

    $JobsId=json_decode($_post['jobid']);
    $JobTitle=json_decode($_post['jobtype']);
    $JobCity=json_decode($_post['city']);

    // Insert data into mysql

    $sql="INSERT INTO jobs (jobid,jobtitle,jobcity,datetime)
          VALUES ('$JobsId ', '$JobTitle','$JobCity',now()) ";
    $result = mysql_query($sql);

    // if successfully insert data into database, displays message "Successful".
    if($result){
        header("Location: index.php#page4?message=success");
        echo"successfully registered";
    } else {
        echo "ERROR";
    }


text:
Q: UINavigationItem title location not updating on rotation This feels like a silly question but for the life of me, I can't figure it out. In short, I'm manually adding a navigation bar to my view and it contains a UINavigationItem.
I've added one UIBarButtonItem and I'm setting the title like so:
UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonSystemItemDone target:self action:@selector(doneTapped:)];
[doneButton setBackgroundVerticalPositionAdjustment:20 forBarMetrics:UIBarMetricsDefault];
doneButton.tintColor = [UIColor blackColor];

self.navItem = [[UINavigationItem alloc] init];
[self.navItem setLeftBarButtonItem:doneButton];
self.navItem.title = @"Help Directory";
[self.navBar setItems:@[self.navItem]];

This works fine will I reach this view controller. Problems start to arise during rotation. The title stays in the exact same location. Here's the portrait version:

Here's the landscape version:

This bug appears in earlier versions of the app, so it's not just an iOS 7 issue. Any advice on how to handle is appreciated. Many thanks.


text:
Q: SP2016 Powershell: Error Updating OwnerAlias - InvalidData I'm trying to update a site collection's owner and secondary with PowerShell.  Currently, they're blank and CA fails.  I enter the following in PowerShell:
Get-SPSite "http://company/division/site" | %{Set-SPSite $_ -OwnerAlias "spadmin" -SecondaryOwnerAlias "altspadmin"}

The following error is returned:

Set-SPSite :    At line:11 char:46
  + Get-SPSite "http://company/division/site" | %{Set-SPSite $_ -OwnerAlias "spadmin ...
  +                                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidData: (Microsoft.Share...SPCmdletSetSite:SPCmdletSetSite) [Set-SPSite],
  SPException
      + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletSetSite

(The highlight is under the Set-SPSite command.)  The names are valid.
 Even the domain\name fails.
Note: I don't know if this has something to do with the error, but I notice that the content db is missing the SPDataAccess and SPReadOnly.  Do you know how to get these roles installed?

A: *

*Make sure that you have set the correct Site Collection URL at Get-SPSite "<SiteCollection>"

*

*I tried this on my side and get the same error but you looks like not copy the full error message

So run first Get-SPSite to can get the Site Collection list, then add the correct site collection URL in your Cmdlet

*

*Make sure that the Owner Alias user is formatted as <domain>\<username>
Change site collection administrator CMDLET
Set-SPSite -Identity "<SiteCollection>" -SecondaryOwnerAlias "<User>"

Note: <User> is the name of the user whom you want to add in the format <domain>\<username>.
For more details check Change site collection administrators in SharePoint Server 2016


text:
Q: Scan from Xerox WorkCentre 3025 I have a multifunctional printer Xerox WorkCentre. I can print and scan from my computer. However, I cannot make scans from the device, when choosing scanning to PC. Is there a way to scan directly from the scanner instead of computer? I use Ubuntu 16.04.

A: In order to get the document scanned you may want to follow this :

*

*Install vsftpd
sudo apt-get install vsftpd

*As root, create the directory /home/ftpscan (read only for everybody except root) and  /home/ftpscan/write (read-write for everybody).
# sudo mkdir /home/ftpscan
# sudo mkdir /home/ftpscan/write
# sudo chmod ugo+rwx /home/ftpscan/write

*modify the configuration of vsftpd to include those lines :
# edit /etc/vsftpd.conf with your favorite text editor
# enable anonymous user : any password accepted
anonymous_enable=YES
# Do not need those local users
local_enable=NO
#allow anonymous to write
write_enable=YES
anon_mkdir_write_enable=YES
anon_upload_enable=YES
anon_root=/home/ftpscan
# Allows everybody to read the item placed anonymously
chown_upload_mode=0666
anon_umask=000

*restart service vsftpd

*Open the port 21 (FTP) for your printer (I think you may want to use UFW).

*Configure your printer via the http interface : I do not know the english words, may be you can help.  We take a webbrowser and follow
 HTTP://<IP>
 -> "Carnet d'adressse"              / ? 3th item
 -> "Carnet d'addresse PC/Server"    / ?
 -> "Carnet d'adresses PC / Serveur" / ?
 -> "ajouter"                        / add
  Change those fields (<.> means that it must be interpreted)
  - Name is free
  - Type of network   == FTP server and not SMB server
  - Host Address      == <your computer hostanme or your computer ip>
  - Port number       == <empty or 21>
  - connection name   == anonymous
  - password          == <anything or nothing>
  - path to directory == write

That is very creative names. Xerox is not giving neither easy nor standard interface.  I was expecting something more admirable from this company.

A: Solution for Windows:
Scan to Network PC

*

*Open the Xerox Easy Printer Manager application. Select

Start -> Programs or All Programs -> Xerox Printers -> Xerox Easy Printer Manager -> Easy Printer Manager.

*Select the Switch to Advanced Mode button at the top of the window.

*Select your machine in the Printer List and add it, if required.

*Select the Scan to PC Settings button. The Scan to PC Settings screen appears.

*Select Enable Scan from Device Panel.

*Select your required settings for Scan Settings:
• Output Color
• Resolution
• Original Size

*Select your required settings for File Settings:
• Save To
• File Format
• OCR Language
• Delete Original Image after OCR


text:
Q: Python Pip: Is it safe to delete ~/.local/bin in order to delete all user packages installed by pip? I installed a few user packages with pip by using
pip3 install --user <package_name>

I did this on a machine running Ubuntu 17.10.
I would like to start afresh. Is it safe to delete ~/.local/bin in order to do so or is there some other, more elegant solution? In particular, I'm worrying about messing with the Python packages, which my system requires to function properly.

A: The Free Desktop Specification notes that ~/.local/bin is a general place for user binaries, so I don't think its safe to assume that deleting that wont affect anything else.
The best method would be to use pip3 uninstall --user <package> to remove specific packages. you can list installed packages with pip3 list --user
Edit: A one-liner to delete all pip3 installed packages, using pip3's uninstall method and jq:
pip3 list --user --format=json | jq '.[].name' | xargs -I{} pip3 uninstall --user {}
Be careful though, as it will delete everything user installed, whether you use it or not!

A: You should uninstall package manually:
pip uninstall package_name


text:
Q: ListView Save State Of Checked Box I have made a checkbox within the Listview. However, when I shut the app and reopen, it doesn't save the state of items that I have listed.
However this has not worked for me, and I cant seem to find an answer as to how to solve this problem. If anyone can help me through the code for ListAdapter Activty as shown below, it would be appreciated.
public class ListAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;

ListAdapter(Context context, ArrayList<Product> products) {
    ctx = context;
    objects = products;
    lInflater = (LayoutInflater) ctx
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return objects.size();
}

@Override
public Object getItem(int position) {
    return objects.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        view = lInflater.inflate(R.layout.item, parent, false);
    }

    Product p = getProduct(position);

    ((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
    ((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
    ((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);

    CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
    cbBuy.setOnCheckedChangeListener(myCheckChangList);
    cbBuy.setTag(position);
    cbBuy.setChecked(p.box);
    return view;
}

Product getProduct(int position) {
    return ((Product) getItem(position));
}

ArrayList<Product> getBox() {
    ArrayList<Product> box = new ArrayList<Product>();
    for (Product p : objects) {
        if (p.box)
            box.add(p);
    }
    return box;
}

OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView,
                                 boolean isChecked) {
        getProduct((Integer) buttonView.getTag()).box = isChecked;
    }
};
}

I'm not sure if I did something wrong or if I put it in wrong place or if the whole code is incorrect in doing this.
This is the Edited Solution Version using Shared Preferences:
public class ListAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;

ListAdapter(Context context, ArrayList<Product> products) {
    ctx = context;
    objects = products;
    lInflater = (LayoutInflater) ctx
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return objects.size();
}

@Override
public Object getItem(int position) {
    return objects.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        view = lInflater.inflate(R.layout.item, parent, false);
    }

   final Product p = getProduct(position);

    ((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
    ((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
    ((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);

    final CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
    SharedPreferences settings  = ctx.getSharedPreferences("data",ctx.MODE_PRIVATE);
    boolean Checked = settings.getBoolean(p.name, false);
    cbBuy.setChecked(Checked);

    cbBuy.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(cbBuy.isChecked()==true){
                SharedPreferences settings = ctx.getSharedPreferences("data",Context.MODE_PRIVATE);
                settings.edit().putBoolean(p.name, true).commit();
                Toast.makeText(ctx, "You Selected" + p.name, Toast.LENGTH_SHORT).show();

            }else{
                SharedPreferences settings = ctx.getSharedPreferences("data", Context.MODE_PRIVATE);
                settings.edit().putBoolean(p.name, false).commit();
                Toast.makeText(ctx, "You Deselected" +p.name, Toast.LENGTH_SHORT).show();

            }
        }
    });{

        return view;

    }

}

A: Fields are not persistent storage. If you want to persist data across launches, you'll have to save it on close and load it on start.


text:
Q: How to make div height same as sibling div's height?
I'm looking for a way to make #items div be the same height as #details div and I can't seem to be able to do this with CSS, therefore seeking for SO help.
There are also few nuances:

*

*#details height can vary depending on the content but will have a minimum height (e.g. 400px)

*#items can have 1 to N items, therefore scroll bar should hide if not needed (overflow-y: auto)

A: try flex like that:
.container {
  display: flex;
  align-items: stretch;
  justify-content: center;
}

#details {
   min-height: 400px;
}

note: container is parent of #items and #details

A: this can easily be achieved using flex,

.row {
    display: flex
}

#items {
    background: red;
    width: 20%;
}

#details {
    background: blue;
    width: 80%;
}

words

words wordswords words wordswordswords wordswordswords wordswordswords wordswordswords wordswordswords wordswordswords wordswordswords wordswordswords wordswords words wordswords words wordswords


text:
Q: How to create list of string elements I need method to get any type of text in list so it looks like this:
L = ['@', '$'. ')'] etc. I couldn't do it because text contains all special characters like brackets, # etc.
Example of text:
(&_+][&_@)$&$&^[_$(++$^}]&^^*(+*!&#_$]*+@!]+{%^_*+!&}@$!#^{+_#([+@(((*+)[()__}(^
@)](+[$*_(]*$[[&@^(_*#(*&!^{+]_%i)_)^[}@]#]%#@+^+[%{_*{!)}#$@#)_$!_(!*+#}%%}+$&$[
%&]!{{%*_!*}&)}$**_{*!#%[[#]!](^^$![#[[*}%(_#^^!%))!_^@)@**@}}(%%{#*%@(((]^%^![&
}!)$]&($)@](+(#{$)_%^%_^^#][{*[)%}+[##(##^{$}^]#&(&*{)%)&][&{]&#]}[[^^&[!#}${@_(
@}&$[[%]_&$+)$!%{(}$^$}*

Problem is that I need to make program that will search this kind of text to get letters, but I can't create list of this characters.

A: You get achieve like this
>>> text = """(&_+][&_@)$&$&^[_$(++$^}]&^^*(+*!&#_$]*+@!]+{%^_*+!&}@$!#^{+_#([+@(((*+)[()__}(^
... @)](+[$*_(]*$[[&@^(_*#(*&!^{+]_%i)_)^[}@]#]%#@+^+[%{_*{!)}#$@#)_$!_(!*+#}%%}+$&$[
... %&]!{{%*_!*}&)}$**_{*!#%[[#]!](^^$![#[[*}%(_#^^!%))!_^@)@**@}}(%%{#*%@(((]^%^![&
... }!)$]&($)@](+(#{$)_%^%_^^#][{*[)%}+[##(##^{$}^]#&(&*{)%)&][&{]&#]}[[^^&[!#}${@_(
... @}&$[[%]_&$+)$!%{(}$^$}*"""
>>> L = list()
>>> for character in text:
...     L.append(character)
...
>>> L
['(', '&', '_', '+', ']', '[', '&', '_', '@', ')', '$', '&', '$', '&', '^', '[', '_', '$', '(', '+', '+', '$', '^', '}', ']', '&', '^', '^', '*', '(', '+', '*', '!', '&', '#', '_', '$', ']', '*', '+', '@', '!', ']', '+', '{', '%', '^', '_', '*', '+', '!', '&', '}', '@', '$', '!', '#', '^', '{', '+', '_', '#', '(', '[', '+', '@', '(', '(', '(', '*', '+', ')', '[', '(', ')', '_', '_', '}', '(', '^', '\n', '@', ')', ']', '(', '+', '[', '$', '*', '_', '(', ']', '*', '$', '[', '[', '&', '@', '^', '(', '_', '*', '#', '(', '*', '&', '!', '^', '{', '+', ']', '_', '%', 'i', ')', '_', ')', '^', '[', '}', '@', ']', '#', ']', '%', '#', '@', '+', '^', '+', '[', '%', '{', '_', '*', '{', '!', ')', '}', '#', '$', '@', '#', ')', '_', '$', '!', '_', '(', '!', '*', '+', '#', '}', '%', '%', '}', '+', '$', '&', '$', '[', '\n', '%', '&', ']', '!', '{', '{', '%', '*', '_', '!', '*', '}', '&', ')', '}', '$', '*', '*', '_', '{', '*', '!', '#', '%', '[', '[', '#', ']', '!', ']', '(', '^', '^', '$', '!', '[', '#', '[', '[', '*', '}', '%', '(', '_', '#', '^', '^', '!', '%', ')', ')', '!', '_', '^', '@', ')', '@', '*', '*', '@', '}', '}', '(', '%', '%', '{', '#', '*', '%', '@', '(', '(', '(', ']', '^', '%', '^', '!', '[', '&', '\n', '}', '!', ')', '$', ']', '&', '(', '$', ')', '@', ']', '(', '+', '(', '#', '{', '$', ')', '_', '%', '^', '%', '_', '^', '^', '#', ']', '[', '{', '*', '[', ')', '%', '}', '+', '[', '#', '#', '(', '#', '#', '^', '{', '$', '}', '^', ']', '#', '&', '(', '&', '*', '{', ')', '%', ')', '&', ']', '[', '&', '{', ']', '&', '#', ']', '}', '[', '[', '^', '^', '&', '[', '!', '#', '}', '$', '{', '@', '_', '(', '\n', '@', '}', '&', '$', '[', '[', '%', ']', '_', '&', '$', '+', ')', '$', '!', '%', '{', '(', '}', '$', '^', '$', '}', '*']


text:
Q: list files created or updated on a specific day Wondering what is the most simple command to show (ls) local files under a specific folder created or updated on a specific day?
I am using Linux/Mac OS.

A: ls -t

Will sort results based on date.


text:
Q: How to show only RowDetails (not the row) when a DataGridRow is selected? I got the following DataGrid:
<DataGrid ItemsSource="{Binding MyList}" AutoGenerateColumns="False" SelectionUnit="FullRow">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Header" Binding="{Binding MainText}"/>
    </DataGrid.Columns>
    <DataGrid.RowDetailsTemplate>
        <DataTemplate DataType="{x:Type local:MyViewModel}">
            <TextBlock Text="{Binding DetailText}"/>
        </DataTemplate>
    </DataGrid.RowDetailsTemplate>
</DataGrid>

Assumong MyList is a collection of MyViewModel objects:
public class MyViewModel {
    public string MainText { get; set; }
    public string DetailText { get; set; }
}

When the user clicks the row the row details are visible. Is it somehow possible to hide the row and only show the details on selection?

A: You can edit the ControlTemplate of each DataGridRow to hide its main content when it is selected.
You can for example use the Style provided here by MSDN. This is a big style so I'm only gonna paste important parts here:
<Style TargetType="{x:Type DataGridRow}">
  <!-- ...some setters... -->
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type DataGridRow}">
        <Border x:Name="DGR_Border"
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}"
                SnapsToDevicePixels="True">
          <Border.Background>
              <!-- ... -->
          </Border.Background>
          <VisualStateManager.VisualStateGroups>
            <!-- ...some states... -->
          </VisualStateManager.VisualStateGroups>
          <SelectiveScrollingGrid>
            <SelectiveScrollingGrid.ColumnDefinitions>
              <ColumnDefinition Width="Auto" />
              <ColumnDefinition Width="*" />
            </SelectiveScrollingGrid.ColumnDefinitions>
            <SelectiveScrollingGrid.RowDefinitions>
              <RowDefinition Height="*" />
              <RowDefinition Height="Auto" />
            </SelectiveScrollingGrid.RowDefinitions>
            <DataGridCellsPresenter Grid.Column="1"
                                    ItemsPanel="{TemplateBinding ItemsPanel}"
                                    SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
            <DataGridDetailsPresenter Grid.Column="1"
                                      Grid.Row="1"
                                      Visibility="{TemplateBinding DetailsVisibility}"
                                      SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding AreRowDetailsFrozen,
                                                    ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical},
                                                    Converter={x:Static DataGrid.RowDetailsScrollingConverter},
                                                    RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
            <DataGridRowHeader Grid.RowSpan="2"
                               SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical"
                               Visibility="{Binding HeadersVisibility,
                                            ConverterParameter={x:Static DataGridHeadersVisibility.Row},
                                            Converter={x:Static DataGrid.HeadersVisibilityConverter},
                                            RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
          </SelectiveScrollingGrid>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

The key is to change the Visibility of the DataGridCellsPresenter to Visibility.Collapsed when the DataGridRow is selected. You can do it by adding the following <DataGridCellsPresenter.Style> markup in the template:
<DataGridCellsPresenter Grid.Column="1"
                        ItemsPanel="{TemplateBinding ItemsPanel}"
                        SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}">
    <DataGridCellsPresenter.Style>
        <Style TargetType="DataGridCellsPresenter">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGridRow}}" Value="True">
                    <Setter Property="Visibility" Value="Collapsed" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGridCellsPresenter.Style>
</DataGridCellsPresenter>

If you test the application again, this will collapse the main content on selected rows, hence only display the detail row.


text: Q: Is there a way to view Qgis models from version 2.14 so they can be recreated in 3.0 I upgraded my qgis version from 2.14 to 3.0 and didn't realize that the models from the graphic modeler are not compatible.  Is there a way to view or read the models so I can recreate them in 3.0?  I have 24 that I use in various project and I would rather not have to build them from scratch again.


text:
Q: my program keeps hold of files it's written using GDI+   private void save(Rectangle src, Rectangle dest, string fName, int width, int height, Bitmap file)
        {
            Bitmap result = new Bitmap(width, height);

            Graphics g = Graphics.FromImage(result);

            g.DrawImage(file, dest, src, GraphicsUnit.Pixel);
            result.Save(fName);

            g.Dispose();
            result.Dispose();
            result = null;
            g = null;

        }

It does write the files but for some reason even if the program is closed, it keeps hold of them.

A: Try to use the overload with a Stream as a parameter of the Bitmap.Save() method. Then you can dispose the FileStream you pass as the argument.

A:
It does write the files but for some
  reason even if the program is closed,
  it keeps hold of them.

Not possible. The operating system closes all files when the process exits.  Must be some other process that has the file open.
Use the Process Explorer (http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) Find, Find Handle menu command on the file name to determine the process.

A: First of all, stop setting variable references to null - that has no significant effect in .NET.  The garbage collector decides when to free memory after variables go out of scope.
Second, you're not handling exceptions properly here.  C# gives you the try and using constructs for a reason: use them.
using (Bitmap result = new Bitmap(width, height))
{
    using (Graphics g = Graphics.FromImage(result))
    {
        g.DrawImage(file, dest, src, GraphicsUnit.Pixel);
    }
    result.Save(fName);
}

This code is a lot easier to read and won't leak resources if something unexpected happens.
If you're finding that the file itself is still locked or that GDI resources are still leaking, then something else is responsible - the above code cannot leak resources nor keep a file locked.  (Except in the event of certain fatal exceptions, but in that case your whole program is going down anyway)

A: Thanks to everyone. According to process explorer it was some ps3 controller software I was using and also nokia pc suite.


text:
Q: $R$ is the midpoint of $MN$ and the points where $AC$ intersects $MD$ and $ND$ are $P$ and $Q$, respectively. Show that $PR=QR$.
In square $ABCD$, $M$ and $N$ are points on $AB$ and $BC$, respectively such that $\angle MDN=45°$. $R$ is the midpoint of $MN$ and the points where $AC$ intersects $MD$ and $ND$ are $P$ and $Q$, respectively. Show that $PR=QR$.

I'm actually trying to prove that $PQMN$ is cyclic and the circumcircles of $PQMN$ and $\Delta BMN$ are the same. Am I going on the right track? Please help.

A: Yes, it is the right track. You may also directly prove that $PQNBM$ is a cyclic pentagon.
Assuming $D=(0,0),C=(1,0),N=(1,x_0)$, the equation of the $MD$-line is given by:
$$ y = \frac{1+x_0}{1-x_0}\,x $$
by the tangent addition formula, hence $M=\left(\frac{1-x_0}{1+x_0},1\right)$ and $R=\left(\frac{1}{1+x_0},\frac{1+x_0}{2}\right)$.
The equation of the $AC$-line is $y=1-x$, hence $P=\left(\frac{1}{1+x_0},\frac{x_0}{1+x_0}\right)$ and $Q=\left(\frac{1-x_0}{2},\frac{1+x_0}{2}\right)$.
Now it is straightforward to check that $RP=RQ=RN=RB=RM=\frac{1+x_0^2}{2(1+x_0)}$.

You may also prove that $\widehat{NPD}=\widehat{MQD}=\frac{\pi}{2}$, and everything follows nicely.

A: just to show things behind it.

A: My idea is more or less the same as @TomK 's.

First of all, we concentrate on the green circle (that will go through $A, M, Q, D$) . It is cyclic because $\alpha = \alpha_1 = \alpha_2 = 45^0$
Therefore, $\theta_1 + \phi_1 =  \theta_2 + \phi_2 = 90^0$
Together with R is the midpoint of MN, we have "$QMN$ is a semi-circle with $R$ as center".
By going through the same process using the blue circle, you can arrive at the conclusion "$PMN$ is a semi-circle with $R$ as center".
Result follows.

A: You can use the fact that angle QAM = QDM (=45) to show that AMQD is a circle. Hence DMQ is also 45.
Similarly DCNP is also a circle. Keep angle chasing and you should be able to conclude that MPQN is a circle and that the presence of a right angle at MQN reveals MN as the diameter as required.


text:
Q: How do you set up the initial directory for a FileDialog to be in sharepoint and allow you to select multiple items in VBA? What I am trying to do is open file dialog in a network path. I have figured out how to open it in the correct location, but it sets itself up as a website.
Here is the code:
Set files = Application.FileDialog(3) '3 is the File Picker type
    files.InitialFileName = "https://website.com/pathing/Document/"
    'files.InitialFileName = "\\website.com@SSL\pathing\Document\"
    files.AllowMultiSelect = True
    files.Show

Both lines that set the initial file name act exactly the same.
When I run the code I am unable to select more than one file. Unwanted Behavior

However, when I manually type in the pathing \\website.com@SSL\pathing\Document\ the File Dialog behaves as I want it to, allowing me to select multiple files. Desired Behavior

Is there a way for me to get directly to the intended behavior without having to manually enter it into the explorer bar?
Thank you.

A: If you want to access this directly, you need to tell the explorer that its dealing with webDav, which in fact SharePoint does if you open a library in an explorer view.
So the path to your library is https://website.com/pathing/Document/
So the UNC path looks like this:
\\website.com\davWWWroot\pathing\document\
You can however get the correct path all by yourself if you follow these steps:

*

*Open the path in a browser

*Switch to explorer view

*Copy the address in the explorer

*Map a network drive with the copied address.

*The network drive has the desired UNC path for you.


text:
Q: compare model fit logistic regression negative two times log likelihood I'm trying to decide between two logistic regression models.  I think I've used the negative two times log likelihood criterion before.  My two models are not nested - can I still use that approach? If so, please point me to a resource for how to use -2LogL to make the decision.  If not, what do you recommend?

A: If the models are not nested, as you are writing, the log-likelihood ratio test doesn't have the usual limiting $\chi^2$ distribution, so you have to use other methods.
One way could be to use information criteria such as AIC or BIC. In this approach, roughly speaking, the winner is the model that leads to the smallest AIC or BIC.
Another way is to compute the distribution of the test statistic via bootstrap. You could use (i) a parametric bootstrap approach in which data are generated from the estimated model or (ii) a nonparametric bootstrap approach in which the 'new' data are generated by extracting at random and with replacement from the observed dataset. See, for instance, Davison and Hinkley (1997) Bootstrap Methods and their Application, Cambridge University Press


text:
Q: confusion in implementing an interface I am reading a book in which author used a code like this
public class Pool<T> {

    public interface PoolObjectFactory<T> {
        public T createObject();
     }

    private final List<T> freeObjects;
    private final PoolObjectFactory<T> factory;
    private final int maxSize;

    public Pool(PoolObjectFactory<T> factory, int maxSize) {

        this.factory = factory;
        this.maxSize = maxSize;
        this.freeObjects = new ArrayList<T>(maxSize);

    } //end of constructor

} //end of class Pool<T>

Then he used code something like this
PoolObjectFactory<KeyEvent> factory = new PoolObjectFactory<KeyEvent>() {

    @Override
    public KeyEvent createObject() {
        return new KeyEvent();
    } //end of createObject()

};

keyEventPool = new Pool<KeyEvent>(factory, 100);

I want to ask at the line PoolObjectFactory<KeyEvent> factory = new PoolObjectFactory<KeyEvent>() {..}; he didn't say implements PoolObjectFactory. Why? When you use interface then you use implements keyword?
Thanks

A: The author is using a special construct called an anonymous class, which is defined using the following syntax:
new interface-name () { class-body }

A: You only need implements when you are defining a named class.
In this case the author is using an anonymous (unnamed) inner class which implements an interface.
Edit: For background, something a lot of people don't realise/appreciate is that the compiler will generate a .class file for anonymous inner classes.
e.g. the following produces a Fred.class file and a Fred$1.class file:
public class Fred {
    public void sayHelloFred() {
        Object o = new MouseAdapter() {
        };
    }
}

All these .class files still need to be shipped and loaded at runtime, just like if they were named classes.

A: You are creating an anonymous class here. No need for the implements keyword. Note that in this case you use new PoolObjectFactory and this clearly indicates the class you are implementing - no need to indicate it once more using implements.
On the other hand if you are creating a subclass you need to state which is it's parent interface and then you need the implements keyword.

A: The author uses an anonymous class. In such case, a class is created without an identifier and only one instance is created and assigned to the factory variable.

A: The implements keyword is used when defining a class to indicate that the class will meet the requirements of the interface. in the  line in question, the author instantiates an anonymous class.


text:
Q: How do we know you can only flip something's orientation two times? I was exploring what the determinant's sign means geometrically. For 2-D, you can swap the axes and you've flipped orientation, and once you swap them again, you get the original orientation.
Why should this be the case for higher dimensions? Why is it not possible that in 3-D, I can swap i and j, then swap j and k, and I get a "third orientation"?
How is orientation defined anyway?

A: Here is a geometric reason for the definition of orientation.
The set of all invertible $n \times n$ matrices forms a group denoted $GL(n,\mathbb R)$, and it is identified with the set of all invertible linear transformations $T : \mathbb R^n \to \mathbb R^n$.
This group decomposes into two subsets, which I'll denote
$$GL(n,\mathbb R) = {GL}_+(n,\mathbb R) \cup {GL}_-(n,\mathbb R)
$$
where the subscript represents the sign of the determinant.
Here are some key algebraic facts (easily derived from the theorem that the determinant of a product equals the product of the determinants):

*

*The product of any two matrices of positive determinant is another matrix of positive determinant. In other words, ${GL}_+(n,\mathbb R)$ is a subgroup of $GL(n,\mathbb R)$.

*The product of any two matrices of negative determinant is a matrix of positive determinant.

*The product of a matrix of positive determinant with a matrix of negative determinant (in either order) is a matrix of negative determinant.

These three algebraic facts can be summarized in a single statement: there is a group homomorphism $\sigma : GL(n,\mathbb R) \to \{-1,+1\}$ which assigns $+1$ to a matrix of positive determinant and $-1$ to a matrix of negative determinant.
Here are two key geometric facts:

*

*Theorem: Any two matrices in ${GL}_+(n,\mathbb R)$ can be connected by a continuous path of matrices in ${GL}+(n,\mathbb R)$.

*Corollary: Also, any two matrices in ${GL}_-(n,\mathbb R)$ can be connected by a continuous path of matrices in ${GL}_-(n,\mathbb R)$.

You asked:

Why is it not possible that in 3-D, I can swap i and j, then swap j and k, and I get a "third orientation"?

Because if you swap $i$ and $j$ using the following reflection matrix (which has negative determinant)
$$R_1 = \pmatrix{0&1&0\\1&0&0\\0&0&1}$$
and after that if you then swap $j$ and $k$ using the following reflection matrix (which also has negative determinant)
$$R_2 = \pmatrix{1&0&0\\0&0&1\\0&1&0}
$$
and then you formulate the product matrix
$$R_2 R_1 = \pmatrix{0&1&0\\0&0&1\\1&0&0}
$$
then $R_2 R_1$ has positive determinant, as you can check algebraically. Therefore, once you have convinced yourself of the algebraic and geometric facts listed earlier, you will be confident that $R_2 R_1$ does not represent a "new orientation" because it is connected by a continuous path of matrices with every other positive determinant matrix, i.e. with every rotation matrix and with the identity itself.
In fact, and you can verify this by calculation, $R_2 R_1$ is itself a rotation matrix: it is a rotation by $2\pi/3$ around the axis which is parameterized by $t \mapsto (t,t,t)$. If you fix this axis, and then vary the angle of rotation continuously, starting from the angle $2\pi/3$, and varying it down to the angle $0$, you will have produced a continuous path which connects the matrix $R_2 R_1$ with the identity matrix.
To summarize, the reason there is not a "third orientation" is because orientation is defined so as to summarize, and to be consistent with, the key algebraic and geometric facts that are listed above. In other words: invertible $n \times n$ matrices are naturally subdivided into two classes, and we choose to describe those two classes using the terminology of "orientations".
One last word: If you've not seen that theorem before, digging into its proof would be an excellent way to understand the geometric reasons why orientation is defined the way that it is.

A: A reasonable question, indeed, on geometric grounds.
If you track the details of your swap-$i$-and-$j$, and then $j$-and-$k$, you'll see that that composite action is a rotation (preserving orientation).
More generally, the composition of two reflections (the simplest orientation-reversing isometries) is a rotation (orientation-preserving). You can work out the details either geometrically or algebraically.


text:
Q: use pmap to increase counter but missed values (swap! foo (fn [old] 3))

(pmap
 (fn [_] (swap! foo inc))
 (range 10000))

@foo        ;It prints 1027, which is smaller than 10000.

So, why foo is not 10003 ?
Anything to do with laziness ?

A: From the documentation of pmap:

Semi-lazy in that the                                                                                parallel computation stays ahead of the consumption, but doesn't
    realize the entire result unless required. Only useful for
    computationally intensive functions where the time of f dominates
    the coordination overhead.

So yes, it's only realizing a few elements. Try wrapping the pmap in a doall and you'll see your intended result.


text:
Q: how to create .ASPXAUTH cookie on python i need to create .ASPXAUTH cookie on python. i programing to desktop client. and first request not need .ASPXAUTH cookie but second request is need.
My First Request Headers:
User-Agent: WebPolicy
Host: xxx.host
Cache-Control: no-cache

My First Response Headers:
reply: 'HTTP/1.1 200 OK\r\n'
header: Cache-Control: private

header: Transfer-Encoding: chunked

header: Content-Type: text/xml; charset=utf-8

header: Server: Microsoft-IIS/7.5

header: Set-Cookie: tivi_=3tnihi55ezuk50zyrrpuwv45; path=/; HttpOnly

header: X-AspNet-Version: 2.0.50727

header: X-Powered-By: ASP.NET

header: Date: Thu, 14 Oct 2010 13:05:50 GMT

And i need second send headers :
Accept: */*
Content-Length: 259
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://tempuri.org/IMiddlewareServices/Login"
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 1.1.4322)
Host: mw.webtv.ttnet.com.tr
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: .ASPXAUTH=090F2718E32AF3F9B1C9E5A15BA54CFD8D4430C44A91029719953D4A6D38DD1D9164D86D772E2645C0C0545A71C12EA80AE5A8F725FD6037BD00DB291A863DD577735E16D8745E2833979F337935F29A37C509FB0350F1180DA0D2C1C44F97D0F081B13D33984C198ECD695C34B2E79A3E7CFBDD2D67D630C019714C3A70280E; tivi_=nqkngs45drnsh4z4y4b30g55

please help me! how to create ".ASPXAUTH" cookie ?

A: Python requests module does the job for me with .ASPXAUTH cookie-based authentication. In a simple example below .ASPXAUTH cookie is received after the first session.get call and used for the second call:
import requests
session = requests.Session()
session.get('https://host/user/login?username=###&password=###')
print session.cookies
session.get('https://host/apicall')
print session.cookies


text:
Q: Transitioning between development and production stages with AWS Step Functions I have an AWS Step Function that is large enough for me to start worrying about me missing errors updating and deploying.
I have created a duplicate Step Function "dev" and have been copying over my updated JSON from "dev" into my "prod" Step Function. There are lots of Lambda ARNs to update and permissions in both Step Function's IAM Role. I was wondering if there was a better/automatic way of updating the "prod" environment other than pasting my "dev" JSON and then updating all of the Lambda references manually?

A: Using words like "dev" and "prod" is a sign that you have outgrown the console.
AWS offers several infrastructure-as-code approaches to deploy the same resources to multiple environments.  AWS recommends a multi-environment setup, with a separate account per environment.
For low barriers of entry, consider the Serverless Application Model (AWS SAM) and the Cloud Development Kit (AWS CDK), which both support low-complexity CI/CD.  There are plenty of 3rd party IaaC solutions as well.


text:
Q: UIActivityIndicator in Swift: how do you start and end it? I am trying to do something like this:
@IBOutlet weak var myActivityMonitor: UIActivityIndicatorView!

func doStuff(){
   myActivityMonitor.startAnimating()

   //stuff running here

   myActivityMonitor.stopAnimating()
}

but it is not starting nor stopping in sync. Basically if I remove the stop it will look like it is always running after having done the computation that I need. the part inside the comment involves downloading an image from an HTML link.
Any ideas how to solve this?
Thanks,

A: When running networking calls, they're usually ran asynchronously meaning that the task is handed off to another thread and completed there. The issue with this is it doesn't wait until the task is finished to stop animating causing myActivityMonitor to start and end almost at the same time.
To fix this, simply ensure that myActivityMonitor is accessible outside of the doStuff method and call myActivityMonitor.stopAnimating() elsewhere; preferably in a delegate method telling you that your data has finished loading.


text:
Q: What is this variant of remember doing? I remember to have heard that your mother has many suitors
Source

"My friend," said Nestor, "now that you remind me, I remember to have heard that your mother has many suitors, who are ill disposed towards you and are making havoc of your estate. Do you submit to this tamely, or are public feeling and the voice of heaven against you? Who knows but what Ulysses may come back after all, and pay these scoundrels in full, either single-handed or with a force of Achaeans behind him? If Minerva were to take as great a liking to you as she did to Ulysses when we were fighting before Troy (for I never yet saw the gods so openly fond of any one as Minerva then was of your father), if she would take as good care of you as she did of him, these wooers would soon some of them him, forget their wooing."

A: This usage, with remember in the sense of "recall, experience a memory" taking  an infinitive complement (Direct Object) is now obsolete. Today we would employ a gerund or that complement:

I remember hearing that ...
  I remember I have heard that ...

Nowadays infinitive complements with remember are reserved for situations where remember has the sense "recall and perform (an obligation)" ...

Did you remember to wash the dishes?

See this question for more about the present-day distinction between remember to VERB and remember VERBing.


text:
Q: ProgressDialog disappearing after some time I have an Android app with an AsyncTask, that does some synchronization from a database. While the task is performing, a ProgressDialog, started from the Task, is shown and updated after each synced peace of data. The whole task takes about 30-40 mins and runs good and clean every time. But afer about 20 mins the ProgressDialog disappears for some reason, while the task carries on.
I don't know why that happens... even if you hit the home button its still there. Is there some kind of trick oder workaround to fix this?
Here is my relevant code:
protected void onPreExecute() {
    dialog = new ProgressDialog(context);
    dialog.setCanceledOnTouchOutside(false);
    dialog.setCancelable(false);
    dialog.setTitle("Synchronisiere Datenbank...");
    this.dialog.setMessage("Datenbank wird synchronisiert. Dieser Vorgang     kann einige Minuten dauern");
    dialog.setView(bar);
    this.dialog.show();
}

protected void onPostExecute(String result) {
    Log.d("", "" + result);
    System.out.println("FEDDIG");

    try {
        if (this.dialog != null && this.dialog.isShowing()) {
            this.dialog.dismiss();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (!uploadSuccessful) {
        showErrorDialog();
    }
}


text:
Q: Central Limit Theorem for Truncated observations Consider a random variable $X$ with values in $\left[0,\infty\right)$ such that $E\left[X\right]=\infty$. Given $M > 0$ I want to estimate the expected value of $X$ truncated at $M$. That is I want to estimate
$\mu_M = E\left[X|X \le M\right]$. I observe a sequence $X_1, X_2, \ldots, X_n$, and then discard values greater than $M$, then compute the mean, essentially:
$$
\hat{\mu} = \frac{\sum_{1\le i \le n} I_{X_i \le M} X_i}{\sum_{1\le i \le n} I_{X_i \le M}}.
$$
Is $\hat{\mu}$ governed by a central limit theorem? Will it converge to $\mu$? How is the asymptotic variance of $\hat{\mu}$ affected by $n$ and $\mathcal{P}\left(X \le M\right)$?

A: Since you have truncated to a finite support, the variance of the truncated random variable must be finite, and so you can apply the classical central limit theorem to the parts that make up your estimator.  So yes, the asymptotic behaviour of the numerator and denominator in your expression are both governed by the central limit theorem.  As to convergence, the law-of-large numbers also applies, so yes, it will converge.  (Note that the LLN holds even in some cases with infinite variance.)
In this case the situation is complicated by the fact that the numerator and denominator in your expression are correlated random variables that are both asymptotically normal.  Below I will show you their asymptotic normal distributions useing the CLT.

Suppose we denote the "effective sample size" and "effective sample total" respectively by:
$$n_\text{eff}(\mathbf{x}_n) = \sum_{i=1}^n \mathbb{I}(x_i \leqslant M)
\quad \quad \quad
T(\mathbf{x}_n) = \sum_{i=1}^n x_i \cdot\mathbb{I}(x_i \leqslant M).$$
Let $\lambda = \mathbb{P}(X_i \leqslant M)$ denote the probability that an observation is with the trucation range, and define the conditional mean $\mu_M = \mathbb{E}(X_i|X_i \leqslant M)$ and conditional variance $\sigma_M^2 = \mathbb{V}(X_i|X_i \leqslant M)$.  To facilitate our analysis we take $Y_i = \mathbb{I}(X_i \leqslant M)$ and we note that:
$$\mathbb{E}(X_i Y_i | Y_i) = Y_i \cdot \mu_M
\quad \quad \quad
\mathbb{V}(X_i Y_i | Y_i)  = Y_i \cdot \sigma_M^2.$$
Thus, applying the law of iterated expectation and the law of iterated variance we have:
$$\begin{align}
\mathbb{E}(T(\mathbf{X}_n))
&= \sum_{i=1}^n \mathbb{E}(X_i Y_i) \\[6pt]
&= \sum_{i=1}^n \mathbb{E}(\mathbb{E}(X_i Y_i|Y_i)) \\[6pt]
&= \sum_{i=1}^n \mathbb{E}(Y_i \cdot \mu_M) \\[6pt]
&= \sum_{i=1}^n \lambda \mu_M \\[12pt]
&= n \lambda \mu_M, \\[12pt]
\mathbb{V}(T(\mathbf{X}_n))
&= \sum_{i=1}^n \mathbb{V}(X_i Y_i) \\[6pt]
&= \sum_{i=1}^n \Big[ \mathbb{E}(\mathbb{V}(X_i Y_i | Y_i)) + \mathbb{V}(\mathbb{E}(X_i Y_i | Y_i)) \Big] \\[6pt]
&= \sum_{i=1}^n \Big[ \mathbb{E}(Y_i \cdot \sigma_M^2) + \mathbb{V}(Y_i \cdot \mu_M) \Big] \\[6pt]
&= \sum_{i=1}^n \Big[ \lambda \sigma_M^2 + \lambda (1-\lambda) \mu_M^2 \Big] \\[12pt]
&= n \lambda (\sigma_M^2 + (1-\lambda) \mu_M^2). \\[12pt]
\end{align}$$
Consequently, we have:
$$\mathbb{E} \bigg( \frac{T(\mathbf{X}_n)}{n \lambda } \bigg) = \mu_M
\quad \quad \quad
\mathbb{V} \bigg( \frac{T(\mathbf{X}_n)}{n \lambda} \bigg) = \frac{\sigma_M^2 + (1-\lambda) \mu_M^2}{n \lambda}.$$
We can then form the standardised pivotal quantity and apply the central limit theorem to get:
$$\sqrt{n \lambda} \cdot \frac{T(\mathbf{X}_n)/n \lambda - \mu_M}{\sqrt{\sigma_M^2 + (1-\lambda) \mu_M^2}}
\overset{\text{Approx}}{\sim} \text{N}(0,1).$$
Undertaking similar calculations gives:
$$\mathbb{E} \bigg( \frac{n_\text{eff}(\mathbf{X}_n)}{n \lambda } \bigg) = 1
\quad \quad \quad
\mathbb{V} \bigg( \frac{n_\text{eff}(\mathbf{X}_n)}{n \lambda} \bigg) = \frac{1-\lambda}{n \lambda},$$
with the standardised pivotal quantity:
$$\sqrt{n \lambda} \cdot \frac{n_\text{eff}(\mathbf{X}_n)/n \lambda - 1}{\sqrt{1-\lambda}}
\overset{\text{Approx}}{\sim} \text{N}(0,1).$$
This gives the asymptotic distributions of the scaled numerator and denominator for $\hat{\mu}$.  The usual thing to do next would be to approximate the ratio by a T-distribution using an appropriate degrees-of-freedom.  One could go further by examining the correlation between these quantities and taking account of this in looking at the behaviour of the ratio.  In any case, the above shows how the CLT applies here.


text:
Q: A good C equivalent of STL vector? I've noticed that at several places in our code base we use dynamically expanding arrays, i.e. a base array coupled with an element counter and a "max elements" value.
What I want to do is replace these with a common data structure and utility functions, for the usual object-oriented reasons.
The array elements can be either basic data types or structs, I need fast random access to the elements, and preferably a type-safe implementation.
So, basically, what I would like to use is an STL vector, but the code base is restricted to C89 so I have to come up with something else :-)
I gave it some thought and whipped up this initial draft, just to show what I'm aiming at:
/* Type-safe dynamic list in C89 */

#define list_declare(type) typedef struct _##type##_list_t { type * base_array; size_t elements; size_t max_size; } type##_list_t
#define list(type) type##_list_t
#define list_new(type, initial_size) { calloc(initial_size, sizeof(type)), 0, initial_size }
#define list_free(list) free(list.base_array)
#define list_set(list, place, element) if ( list.elements < list.max_size ) { list.base_array[place] = element; } else { /* Array index out of bounds */ }
#define list_add(list, element) if ( list.elements < list.max_size ) { list.base_array[list.elements++] = element; } else { /* Expand array then add */ }
#define list_get(list, n) list.base_array[n]

/* Sample usage: */

list_declare(int);

int main(void)
{
    list(int) integers = list_new(int, 10);
    printf("list[0] = %d\n", list_get(integers, 0));
    list_add(integers, 4);
    printf("list[0] = %d\n", list_get(integers, 0));
    list_set(integers, 0, 3);
    printf("list[0] = %d\n", list_get(integers, 0));
    list_free(integers);

    return EXIT_SUCCESS;
}

...however, there must be someone else who has done this before. I'm aware of the FreeBSD sys/queue.h implementation of a similar concept for some different queues, but I can't find anything like that for arrays.
Is anyone here any wiser?

A: here a simple vector-replacement, its ONE function for all, its strictly C89 and threadsafe;
libs are too difficult for me, i use my own;
no performance, but easy to use
/* owner-structs too */
typedef struct {
  char name[20],city[20];
  int salary;
} My,*Myp;

typedef char Str80[80];

/* add here your type with its size */
typedef enum {SPTR,INT=sizeof(int),DOUBLE=sizeof(double),S80=sizeof(Str80),MY=sizeof(My)} TSizes;

typedef enum {ADD,LOOP,COUNT,FREE,GETAT,GET,REMOVEAT,REMOVE} Ops;

void *dynarray(char ***root,TSizes ts,Ops op,void *in,void *out)
{
  size_t d=0,s=in?ts?ts:strlen((char*)in)+1:0;
  char **r=*root;
  while( r && *r++ ) ++d;
  switch(op) {
  case ADD:   if( !*root ) *root=calloc(1,sizeof r);
              *root=realloc(*root,(d+2)*sizeof r);
              memmove((*root)+1,*root,(d+1)*sizeof r);
              memcpy(**root=malloc(s),in,s);
              break;
  case LOOP:  while( d-- ) ((void (*)(char*))in)((*root)[d]); break;
  case COUNT: return *(int*)out=d,out;
  case FREE:  if(r) {
                ++d; while( d-- ) realloc((*root)[d],0);
                free(*root);*root=0;
              } break;
  case GETAT: { size_t i=*(size_t*)in;
                if(r && i<=--d)
                  return (*root)[d-i];
              } break;
  case GET:   { int i=-1;
                while( ++i,d-- )
                if( !(ts?memcmp:strncmp)(in,(*root)[d],s) )
                  return *(int*)out=i,out;
                return *(int*)out=-1,out;
              }
  case REMOVEAT: { size_t i=*(size_t*)in;
                   if(r && i<=--d) {
                     free((*root)[d-i]);
                     memmove(&(*root)[d-i],&(*root)[d-i+1],(d-i+1)*sizeof r);
                     return in;
                   }
                 } break;
  case REMOVE: while( *(int*)dynarray(root,ts,GET,in,&d)>=0 )
                 dynarray(root,ts,REMOVEAT,&d,0);
  }
  return 0;
}

void outmy(Myp s)
{
  printf("\n%s,%s,%d",s->name,s->city,s->salary);
}

main()
{
  My    z[]={{"Buffet","Omaha",INT_MAX},{"Jobs","Palo Alto",1},{"Madoff","NYC",INT_MIN}};
  Str80 y[]={ "123","456","7890" };
  char **ptr=0;
  int x=1;

  /* precondition for first use: ptr==NULL */
  dynarray(&ptr,SPTR,ADD,"test1.txt",0);
  dynarray(&ptr,SPTR,ADD,"test2.txt",0);
  dynarray(&ptr,SPTR,ADD,"t3.txt",0);

  dynarray(&ptr,SPTR,REMOVEAT,&x,0); /* remove at index/key ==1 */
  dynarray(&ptr,SPTR,REMOVE,"test1.txt",0);

  dynarray(&ptr,SPTR,GET,"t3.txt",&x);
  dynarray(&ptr,SPTR,LOOP,puts,0);

  /* another option for enumerating */
  dynarray(&ptr,SPTR,COUNT,0,&x);
    while( x-- )
      puts(ptr[x]);
  dynarray(&ptr,SPTR,FREE,0,0); /* frees all mallocs and set ptr to NULL */

  /* start for another (user)type */
  dynarray(&ptr,S80,ADD,y[0],0);
  dynarray(&ptr,S80,ADD,y[1],0);
  dynarray(&ptr,S80,ADD,y[2],0);
  dynarray(&ptr,S80,ADD,y[0],0);
  dynarray(&ptr,S80,LOOP,puts,0);
  dynarray(&ptr,S80,FREE,0,0); /* frees all mallocs and set ptr to NULL */

  /* start for another (user)struct-type */
  dynarray(&ptr,MY,ADD,&z[0],0);
  dynarray(&ptr,MY,ADD,&z[1],0);
  dynarray(&ptr,MY,ADD,&z[2],0);
  dynarray(&ptr,MY,ADD,&z[0],0);
  dynarray(&ptr,MY,LOOP,outmy,0);
  dynarray(&ptr,MY,FREE,0,0);

  return 0;
}

A: There is sglib, which implements various lists,hashmaps and rbtrees in a generic fashion (i.e. by specializing over a type). There is also a fast sorting function for arrays:

*

*http://sglib.sourceforge.net/

A: qLibc implements a vector in pure C. The data structure allows it to store any type of object like (void *object) and it provides convenient wrappers for string, formatted string and integer types.
Here's a sample code for your idea.
qvector_t *vector = qvector(QVECTOR_OPT_THREADSAFE);
vector->addstr(vector, "Hello");
vector->addstrf(vector, "World %d", 123);
char *finalstring = vector->tostring(vector);

printf("%s", finalstring);
free(finalstring)
vector->free(vector);

for object type:
int a = 1, b = 2;
qvector_t *vector = qvector(QVECTOR_OPT_THREADSAFE);
vector->add(vector, (void *)&a, sizeof(int));
vector->add(vector, (void *)&b, sizeof(int));
int *finalarray = vector->toarray(vector);

printf("a = %d, b = %d", finalarray[0], finalarray[1]);
free(finalarray)
vector->free(vector);

Note) I made this sample code just for your reference, copying from its example code.
      it might have typo errors.
You can check out the Full API reference at http://wolkykim.github.io/qlibc/

A: I'm using the following macro implementation without problems so far. It isn't a complete implementation but grows the array automatically :
#define DECLARE_DYN_ARRAY(T) \
    typedef struct \
    { \
        T *buf; \
        size_t n; \
        size_t reserved; \
    } T ## Array;

#define DYN_ARRAY(T) T ## Array

#define DYN_ADD(array, value, errorLabel) DYN_ADD_REALLOC(array, value, errorLabel, realloc)

#define DYN_ADD_REALLOC(array, value, errorLabel, realloc) \
    { \
        if ((array).n >= (array).reserved) \
        { \
            if (!(array).reserved) (array).reserved = 10; \
            (array).reserved *= 2; \
            void *ptr = realloc((array).buf, sizeof(*(array).buf)*(array).reserved); \
            if (!ptr) goto errorLabel; \
            (array).buf = ptr; \
        } \
        (array).buf[(array).n++] = value; \
    }

To use you first write: DECLARE_DYN_ARRAY(YourType)
To declare variables you write DYN_ARRAY(YourType) array = {0}.
You add elements with DYN_ADD(array, element, errorLabel).
You access elements with array.buf[i].
You get the number of elements with array.n.
When done you free it with free(array.buf) (or whatever function you used to allocate it.)

A: glib provides an GArray type, which implements a dynamically growing array.  If you can use external 3rd party libraries, glib is almost always a good choice as "standard" library for C.  It provides types for all basic data structures, for unicode strings, for date and time values, and so on.

A: I usually roll my own code for purposes such as this, like you did. It's not particularly difficult, but having type safety etc. is not easily achievable without a whole OO framework.
As mentioned before, glib offers what you need - if glib2 is too big for you, you could still go with glib1.2. It's quite old, but doesn't have external dependencies (except for pthread if you need thread support). The code can also be integrated into larger projects, if necessary. It's LGPL licensed.

A: Personally, I prefer "Gena" library. It closely resembles stl::vector in pure C89.
It is comfortable to use because you can:

*

*Access vector elements just like plain C arrays: vec[k][j];

*Have multi-dimentional arrays;

*Copy vectors;

*Instantiate necessary vector types once in a separate module, instead of doing this every time you needed a vector;

*You can choose how to pass values into a vector and how to return them from it: by value or by pointer.

You can check it out here:
https://github.com/cher-nov/Gena


text:
Q: Endomorphism on $\mathbb{P}^n$ Suppose $f: \mathbb{P}^n \to \mathbb{P}^n$ be a surjective morphism and $D$ be a reduced divisor satisfying ${f^{-1}(D)}_{\text{red}}=D$. Is $f$ unramified outside $D$ ?

A: No. Take for instance
$$
f(x_0,x_1,\dots,x_n) = (x_0^d,x_1^d,\dots,x_n^d)
$$
and $D = \{x_0 = 0\}$.


text:
Q: C program How to get return value from other function by using switch statement So I am trying to do a program where it shows a menu and asks what will the user do. I am stuck in where I cant get the return value in case 1 and use it in case 5. I am only a beginner and need help.
This is what I have in my program.
#include <stdio.h>

int choice, arrayval, val;
char reply, y, n;

void menu()
{
printf("\n\n");
printf("MAIN MENU");
printf("\n\n");
printf("[1] - Store/Fill Array\n");
printf("[2] - Find and Replace\n");
printf("[3] - Display Frequency\n");
printf("[4] - Unique\n");
printf("[5] - Print\n");
printf("[0] - Print\n");
printf("Enter your choice: ");
scanf(" %s", &choice);
}

int storearray()
{
int arrayval[10];
int i;

for(i=0;i<10;i++)
{
    printf("Enter Value for Array[%d]", i);
    scanf("%d", &arrayval[i]);
}

return arrayval;
}

void printarr(arrayval)
{
int i;
for(i=0;i<10;i++)
{
    printf("Array[%d] %d\n", i, arrayval);
}
}

int main()
{
do
{
menu();
switch(choice)
{
case '1':
    storearray();
    main();
    break;
case '5':
    val = storearray();
    printarr(val);
    return 0;
    break;

default:
    printf("Invalid");
}

}
while (choice != 1,2,3,4,5);

printf("End of Program!");
return 0;
}

need help on how to get the value from storearray() and use it to print in printarr()

A: Here's a modified version of your code with the fixes mentioned in the comments of your question:
#include <stdio.h>
#include<stdlib.h>

char choice;
int *val;
char reply, y, n;

void menu()
{
    printf("\n\n");
    printf("MAIN MENU");
    printf("\n\n");
    printf("[1] - Store/Fill Array\n");
    printf("[2] - Find and Replace\n");
    printf("[3] - Display Frequency\n");
    printf("[4] - Unique\n");
    printf("[5] - Print\n");
    printf("[0] - Print\n");
    printf("Enter your choice: ");
    scanf(" %c", &choice);
}

int* storearray()
{
    int *arrayval=malloc(10*sizeof(int));
    int i;

    for (i = 0; i < 10; i++)
    {
        printf("Enter Value for Array[%d]", i);
        scanf("%d", &arrayval[i]);
    }

    return arrayval;
}

void printarr(int *arrayval)
{
    int i;
    for (i = 0; i < 10; i++)
    {
        printf("Array[%d] %d\n", i, arrayval[i]);
    }
}

int main(void){
    val=NULL;
    int inv=1;
    do
    {
        menu();
        switch (choice)
        {
        case '1':
            val=storearray(); //be sure to `free(val)` (if `val` is pointing to a malloc'ed memory) before you do `val=storearray()` or you'll lose the pointer and it'll result in a memory leak
            break;
        case '5':
            //I'd also recommend a check here to ensure `val` isn't NULL
            printarr(val);
            inv=0;
            break;
        default:
            printf("Invalid");
            inv=0;
            break;
        }
    } while (inv);
    printf("End of Program!");
    free(val);
    return 0;
}

Also, as chux mentioned in the comment:

"I am only a beginner and need help." --> Simple tip: enable all compiler warnings. Faster feedback than posting stack overflow.


text:
Q: Like query with alphanum string bindParam I´m new working with pdo statements and when I try to set a query like this in phpMyadmin sql console, it´s works fine:
SELECT name, number FROM client WHERE number LIKE '%30%'

Result:
|name|number|
|antonio|30857898H|
|andrés|30987454U|

But when I pass the params with the method bindParam() or the method bindValue() or with the type value like PDO::PARAM_STR or PDO::PARAM_INT, the behaviour is that the query stop in the first number, and don´t get the other characters. The cols are both 'char'...
This is my method:
function getQueryData($key,$i_query){

    require_once '../queryList.php';//get all the querys
//$key is an array like this $key[0][0] = ':number', $key[0][1] = '%30%'
    $this->consulta = $this->conInstance->prepare($gQuery[$i_query]);

    foreach ($key as $clave => $valor) {
        $this->consulta->bindParam($key[$clave][0], $key[$clave][1]);
        }
    $this->consulta->execute();

    $this->consulta->setFetchMode(PDO::FETCH_ASSOC);

    return $this->consulta;
    //Make the bucle on the system
}

Thaks a lot for the help in this comunity, the people here are fantastic

A: try isolate the param content in the like matching clause as
SELECT name, number FROM client WHERE number LIKE concat('%', '30', '%')

eg
SELECT name, number FROM client WHERE number LIKE concat('%', :your_param , '%')

or equivalent

A: With bind parameters you need pass whole string with '%'
query:
SELECT name, number FROM client WHERE number LIKE :your_param

code:
$value = 'some value';
$this->consulta->bindParam('your_param', '%'.  $value . '%');


text:
Q: primefaces toggle (command)button I'm trying to use a primefaces commandbutton as toggle button. My idea was to add a css class with the desired style, in this way:
<p:commandButton id="mybutton" onclick="toggleButton();"/>

javascript:
function toggleButton() {
        $(this).toggleClass("myCustomClass");
    return true;
}

css:
.myCustomClass{
 background-color: red;
}

For some reasons, this doesn't work. My supposition is that PF does some magic with button's style, and my class is added and right away removed. Some hint?

A: The reason why your style is not changed, may be that the <p:commandButton> makes an ajax request and updates parts of the view. (See Attribute update of the button.) Then the changes made by JavaScript are gone.
If you need to make an ajax request on click of the button, it may be best to bind the styleClass value to an attribute on a server side bean, e.g.
<p:commandButton styleClass="#{myBean.buttonEnabled ? '' : 'myCustomClass'}"
                 action="myBean.someAction()"...
                 update="@this" />

And in the action you can then toggle the variable.

A: Have you tried just to update the commandButton instead the whole form?
<p:commandButton id="my button" update="@this" onclick="toggleButton();"/>

But for other reasons... i just noticed that primefaces sometimes removes all css classes from a component in a very last step just to put their own classes again. So it is impossible to change a style class. But not in combination with a commandButton