text:
Q: How to display calendar view in Android? In my application I need to display calendar and some events on it, like on image below.

I've read this topic, but libs described there doesn't fit my needs. I've also found this lib: Extended Calendar View, but it works only on devices with api level 14 or higher while I need to support api level 10.
Maybe someone know some library for solving this problem? Any help will be highly appreciated.

A: i referred this link to create something like that link
/**
             * NOTE: YOU NEED TO IMPLEMENT THIS PART Given the YEAR, MONTH, retrieve
             * ALL entries from a SQLite database for that month. Iterate over the
             * List of All entries, and get the dateCreated, which is converted into
             * day.
             *
             * @param year
             * @param month
             * @return
             */
            private HashMap findNumberOfEventsPerMonth(int year, int month)
                {
                    HashMap map = new HashMap<String, Integer>();
                    // DateFormat dateFormatter2 = new DateFormat();
                    //
                    // String day = dateFormatter2.format("dd", dateCreated).toString();
                    //
                    // if (map.containsKey(day))
                    // {
                    // Integer val = (Integer) map.get(day) + 1;
                    // map.put(day, val);
                    // }
                    // else
                    // {
                    // map.put(day, 1);
                    // }
                    return map;
                }

In the above code create Hashmap which contains date. and replace if condition with this(Make changes according to ur needs)
if ((mEventsPerMonthMap != null) && (!mEventsPerMonthMap.isEmpty())) {
        Set<String> keys = mEventsPerMonthMap.keySet();
        for (String key : keys) {
            if (key.equals(theday + "/" + monthInNo+ "/" + theyear)
            && mEventsPerMonthMap.containsKey((String.format("%02d", Integer.parseInt(theday)))
            + "/"+ monthInNo+ "/" + theyear)) {
datewiseEventmap.put(theday + "/" + monthInNo+"/" + theyear,
                        (ArrayList<Appointment>)
                        mEventsPerMonthMap.get((String.format("%02d",Integer.parseInt(theday)))+ "/" + monthInNo+ "/" + theyear));}}

Changing each grid cell
if (datewiseEventmap != null && datewiseEventmap.size() > 0) {
            mNumEvents = (ArrayList<Appointment>) datewiseEventmap
                    .get(theday + "/" + monthInNo+ "/" + theyear);

            eventName.setText(sbf);

            eventName.setBackgroundResource(R.drawable.appointment_name_bg);
            //gridcell.setBackgroundResource(R.drawable.calender_details_description);
            eventCount.setVisibility(View.VISIBLE);
            //eventCount.setBackgroundResource(R.drawable.calender_details_description);
            if (mNumEvents.size() > 1) {
                eventCount.setVisibility(View.VISIBLE);
                eventCount.setText("+ " + String.valueOf(mNumEvents.size()));

            }


text:
Q: Display final docker compose When using multiple docker compose files, they will be merged into a final compose final before it will be used.
Is there any way of displaying this "final" compose file, to see how the different compose files are put together? I am looking for a dump command, instead of the usual up, stop, ... commands, but I do not find that in the documentation.
Is there any workaround for achieving the same result?

A: The command you are looking for is docker-compose config. Pass the same parameters you would to up/stop/etc to parse multiple files, and it will output the parsed and merged yaml with variables expanded.
See the docs for more details: https://docs.docker.com/compose/reference/config/

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ - Create Pythonwrapper to existing Library I need to write a python wrapper for an existing C++ Module. First I tested the procedere with this basic example (which now actually works fine):  C++ - Python Binding with ctypes - Return multiple values in function
Now I tried to change the setting: I want to use the existing lib instead of my single cpp file. I tried it with this:
g++ -c -I. -fPIC projectionWrapper.cpp -o projectionWrapper.o
g++ -shared -Wl,-soname,libproj.so
    -L./build/liborig_interface.a,./build/liborig_base.a
    -o libproj.so  projectionWrapper.o

I wanted to link against both .a files from the given library with the -L command. I don't get any errors on that, but when I try to import the module via ipython, I get this:
import myprojection    # I load libproj.so in this python file
OSError: ./libproj.so: undefined symbol: _Z29calibration_loadPKcjbP14camera_typetS2_

There is a function "calibration_load", as well a "camera_type" in the original framework. But I have no clue where the cryptic things in between come from.
Sorry for my vague explanation, I tried to explain it as good as possible, but a C++ Wrapper is not one of my topics where I feel "at home".

A: The problem is that you're not linking against the external library that you use in your C++ code; add -l<library> to your second g++ call.

A: g++ -shared projectionWrapper.o
    -L./build/base -L./build/interface
    -loriginterface -lorigbase
    -Wl,-soname,libproj.so
    -o libproj.so

did the job. Thanks for the hint that I actually didn't link the libraries as I only used the -L option.
Moreover the order of the options was wrong. I had to state "projectionWrapper.o" right at the beginning, as well as "-loriginterface" before "-lorigbase". This was answered here: "undefined reference" when linking against a static library
(complete name of the libs are: liboriginterface.a and liborigbase.a)


text:
Q: Moving a limit inside an infinite sum Is uniform convergence justification for moving a limit inside an infinite sum?
I'm trying to evaluate $$ \lim_{n \to \infty} n \int_{0}^{1} \ln(1+x^{n}) \ dx . $$
I found that it equals $$\displaystyle\lim_{n \to \infty} \sum_{k=1}^{\infty} (-1)^{k+1} \frac{n}{k+k^2n}.$$
Can I move the limit inside the infinite sum and conclude
$$ \lim_{n \to \infty} n \int_{0}^{1} \ln(1+x^{n}) \ dx = \sum_{k=1}^{\infty} \frac{(-1)^{k+1}}{k^{2}} = \frac{\pi^{2}}{12}?$$

A: You could also let $x^n = y$, which gives you
$$
n \int_0^1 \log(1+x^n)\,dx = \int_0^1 \frac{\log(1+y)}{y}\,y^{1/n}\,dy \longrightarrow \int_0^1 \frac{\log(1+y)}{y}\,dy,
$$
by the dominated convergence theorem.

A: Yes. Uniform convergence allows you to pass the limit inside the sum and inside the integral. The Theorem goes as follows:
Let $X\subseteq \mathbb{R}$, $a\in \bar{\mathbb{R}}$ be a limit point of $X$ (*), $f_k:X\to \mathbb{R}$. If the limit $\lim_{x\to a}f_k(x)$ exists and $\sum_{k=0}^{\infty}f_k$ converges uniformly then
\begin{equation}\lim_{x\to a}\sum_{k=0}^{\infty}f_k(x)=\sum_{k=0}^{\infty}\lim_{x\to a}f_k(x)\end{equation}
So in your case you need to show $\lim_{n\to \infty}(-1)^{k+1}\frac{n}{k+k^2n}$ for fixed $k$ exists (simple) and  $\sum_{k=0}^{\infty}(-1)^{k+1}\frac{n}{k+k^2n}$ converges uniformly for $n$. I suggest the Weierstrass M test:
If $\forall k\in  \mathbb{N}\; \sup_{x\in X}\left|f_k(x)\right|\le M_k$ and the series $\sum_{k=0}^{\infty}M_k$ converges then the series $\sum_{k=0}^{\infty}f_k$ converges uniformly.
In our case, for $x\ge 0$ and $k\ge 1$,
$$\left|f_k(x)\right|=\frac{x}{k+k^2x}\le \frac1{k^2}:=M_k$$
and so...
(*) $a$ may very well be infinite


text:
Q: Shortest subset sum of arr dynamic programming My goal is to find the shortest subset of an array that its sum is equal to target. I tried to use the following solution (with dynamic programming):
public static List<Integer> bestSum_efficient(int targetSum, int[] numbers) {
    return bestSum_efficient(targetSum, numbers, new HashMap<>());
}

public static List<Integer> bestSum_efficient(int targetSum, int[] numbers, Map<Integer, List<Integer>> map) {
    if (map.containsKey(targetSum)) {
        return map.get(targetSum);
    }
    if (targetSum == 0)
        return new ArrayList<>();
    if (targetSum < 0)
        return null;

    List<Integer> shortestCombination = null;
    for (int n : numbers) {
        List<Integer> remainedCombination = bestSum_efficient(targetSum - n, numbers,map);
        if (remainedCombination != null) {
            remainedCombination.add(n);

        if (shortestCombination == null || shortestCombination.size() > remainedCombination .size()) {
                shortestCombination = remainedCombination ;
            }
        }
    }
    map.put(targetSum, shortestCombination);
    return shortestCombination;
}

With this code I tried to run the following test:
System.out.println(bestSum_efficient(8, new int[]{1, 4, 5})); // [4,4]

I got: [4,1,4]
When I changed the content of the first if to the following, everything worked fine:
  for (int n : numbers) {
    List<Integer> remainedCombination = bestSum_efficient(targetSum - n, numbers,map);
    if (remainedCombination != null) {
        List<Integer> combination = new ArrayList<>();
        combination.add(n);
        combination.addAll(remainedCombination);

    if (shortestCombination == null || shortestCombination.size() > combination.size()) {
            shortestCombination = combination;
        }
    }
}

Why does creating a new combination list each in each iteration worked, while using the remainingCombination list that returned didn't?

A: After squeezing my brain for a while, I think that I have found the root cause of this issue.
In the first scenario:
        List<Integer> remainedCombination = bestSum_efficient(targetSum - n, numbers,map);
        if (remainedCombination != null) {
            remainedCombination.add(n);

We modify directly the list remainedCombination by adding n at the end of it. This will actually modify the entry of the HashMap that we use for memoization, when the function bestSum_efficient returns the saved entry via the lines:
    if (map.containsKey(targetSum)) {
        return map.get(targetSum);
    }

as in this situation remainedCombination will be a reference to map.get(targetSum), so doing remainedCombination.add(n); is the equivalent of doing map.get(targetSum).add(n);
However we only want to modify the entries of the HashMap at the end of the bestSum_efficient function if we find a shortest way to reach the target sum and not directly in the for loop before checking the length condition  if (shortestCombination == null || shortestCombination.size() > remainedCombination .size()) {
In the 2nd (working) example, we create a new temporary ArrayList
        List<Integer> combination = new ArrayList<>();
        combination.add(n);
        combination.addAll(remainedCombination);

before adding n there. This will therefore not affect the HashMap used for the memoization, that will only be modified just before the return of the function:
    map.put(targetSum, shortestCombination);
    return shortestCombination;


text:
Q: Programmatically set the arrow tip of a popup I am missing the right terminology thus find it hard to Google / search for a solution -
nevertheless, I want to have the pointing arrow of a popup view pointing to different locations, take a look at the following image to see what I am talking about

questions

*

*What is Apple's name / term of this element

*How does one programmatically change it's position

*Is this element supported by the SDK itself as an element and if state where

A: You want the popoverArrowDirection property of your UIPopoverController. Set it to one of the UIPopoverArrowDirection values.
You can also specify the allowed direction in either of these functions for showing the popover:
presentPopoverFromRect:inView:permittedArrowDirections:animated:
presentPopoverFromBarButtonItem:permittedArrowDirections:animated:

A: try this it might help you.....
[popoverController presentPopoverFromRect:CGRectMake(375, 230.0, 0.0, 0.0) inView:self.view  permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];


text:
Q: Query between two intervals of time In my app I have Clients and Professionals. A professional can set his availability of work, my Availability model has "start_time", "end_time", they are time without time zone.
So a client wants to hire a professional that is available at 20:00 to 22:00 for example.
How can I query that?

A: It sounds like you have two input values, and you want to make sure the time block they delineate fits inside a second block, delineated by the start_time and end_time attributes of your model. I would think this would be as simple as
Professional.joins(:availability).where('start_time <= :start AND end_time >= :end', :start => first_input, :end => second_input)

Depending on your model (multiple Availabilities per Professional, for instance) there might be some additional complexity, though.


text:
Q: xchat Connection failed. Error: An attempt was made to access a socket in a way forbidden by its access permissions Idk the problem if anyone of you can help me then I'll be thankful to you.
As I do regularly I open my xchat (irc client) and then when I select frrenode to connect then I am getting this crappy error.
I try to connect with other irc to and I got same error.
I just checked my network setting on irc and everything is fine over there idk wtf is going on .
Error shown below
Quote: * Looking up irc.freenode.net
* Connecting to irc.freenode.net (213.232.93.3) port 6667...
* Connection failed. Error: An attempt was made to access a socket in a way forbidden by its access permissions


text:
Q: ArrayFire CPU, will it run out of memory due to late GC? I am not entirely sure how ArrayFire manages memory on the RAM when using CPU mode. Based on task manager observation, it appears the device memory on RAM is not released right away, it looks like there is a GC stage.
Is this true?
What happen if I wanted to allocate a lot of RAM when GC hasn't release the device memory (RAM)? Will I run out of RAM? Or will that triggers GC somehow?
I am running into memory issues when allocating host memory (not device memory) and I still trying to figure out what's wrong. In the meantime, does GC really exists on CPU mode and will it cause out of memory if GC is triggered too late? And how should I fix this?
Thank you

A: ArrayFire will cache allocations and reuse them for later operations. Based on some heuristics or if an allocation fail, ArrayFire will call the garbage collector. You can manually run garbage collector by calling deviceGC which will release unlocked(unused) memory.


text:
Q: How to limit depth of reply comments in laravel I can create unlimited reply comment  by recursively. This thing can be terrible because my web looks ugly.
I want the user just can reply the comment maximum 3 depth of reply comments so if the depth has more from the maximum depth the comment not create nesting again.
Here is my code that I can try so far, in blog.detail.php to show comment
@include('nested.replies', ['comments' => $post->comments, 'post_id' => $parameter, 'depth' => 0])

and in replies.php
@foreach($comments->sortByDesc('created_at') as $comment)

<?php
$parameter = Hashids::connection()->encode($post->id);
$parameter2 = Hashids::connection()->encode($comment->id);
?>

                    {{ $comment->user->name }}
                    {{ $comment->date }}

{{ $comment->body }}

                    @if(Auth::guard('member')->check() && Auth::guard('member')->user()->active == 1)
                        @if(Auth::guard('member')->user()->isBan == 1)

                            Blocked
                        @else
                            {!! Form::open(['method' => 'DELETE','route' => ['comment.destroy', $comment->id]]) !!}
                            {!! Form::submit('delete', ['onclick' => 'return confirm("Are you sure?");','class' => 'btn btn-danger btn-xs pull-right'])!!}
                            {!! Form::close() !!}

                            Reply
                            {!! Form::open([
                                'route' => ['reply.add', $post->slug],
                                'class' => 'showActionComment',
                                'data-parsley-validate'])
                            !!}

                            @csrf

has('comment_body') ? 'has-error': '' }}">
                                {!! Form::textarea('comment_body', null, [
                                    'name'        => 'comment_body',
                                    'class'       => 'form-control',
                                    'placeholder' => 'Write Something.. ',
                                    'required', 'minlength="4"'])
                                !!}
                                @if($errors->has('comment_body'))
                                    {{$errors->first('comment_body')}}
                                @endif

                                {!! Form::hidden('post_id', $parameter) !!}
                                {!! Form::hidden('comment_id', $parameter2) !!}

                                <input type="submit" id="postBtn" value="Add Comment" />
                                <input type="button"  class="btn1 btn-warning" value="Hide" />

                            {!! Form::close() !!}
                        @endif
                    @endif

      @if($depth < 3)

                @include('nested.replies', ['comments' => $comment->replies, 'depth' => $depth + 1])

        @endif

@endforeach

we can see the replies on here
@if($depth < 3)

            @include('nested.replies', ['comments' => $comment->replies, 'depth' => $depth + 1])

@endif

I think this code not working properly, because it still executeS nesting comment..


text:
Q: what is numpy.ndarray without column in python? I saw this sample:
from sklearn import cross_validation
from sklearn import metrics
from sklearn import svm
from sklearn import datasets
iris = datasets.load_iris()
clf = svm.SVC(kernel='linear', C=1)
predicted = cross_validation.cross_val_predict(clf, iris.data,iris.target, cv=10)
metrics.accuracy_score(iris.target, predicted)

So I wrote:
from sklearn import cross_validation
from sklearn import metrics
from sklearn import svm
clf = svm.SVC(kernel='linear', C=1)
train_data_input=train_df.iloc[:,1:].values
train_data_output=train_df[[0]].values
predicted = cross_validation.cross_val_predict(clf, train_data_input,train_data_output, cv=10)
metrics.accuracy_score(train_data_output, predicted)

but I got this error:
  IndexError: too many indices for array.
I think, this problem is relate to type of "train_data_output".
whilst I see these types:
type(train_data_output)
Out[32]: numpy.ndarray

type(iris.target)
Out[33]: numpy.ndarray

But in "Spyder>Variable explorer window" I can see a difference, in "size" column it show that my variable has a column like this (891,1), but in sample variable there isn't any column like this (150,)!!!
train_data_input.shape
Out[34]: (891, 12)

train_data_output.shape
Out[35]: (891, 1)

predicted.shape
Out[36]: (150,)

iris.target.shape
Out[37]: (150,)

By comment @shanmuga I solve my problem in this way:
train_data_output=np.reshape(train_data_output, (891,))

But how could I extract a column from a datafram that don't need this command?


text:
Q: matrices forms a basis for vector space 2x2 $\begin{bmatrix}0&1\\2&3\end{bmatrix}$
$\begin{bmatrix}3&4\\5&6\end{bmatrix}$
$\begin{bmatrix}7&8\\9&10\end{bmatrix}$
$\begin{bmatrix}11&12\\13&14\end{bmatrix}$
Show that the 4 matrix forms a basis for vector space 2x2

A: Hint:
Algebraically, this is the same as showing that the vectors
$$
\begin{bmatrix}0\\1\\2\\3\end{bmatrix},\ \begin{bmatrix}3\\4\\5\\6\end{bmatrix},\ \begin{bmatrix}7\\8\\9\\10\end{bmatrix},\ \begin{bmatrix}11\\12\\13\\14\end{bmatrix}
$$
(top left, top right, bottom left, bottom right) form a basis for $\mathbb{R}^4$.
(I will note, however, that as written: this is false. If the matrices are $A_1,A_2,A_3,A_4$ (respectively), then $x_1=4$, $x_2=1$, $x_3=-13$, and $x_4=8$ makes $\sum x_iA_i$ the $0$-matrix, for instance.)

A: A basis for a vector space is by definition a spanning set which is linearly independent.
Here the vector space is 2x2 matrices, and we are asked to show that a collection of four specific matrices is a basis:
$$ \left\{\begin{bmatrix}0&1\\2&3\end{bmatrix}, \begin{bmatrix}3&4\\5&6\end{bmatrix},
 \begin{bmatrix}7&8\\9&10\end{bmatrix}, \begin{bmatrix}11&12\\13&14\end{bmatrix} \right\} $$
To be a spanning set means every element of the vector space can be expressed as a linear combination (of finitely many) of elements of the given set.  Here it means to show for any 2x2 matrix $\begin{bmatrix}w&x\\y&z\end{bmatrix}$ there exist scalar coefficients $a,b,c,d$ such that:
$$ \begin{bmatrix}w&x\\y&z\end{bmatrix} = a \begin{bmatrix}0&1\\2&3\end{bmatrix} + b \begin{bmatrix}3&4\\5&6\end{bmatrix} + c \begin{bmatrix}7&8\\9&10\end{bmatrix} + d \begin{bmatrix}11&12\\13&14\end{bmatrix} $$
To be linearly independent means that zero can be expressed as a linear combination (of finitely many) of elements of the given set uniquely by using zero coefficients, i.e. in the present case that:
$$ \begin{bmatrix}0&0\\0&0\end{bmatrix} = a \begin{bmatrix}0&1\\2&3\end{bmatrix} + b \begin{bmatrix}3&4\\5&6\end{bmatrix} + c \begin{bmatrix}7&8\\9&10\end{bmatrix} + d \begin{bmatrix}11&12\\13&14\end{bmatrix} $$
implies $a=b=c=d=0$.
It turns out, as Nicholas R. Peterson has already reported, that neither of these conditions is true.  The four given vectors do not form a basis for the vector space of 2x2 matrices.  (Some other sets of four vectors will form such a basis, but not these.)
Let's take the opportunity to explain a good way to set up the calculations, without immediately jumping to the conclusion of failure to be a basis.  The spanning set and linearly independent properties are easily combined into a method for checking if a finite set is a basis, by formulating a system of linear equations with unknown coefficients.  If the systems above (which differ only in the "given" matrix on the left hand side) are multiplied out to determine the four separate entries of the results on the right hand side, we see that the first condition (spanning) requires us to solve:
$$ 0a + 3b + 7c + 11d = w $$
$$ 1a + 4b + 8c + 12d = x $$
$$ 2a + 5b + 9c + 13d = y $$
$$ 3a + 6b + 10c + 14d = z $$
for any possible $w,x,y,z$, while the second condition (linear independence) requires us to show the homogeneous problem $w=x=y=z=0$ has a unique (trivial) solution.  Therefore treating the above linear system will tell us everything we want to know about whether the four vectors form a basis.
Presumably the Reader is familiar with solving such systems by elimination, either using the simple expedient of substitution of variables or the more systematic method of putting an augmented matrix representing the system into reduced row echelon form.  We take a middle path, of leaving the system in an equational form but performing the addition/subtraction/scaling of equations just as someone using elementary row operations might proceed.
To begin, subtract the top equation from each the three equations below it:
$$ 0a + 3b + 7c + 11d = \;w\; $$
$$ 1a + 1b + 1c + 1d = x-w $$
$$ 2a + 2b + 2c + 2d = y-w $$
$$ 3a + 3b + 3c + 3d = z-w $$
Now factor out the 2 and 3 respectively from the last two equations:
$$ 0a + 3b + 7c + 11d = \;w\; $$
$$ 1a + 1b + 1c + 1d = x-w $$
$$ 1a + 1b + 1c + 1d = \frac{y-w}{2} $$
$$ 1a + 1b + 1c + 1d = \frac{z-w}{3} $$
We begin to see that these equations cannot always be solved, because the last three left hand sides will always be equal, but the values of $w,x,y,z$ may not give the last three right hand sides as equal!  Let's take the next step and subtract the second equation from the last two:
$$ 0a + 3b + 7c + 11d = \;w\; $$
$$ 1a + 1b + 1c + 1d = x-w $$
$$ 0a + 0b + 0c + 0d = \frac{y-w}{2} - (x-w) $$
$$ 0a + 0b + 0c + 0d = \frac{z-w}{3} - (x-w) $$
Can we always find a solution to these equations?  No, because we can pick values for $w,x,y,z$ that make the right hand sides in either of the last two equations nonzero while any choice of $a,b,c,d$ will only give a left hand side there of zero.  For example we might take $x=1$ and $w=y=z=0$, so the right hand sides of the last two equations are $-1$.  The system is then inconsistent, since $0 \neq -1$.
With a little thought we can also see that the four vectors (matrices) are not linearly independent.  That is some choice of $a,b,c,d$ other than simply $a=b=c=d=0$ will allow us to get all zeros on the right hand sides (since now $w=x=y=z=0$ is stipulated):
$$ 0a + 3b + 7c + 11d = 0 $$
$$ 1a + 1b + 1c + 1d = 0 $$
$$ 0a + 0b + 0c + 0d = 0 $$
$$ 0a + 0b + 0c + 0d = 0 $$
We really only have two equations (the first two of our last system) to determine four unknowns, and the Reader should be familiar with the fact that this is not possible for linear equations.  If a particular nontrivial choice of $a,b,c,d$ is desired, let $c=1$ and $d=0$ in the those two equations, and work out that $b=-\frac{7}{3}$ and $a=\frac{4}{3}$.  So $a=b=c=d=0$ is not the only way to express the zero 2x2 matrix as a linear combination of the four vectors.


text:
Q: Relation between Riemann integrable and Lebesgue integrable functions Let $f$ be Riemann integrable function and $g$ be Lebesgue integrable function on $[0,1]$. If $\int_{0}^{1} |f-g| = 0$, then what we can say about $g$ i.e. whether $g$ will be Riemann integrable or not?
I feel $g$ will be Riemann integrable, because if $g$ is not Riemann integrable that means set of discontinuities of $g$ must have non zero measure. But from  $\int_{0}^{1} |f-g| = 0$, we can deduce that $f$ and $g$ are equal almost everywhere. I want to verify whether I am thinking in right direction or not. Please help me to figure out this problem, thanks in advance.

A: No, this is not right. Consider $f=0$ and $g=1_\mathbb{Q}$. In particular, Riemann integrability requires that for almost all $x$, $g$ is continuous in $x$. This is not the same as being equal to a continuous function almost everywhere.
The difference is clear here: $g$ is equal to the continuous function $0$ a.e., but it is actually continuous nowhere.

A: If $f\colon[0,1]\longrightarrow\Bbb R$ is the null function and if $g\colon[0,1]\longrightarrow\Bbb R$ is $1$ on the rationals and $0$ otherwise, then$$\int_0^1|f-g|=0,$$but $g$ is not Riemann-integrable.


text:
Q: TA-Lib using TA_INTEGER_DEFAULT and TA_REAL_DEFAULT in VB.NET 2010 VB.NET 2010 below is working. But I need to use default values as stated in TA-Lib documentation: TA_INTEGER_DEFAULT or TA_REAL_DEFAULT for optional parameters. How I can use that in coding?
Currently I assign values manually (need to know what are the values).
Public Sub CalcMACD()
        ' CALCULATE allocationSize
        Dim lookback As Integer = TicTacTec.TA.Library.Core.MacdLookback(optInFastPeriod, optInSlowPeriod, optInSignalPeriod)
        Dim temp As Integer = Math.Max(lookback, startIdx)
        If (temp > endIdx) Then
            allocationSize = 0                    ' No output
        Else
            allocationSize = endIdx - temp + 1
        End If

        optInFastPeriod = 12                                 ' Set optional values <==== HOW TO USE TA_INTEGER_DEFAULT
        optInSlowPeriod = 26                                 ' Set optional values <==== HOW TO USE TA_INTEGER_DEFAULT
        optInSignalPeriod = 9                                ' Set optional values <==== HOW TO USE TA_INTEGER_DEFAULT

        Dim outMACD As Double()                                                       ' Declare output variable type
        ReDim outMACD(allocationSize)
        Dim outMACDSignal As Double()                                                 ' Declare output variable type
        ReDim outMACDSignal(allocationSize)
        Dim outMACDHist As Double()                                                   ' Declare output variable type
        ReDim outMACDHist(allocationSize)

        ' the calculation
        Dim res As TicTacTec.TA.Library.Core.RetCode = TicTacTec.TA.Library.Core.Macd(startIdx, endIdx, openPrice, optInFastPeriod, optInSlowPeriod, optInSignalPeriod, outBegIdx, outNBElement, outMACD, outMACDSignal, outMACDHist)

        ' Add result column to Datagridview
        ' #1 add column to Datagridview1
        DataGridView1.ColumnCount = DataGridView1.ColumnCount + 3
        Dim columnID As Integer = DataGridView1.ColumnCount - 3
        ' #2 define column header
        DataGridView1.Columns(columnID).HeaderText = "MACD"
        DataGridView1.Columns(columnID + 1).HeaderText = "MACD Signal"
        DataGridView1.Columns(columnID + 2).HeaderText = "MACD Histogram"
        '#3 insert values to column
        For i As Integer = startIdx To endIdx
            DataGridView1(columnID, i).Value = outMACD(i)
            DataGridView1(columnID + 1, i).Value = outMACDSignal(i)
            DataGridView1(columnID + 2, i).Value = outMACDHist(i)
        Next
End Sub

A: Public Sub CalcMACD(Optional ByVal optInFastPeriod As Integer = TA_INTEGER_DEFAULT, Optional ByVal optInSlowPeriod As Integer = TA_INTEGER_DEFAULT, Optional ByVal optInSignalPeriod As Integer = TA_INTEGER_DEFAULT)

    ' CALCULATE allocationSize
    Dim allocationSize As Integer = 0
    Dim lookback As Integer = TicTacTec.TA.Library.Core.MacdLookback(optInFastPeriod, optInSlowPeriod, optInSignalPeriod)

    Dim temp As Integer = Math.Max(lookback, startIdx)
    If (temp < endIdx) Then
        allocationSize = endIdx - temp + 1
    End If

    ' Declare output variables
    Dim outMACD(allocationSize) As Double
    Dim outMACDSignal(allocationSize) As Double
    Dim outMACDHist(allocationSize) As Double

    ' the calculation
    Dim res As TicTacTec.TA.Library.Core.RetCode = TicTacTec.TA.Library.Core.Macd(startIdx, endIdx, openPrice, optInFastPeriod, optInSlowPeriod, optInSignalPeriod, outBegIdx, outNBElement, outMACD, outMACDSignal, outMACDHist)

    ' Add result column to Datagridview
    ' #1 add column to Datagridview1
    DataGridView1.ColumnCount = DataGridView1.ColumnCount + 3
    Dim columnID As Integer = DataGridView1.ColumnCount - 3
    ' #2 define column header
    DataGridView1.Columns(columnID).HeaderText = "MACD"
    DataGridView1.Columns(columnID + 1).HeaderText = "MACD Signal"
    DataGridView1.Columns(columnID + 2).HeaderText = "MACD Histogram"
    '#3 insert values to column
    For i As Integer = startIdx To endIdx
        DataGridView1(columnID, i).Value = outMACD(i)
        DataGridView1(columnID + 1, i).Value = outMACDSignal(i)
        DataGridView1(columnID + 2, i).Value = outMACDHist(i)
    Next
End Sub


text:
Q: How to verify if method was called with set of specified elements in Spock? I have a test in Spock:
def repository= Mock(Repository)

@Subject
def service = new Service(repository)

def "test"() {
  given:
  def results = [ /* does not matter */ ]

  def element = XYZ

  when:
  def found = service.findByElement(element)

  then:
  1 * repository.findByElements(_ as Set) >> results
}

which is working properly. But I would like to verify if repository.findByElements method is taking one element set with our specific element. How to achieve this?
Neither this:
1 * repository.findByElements([element] as Set) >> results

nor this:
1 * repository.findByElements({ assert it == [element] as Set }) >> results

does not work.

A: You can use an argument constraint that expects a closure representing a predicate. It looks similar to your second use case - the only difference is that there is no assert keyword needed (predicate has to return a boolean value). Variable it holds the argument value that your mocked method retrieves while being called, so you can create a predicate based on passed value.
def repository= Mock(Repository)

@Subject
def service = new Service(repository)

def "test"() {
    given:
    def results = [ /* does not matter */ ]

    def element = new Element("XYZ")

    when:
    def found = service.findByElement(element)

    then:
    1 * repository.findByElements({ it == [element] as Set }) >> results
}


text:
Q: Dhcp server on windows 2008r2 gives this error: "unable to determine the dhcp server version" Hi i have two dhcp server on my lan and each of them is running on a dc (windows 2008r2).
i'd like to manage both of the dhcp server from the command line with the netsh command by domain\administrator as user but i'm unable to do that on the remote host because it gives me this error :
unable to determine the dhcp server version

althought it works on local, i checked the firewall policy both on local and remote and they look fine.
do you have an idea on how to fix that?
thank you in advance


text:
Q: Ruby on rails -- Jquery not submiting put request before another post request I basically want to click a button and then submit a form when the user clicks another button. The form gets submitted but the button doesn't get clicked.
Method in the controller (put):
def set_everything
    user.update_column(:everything_set, true)
end

And then I have a form:
<%= form_tag("http://someotherwebsite.com/post_method", method: :post, id:"form")%>
     <%= some_field %>
     <button type="button" id="form-button">Done</button>
<% end %>

And then on the same view I also have another link_to:
<%= link_to set_everything_path, method: :put, id:"set-everything-button", style:"display:none" %>

My Jquery code:
$(document).ready(function(){
   $('#form-button').click(function(){
     $('#set-everything-button').trigger('click');
     setTimeout(function(){ $('form').submit();}, 2000);
   });
});

Now I have also tried using a button_to instead of link_to but it still doesn't get clicked and when I try it manually it works just fine.

A: Put the target url in a data attribute on the button:
<button type="button" id="form-button" data-trigger-url="<%= set_everything_path %>">Done</button>

Send the PUT request directly in your click handler:
$(document).ready(function(){
   $('#form-button').click(function(event){
     event.preventDefault();
     var form = $(this).closest('form');
     var url = $(this).data('trigger-url');
     $.ajax({
       url: url,
       method: 'PUT',
       dataType: 'html',
       success: function(){
         form.submit()
       }
     })
   });
});

Don't forget to send back 200 (OK) response from the controller action so that the javascript runs the success handler (and thus submits the form):
def set_everything
  user.update_columns(everything_set: true)
  head :ok, content_type: "text/html"
end


text:
Q: Local installation of gcc on CentOS I would like to know if it is possible to install gcc as a "local installation" on my home directory?  Thanks!
I am running CentOS 5.5 and exploring the possibility of installing gcc 4.2.* in my home directory btw.
~Susanth

A: try this: yum install gcc
If you're going to compile from source you'll also want to have kernel-devel installed...
yum install kernel-devel

A: Short Ans : You need a sysadmin access if you are installing any app in Linux but there are ways to tweak it like -
Using sudo
$sudo make install

Using a prefix
./configure --prefix=$HOME/install

Creating a private RPM database and installing from it (though for gcc I doubt it should work)
ref - http://www.nordugrid.org/documents/rpm_for_everybody.html


text:
Q: Can't mount .obb file (state = 21) on Meizu m3 note I've met with another strange issue with APK Expansion files (.obb-files). My expansion file mounts fine on all my test devices:

*

*Sony Xperia Z1 Compact (API 22)

*Sony Xperia Z1 Ultra (API 22)

*LG Nexus 5X (API 23)

*LG Nexus 4 (API 17)

I've created encrypted .obb file with jobb-utilite:
jobb -o obb-filename -d files-dir -k password -pn applicationId -pv versionCode
In my app I read .obb file with following code:
public void initialize(final Context context) {
    final StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
    final File mainObbFile = getMainObbFile();

    final OnObbStateChangeListener listener = new OnObbStateChangeListener() {
        @Override
        public void onObbStateChange(String path, int state) {
            super.onObbStateChange(path, state);
            if (state == OnObbStateChangeListener.MOUNTED) {
                // work with obb file
            } else {
                throw new RuntimeException("OnObbStateChangeListener::onObbStateChange - can't mount .obb file (state = " + state + ").");
            }
        }
    };

    final String key = BuildConfig.MAIN_XAPK_KEY;
    if (storageManager.isObbMounted(mainObbFile.getAbsolutePath())) {
        // work with obb file
    } else if (!storageManager.mountObb(mainObbFile.getAbsolutePath(), key, listener)) {
        throw new RuntimeException("Can't create listener for mounting .obb file.");
    }
}

And everything works fine. But on Meizu m3 note (API 22) we got strange error: "OnObbStateChangeListener::onObbStateChange - can't mount .obb file (state = 21)".
Previously, I have met with this problem and it was solved with another generation of .obb-file. But in this case it did not help.
Also, I've tried to generate .obb file with fixed jobb tool (https://github.com/monkey0506/jobbifier.git), and it doesn't work.
May be anyone knows, what's wrong, why sometimes .obb files doesn't work on some devices?..
UPDATE
Also, I've checked mounting of non-encrypted .obb file on Meizu. It works.
Thanks in advance.

A:
I had the same problem, and i figured out that many times Error 21 is
  caused by Linux Files Permissions over the obb, and the problem is
  that Android cannot have access to it so the StorageManager launches
  Error 21. When you create the .obb file, change permissions and user
  group to the file, something like:

$chmod 664 <obb-filename>.obb
$chown user:group <obb-filename>.obb

Then try again, worked for me.

A: I got same problem with Error code 21 i removed the -k password from:
jobb -o obb-filename -d files-dir -pn applicationId -pv versionCode

and passed null in mountObb method instead password
storageManager.mountObb(mainObbFile.getAbsolutePath(), null, listener)

I don't know why jobb not work with password, if someone know please share.


text:
Q: I understand why 0 prints 0, and foo! but why doesn't 1 or 2 print anything? for variable in range(20):
    if variable % 4 == 0:
        print variable
    if variable % 16 == 0:
        print 'Foo!'

A: do you mean 0 behind the equal mark or as a value of variable?
As a value of variable it can't print anything because neither 1 or 2 are a multitude of 4 or 16. As the second part of the equation, it should print something for variable == (1 || 2).
0 is a multitude of any number as anything * 0 == 0
Hope I got your question right.


text:
Q: Why did Edmure Tully agree to this plan? Edmure was set free by Jaime. He could have just held the Riverlands.
Yet he chose to go back in his cage and betray his own men to ensure that his child could live.
That's kind of idiotic isn't it?
His son, whom he never saw, is  Walder Frey's grandson. He shouldn't fear that they will murder his son. Yet he takes a much greater risk and forgoes his freedom just so Jaime doesn't murder his son.
If I were him, I'd just enjoy my freedom and father more sons on other women than Roslin Frey.

A: There are a few incorrect assumptions in your question, so I will address them here:

Edmure was set free by Jaime.

Edmure was not set free by Jaime. Jaime had ordered (off-screen) for Edmure to re-enter Riverrun and open the gates from the inside.

Jaime meets Edmure in the tent where he is being imprisoned and implores him to appeal to his uncle to surrender Riverrun.
  ...Jaime offers to reunite him with his wife and son and have him live out his days in gentle imprisonment as a hostage at Casterly Rock.[1]

He didn't choose any of this, he was forced to do it at gun-point sword-point.

That's kind of idiot isn't it?

No it isn't; he's lost everything - his father, his sisters (Catelyn and Lysa), his lands and his home. The only thing left in his life are his wife (whom he actually liked), and his son whom he's never met. He's chosen to defend them and their lives over the lands of Riverrun and his uncle, the Blackfish.

He shouldn't fear that they will murder his son.

Yes he should. In Westeros, family, heritage and legacy are all that matters. His son, whether Frey or not is his only chance at surviving the world and having a meaningful life. In fact, the Tully words are "Family, Duty, Honour"[2], so keeping his family safe is his utmost duty.

If I were him, I'll just enjoy my freedom and father more sons on other women than Roslin Frey.

Well, he's not you. He has chosen to save his family and to give them a chance at a peaceful life. Not everyone is as frivolous with their family tree as Walder Frey. Walder has many children which he's fathered by many women[3]. If Edmure was to simply drop his wife and child and "just make new ones", he'd be no better than Walder!

A: Blackfish's quest to find a worthy death
Blackfish was fighting for an honourable death which would be worthy of a Tully of Riverrun. He had no wife or children to consider. He had absolutely nothing to lose which is why he was defiant despite being offered peace by Jaime. He never wanted peace, he just wanted death for himself. That's the only thing the old man wanted.
Edmure and the quest to keep Tully name alive
Edmure however was married and had a Child. He and his child are future of House Tully. If they die, House Tully dies with them because Brynden is unlikely to reproduce given his celibacy, his advanced age and him being besieged. If House Tully dies, what does it matter who holds Riverrun?
But if they live, the hope of one day getting Riverrun back is alive as well. Edmure chose that instead of going down as the heroic last Lord of Riverrun.
Walder Frey's kinship to Edmure's kid
You are saying Walder Frey would not kill his grandson but you are forgetting something, It wasn't the Freys who were calling the shots, it was the Lannisters. Walder Frey would not be able to defy a command by Jaime to hand over the child. It would be better for Walder anyways because the babe would be a Tully claimant to the Riverlands and with him dead, Frey hold could be more secure.
The hopeless situation
Jaime had the numbers to take the castle by storming its walls. He made it clear to Edmure that he did not care how many men died taking the Castle but eventually he will take the Castle. So what's the point of getting your child killed and then getting yourself killed anyways? That's something that would be kind of silly. Abandoning a besieged castle, surrounded by enemies with no prospect of a relief or victory is something which I would call smart.

A: The reason that is looks extremely awful on Edmure's part is that the series completely messed up that part. What happened in the books is much better to understand. That's why even though you don't have the asoiaf tag, I'll quote the books.
Like in the show, Freys had Edmure on the gallows each day from dawn till dusk.
That part is the same, and Jaime first made sure Freys stop acting like it.
Blackfish could resist to the siege.
This part is different. Due to its location, Riverrun is easy to defend. And in fact, Blackfish did not get it from the Freys, he was already there so he had plenty of time to obtain provisions for a long siege, approximately for two years. With winter approaching, he had a chance of holding the fort.
Jaime threatened Edmure to yield the castle.

 "I will assault the castle tomorrow. First I will send the riverlords. You will first be killing your brothers you fought together."

Except Lord Blackwood who did not surrender and except Lord Bracken who were besieging Lord Blackwood all riverlords were there in the siege.

 "Then I will send the Freys. I have no shortage of them."

Frey army was largely intact. They withdrew after Crag has fallen.

 "Only after the last Frey is dead, you'll be fighting against Lannisters."

I think he brought an army around 4000. Soldiers from the Westerlands constituted roughly half of the army.
So, Edmure realized how impossible the situation is. Jaime offered him an exile in Lannisport Casterly Rock, not a dungeon cell in the Crossing. He went in there to negotiate a truce with the Blackfish. But he did not attempt to capture Blackfish.

 When Jaime asked where the Blackfish is, Edmure did not respond. After Jaime threatened him with a cell in Lannisport Casterly Rock, he responded "Fish can swim, we opened a gate in the water and he swim through it."

So, as you can see, neither Edmure is a broken idiot nor Blackfish is a romantic fool.


text:
Q: Can I programmatically add a qualifier to a bean? I am registering transaction managers in my code, I would normally use annotation based configuration but as I don't know until runtime how many data sources (and hence transaction managers) there will be, I have to programmatically register these, as follows:
private final void registerTransactionManagerBean(final DataSource dataSource, ConfigurableApplicationContext context) {

    String transactionManagerName = this.getName() + "-transactionManager";

    context.getBeanFactory().registerSingleton(transactionManagerName, new DataSourceTransactionManager(dataSource));

    LOG.info("Registering transaction manager under name : " + transactionManagerName);
}

Assuming this.getName() returned 'mydb', I originally expected to be able to qualify a transaction manager like this:
@Transactional("mydb-transactionManager")

What I've realised however is the value of that annotation refers to the qualifier and not the name. I did a quick test by declaring a bean as below and it works:
@Bean
@Qualifier("mydb-transactionManager")
public PlatformTransactionManager test() {
    return new DataSourceTransactionManager(new EmbeddedDatabaseBuilder().build());
}

My question is, is there a way I can programmatically add a qualifier when registering a bean?
UPDATE
I've worked this out, I'm falling foul of this problem (in BeanFactoryAnnotationUtils:isQualifierMatch):
catch (NoSuchBeanDefinitionException ex) {
// ignore - can't compare qualifiers for a manually registered singleton object
}

I am manually registering my transaction manager bean so I presume this is why I'm stuck. I'm not really sure what options that gives me apart from to not programmatically register transaction managers as a runtime thing sadly.

A: I've worked this out, I'm falling foul of this problem:
catch (NoSuchBeanDefinitionException ex) {
// ignore - can't compare qualifiers for a manually registered singleton object
}

I am manually registering my transaction manager bean so I presume this is why I'm stuck. I'm not really sure what options that gives me apart from to not programatically register transaction managers as a runtime thing sadly.
Raised as a JIRA issue - https://jira.spring.io/browse/SPR-11915

A: public class RuntimeRegistrationWithQualifierTest {
    private AnnotationConfigApplicationContext context;

    @Test
    public void beanWithQualifier() {

        final GenericBeanDefinition helloBeanDefinition = new GenericBeanDefinition();
        helloBeanDefinition.addQualifier(new AutowireCandidateQualifier(Hello.class));

        final GenericBeanDefinition worldBeanDefinition = new GenericBeanDefinition();
        worldBeanDefinition.addQualifier(new AutowireCandidateQualifier(World.class));

        final DefaultListableBeanFactory factory = context.getDefaultListableBeanFactory();

        factory.registerBeanDefinition("helloBean", helloBeanDefinition);
        factory.registerSingleton("helloBean", "hello");

        factory.registerBeanDefinition("worldBean", worldBeanDefinition);
        factory.registerSingleton("worldBean", "world");

        context.register(Foo.class);

        context.refresh();

        final Foo foo = context.getBean(Foo.class);

        assertThat(foo.hello).isEqualTo("hello");
        assertThat(foo.world).isEqualTo("world");
    }

    @Before
    public void newContext() {
        context = new AnnotationConfigApplicationContext();
    }

    @Qualifier
    @Retention(RUNTIME)
    @Target({FIELD, PARAMETER})
    @interface Hello {}

    @Qualifier
    @Retention(RUNTIME)
    @Target({FIELD, PARAMETER})
    @interface World {}

    static class Foo {
        final String hello;
        final String world;

        Foo(@Hello final String hello, @World final String world) {
            this.hello = hello;
            this.world = world;
        }
    }
}


text:
Q: Is it usual to create a parent POM for different projects? I have three different multimodule projects. I have also created one POM in the top level folder of these three different projects where I have added some configuration such as dependencyManagement element. So the different projects have their parent element set to this POM.
I wonder if such usage is a little strange or bad? Should I delete this POM and instead configure each top level POM of each multimodule project?

A: It's not unusual at all. Parent and multi-module projects are not the same thing, so by all means you can reuse your config the way you described. In fact, that's how all projects in Maven work, in a sense.
However, if I understand you correctly, you have a "meta-parent" sitting in a folder that contains several of the child projects, which are multi-module themselves. This might be confusing since it evokes association with modules (which the children are not). You might be slightly better-of having the "meta-parent" sit in a folder parallel to the multi-module projects, have the relativePath of the latter set to ../metaParent, and/or deploy the "meta-parent" to your Maven repo.


text:
Q: Does the Elo K-factor affect winning probabilities? Per the Wikipedia article on Elo ratings:

The difference in the ratings between two players serves as a predictor of the outcome of a match. Two players with equal ratings who play against each other are expected to score an equal number of wins. A player whose rating is 100 points greater than their opponent's is expected to score 64%; if the difference is 200 points, then the expected score for the stronger player is 76%.

This makes no mention of these probabilities being dependent on the K factor, is this correct?

A: K-factor does not affect the winning probabilities.
The K-factor enters when you are updating the Elo rating based on results from new games, it determine how big the change will be. When winning\losing a game, A player can gain\lose up to the K factor.
See Wikipedia for the formulas.


text:
Q: Clojure, Agent, lack side-effects I'm using agents to manipulate a structure, but I don't have all my side effects.
All the messages are sent(I've printed and counted them), but there are times when I don't have all my side-effects. As if not all of my functions were applied on the agent's state, or if the last send is applied on a previous state..
I experimented with doall, dorun but haven't find a solution, appreciate any help.
;; aux function for adding an element to a hashmap
(defn extend-regs [reg s o]
  (let [os (get reg s)]
    (if (nil? os)
      (assoc reg s [o])
      (assoc reg s (conj os o)))))

;; the agent's altering function - adding an element to the :regs field(a hashmap)
(defn add-reg! [d s o]
  (send d (fn [a] (assoc a :regs (extend-regs (:regs a) s o)))))

;; Creating the agents, dct/init returns an agent
;; pds: data for fields
(defn pdcts->init-dcts! [pds]
  (doall (map dct/init (map :nam pds) (repeat nil))))

;; Altering one agent's state,  dct/add-reg  sends an assoc message to the agent
;; d: agent,  pd: data for fields
(defn dct->add-regs! [d pd]
  (dorun (map (fn [s r] (dct/add-reg! d s r))
          (:syms pd)
          (:regs pd)))
  d)

;; Going through all agents
;; ds: agents,  pds: datas
(defn dcts->add-regs! [ds pds]
  (dorun (map (fn [d pd] (dct->add-regs! d pd))
          ds
          pds))
  ds)

EDIT: =====================================================
Okay it turned out I just haven't wait enough to my threads to finish their tasks. Now the question is how can I monitor my agents. How can I know that there are unfinished threads in the queue?  I've only found swank.core/active-threads and similar ones but they are not a solution.

A: I do not have a solution for your problem, but I can't resist suggesting some improvement on the first two functions:
(defn extend-regs [reg s o]
  (let [os (get reg s)]
    (if (nil? os)
      (assoc reg s [o])
      (assoc reg s (conj os o)))))
;; => place the 'if inside the assoc:
(defn extend-regs [reg s o]
  (let [os (get reg s)]
    (assoc reg s (if (nil? os) [o] (conj os o)))))
;; => this (if (nil? x) ...) is the pattern of function fnil, so ...
(defn extend-regs [reg s o]
  (let [os (get reg s)]
    (assoc reg s ((fnil conj []) os o))))
;; with update-in, this will be even clearer, and we can remove the let altogether:
(defn extend-regs [reg s o]
  (update-in reg [s] (fnil conj []) o))

As for the second:
(defn add-reg! [d s o]
  (send d (fn [a] (assoc a :regs (extend-regs (:regs a) s o)))))
;; => We can, again, use update-in instead of assoc:
(defn add-reg! [d s o]
  (send d (fn [a] (update-in a [:regs] extend-regs s o))))
;; or, if you can get rid of extend-regs:
(defn add-reg! [d s o]
  (send d (fn [a] (update-in a [:regs s] (fnil conj []) o)))

Finally, as a matter of style, I would place add-reg in a separate function, and directly use the idiom of sending to the agent in the client code (or have a simplified add-reg! function):
(defn add-reg [v s o] (update-in v [:regs s] (fnil conj []) o))

(defn add-reg! [d s o] (send d add-reg))

I know this doesn't answer your initial question, but it was fun to write this step by step refactoring

A: Use await or await-for to wait until an agent finished it's current work queue:
(await agent1 agent2 agent3)

or
(apply await list-of-agents)

A minor improvement of add-reg:
(defn extend-regs [reg s o]
  (update-in reg [s] conj o))

This works because of
(conj nil :b)               ; => [:b]

thus
(update-in {} [:a] conj :b) ; => {:a [:b]}

finally we have.
(defn add-reg! [d s o]
  (send d update-in s [:regs] conj o)


text:
Q: Idiom or Synonym for Someone who looks/feels like you could trust them, like they are someone reliable? I'm writing a character description, and the person I'm describing looks and/or feels like someone you can trust, like someone who would be honest with you, someone innocent, maybe even pure. Even if you just met them.
You just have the feeling like anything they say or do is with honest and good intentions and in case something they said or did come out as a lie, as something wrong you still feel the same somehow.
It would take something big to change your mind or else you would just think that they didn't mean it like that.
And it doesn't matter if the really didn't mean it or not.
I do not mean someone who pretends to be trustable, in this case you don't know if they are what they seem to be or not. So please keep that in mind.
I knew a word, description, idiom or synonym that just fit, but I can't seem to remember. Please help?
Thankful,
Aina

A: This person can be dependable, genuine, authentic, or sincere if you feel they're always being honest and true with you.  These have positive connotations.
If despite their actions you feel compelled to still trust them, they could be mesmerizing or enchanting.  These have more of a supernatural if not negative connotation.

A: Google: Soulmate. "A soulmate is someone that just gets you. It's a connection of minds, a mutual respect, an unconditional love and a total understanding. It's about being yourself and knowing, not only that person is following and understanding your thoughts, but is right there with you, side by side. ... My sister is my soulmate.


text:
Q: What is the use of a *.pb file in TensorFlow and how does it work? I am using some implementation for creating a face recognition which uses this file:
"facenet.load_model("20170512-110547/20170512-110547.pb")"
What is the use of this file? I am not sure how it works.
console log :
Model filename: 20170512-110547/20170512-110547.pb
distance = 0.72212267

Github link of the actual owner of the code
https://github.com/arunmandal53/facematch

A: pb stands for protobuf. In TensorFlow, the protbuf file contains the graph definition as well as the weights of the model. Thus, a pb file is all you need to be able to run a given trained model.
Given a pb file, you can load it as follow.
def load_pb(path_to_pb):
    with tf.gfile.GFile(path_to_pb, "rb") as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
    with tf.Graph().as_default() as graph:
        tf.import_graph_def(graph_def, name='')
        return graph

Once you have loaded the graph, you can basically do anything. For instance, you can retrieve tensors of interest with
input = graph.get_tensor_by_name('input:0')
output = graph.get_tensor_by_name('output:0')

and use regular TensorFlow routine like:
sess.run(output, feed_dict={input: some_data})

A: Explanation
The .pb format is the protocol buffer (protobuf) format, and in Tensorflow, this format is used to hold models. Protobufs are a general way to store data by Google that is much nicer to transport, as it compacts the data more efficiently and enforces a structure to the data. When used in TensorFlow, it's called a SavedModel protocol buffer, which is the default format when saving Keras/ Tensorflow 2.0 models. More information about this format can be found here and here.
For example, the following code (specifically, m.save), will create a folder called my_new_model, and save in it, the saved_model.pb, an assets/ folder, and a variables/ folder.
# first download a SavedModel from TFHub.dev, a website with models
m = tf.keras.Sequential([
    hub.KerasLayer("https://tfhub.dev/google/imagenet/mobilenet_v2_130_224/classification/4")
])
m.build([None, 224, 224, 3])  # Batch input shape.
m.save("my_new_model") # defaults to save as SavedModel in tensorflow 2

In some places, you may also see .h5 models, which was the default format for TF 1.X. source

Extra information: In TensorFlow Lite, the library for running models on mobile and IoT devices, instead of protocol buffers, flatbuffers are used. This is what the TensorFlow Lite Converter converts into (.tflite format). This is another Google format which is also very efficient: it allows access to any part of the message without deserialization (unlike json, xml). For devices with less memory (RAM), it makes more sense to load what you need from the model file, instead of loading the entire thing into memory to deserialize it.

Loading SavedModels in TensorFlow 2
I noticed BiBi's answer to show loading models was popular, and there is a shorter way to do this in TF2:
import tensorflow as tf
model_path = "/path/to/directory/inception_v1_224_quant_20181026"
model = tf.saved_model.load(model_path)

Note,

*

*the directory (i.e. inception_v1_224_quant_20181026) has to have a saved_model.pb or saved_model.pbtxt, otherwise the code will crash. You cannot specify the .pb path, specify the directory.

*you might get TypeError: 'AutoTrackable' object is not callable for older models, fix here.

If you load a TF1 model, I found that I don't get any errors, but the loaded file doesn't behave as expected. (e.g. it doesn't have any functions on it, like predict)


text:
Q: Are raw data provided by tshark full? Because display filters are not supported when saving captured data with tshark
I am trying to create valid cap file that I can read in Wireshark.
I capture data with

tshark -i wlan2 -V -x -q -Y "radiotap.channel.freq > 2400 && radiotap.channel.freq < 2500"

In python I am scraping raw data with:
for line in io.TextIOWrapper(tshark_process.stdout, encoding="utf-8"):
   substring = oneline[5:53]
   clean = ''.join([c for c in substring if 34 < ord(c) < 127])
   raw_packet += clean

I am converting these data back to raw hex data:
newFile = open("filename.cap", "wb")
newFile.write(bytes.fromhex(raw_packet))

I also tried:
newFile.write(bytearray(binascii.unhexlify(raw_packet)))

or
newFile.write(binascii.unhexlify(raw_packet))

But when I open the filename.cap in Wireshark I don't see normal packet data:

Frame 1: 260 bytes on wire (2080
  bits), 260 bytes captured (2080 bits)
      Encapsulation type: JavaScript Object Notation (175)
      Frame Number: 1
      Frame Length: 260 bytes (2080 bits)
      Capture Length: 260 bytes (2080 bits)
      [Frame is marked: False]
      [Frame is ignored: False]
      [Protocols in frame: json:data-text-lines] JavaScript
  Object Notation Line-based text data
  (1 lines)
       [truncated]\000\000 \000\256@\000\240 \b\000\240
  \b\000\000\020\002l\t\240\000\336\000d\000\000\000\000\000\000\001\200\000\000\000\377\377\377\377\377\377\264\373\344J\352\346\264\373\344J\352\346p!\200\201+A'\000\000\000d\0001\004\000\

Are raw data provided by tshark full?
How can I convert them back to Wireshark readable file?
Or what am I doing wrong?

A: Capture Formats
Packet captures are file formats that organize packets along with metadata. There are two formats that are primarily used by the *shark family:

*

*pcap: Format popularized by tcpdump, which is based on libpcap

*pcapng: Modern format that supports saving more metadata (like packet statistics, interface names, capturing OS, etc.) By default, *shark saves to this format.

If you want a visual on the file bytes of a pcap, including file header, this article deconstructs a capture with 2 ARP packets.
Python & Packets
There are many python parsers to create capture files that can be read by Wireshark. The most versatile one is Scapy, which is used to both read and generate packets. You can read and write to a pcap without worrying about the file header:
Generate Traffic
First generate a 1 packet file with tshark:
tshark -w example.pcap -c 1

Read Capture
Then read with scapy. Here we use the Scapy interpreter that extends the Python interpreter. You can do the same thing in a script by prefacing it with from scapy.all import *. Note that Scapy provides many more tools to manipulate packets.
>>> capture = rdpcap("example.pcap")
>>> len(capture)
1
>>> for pkt in capture:
...:     pkt.show()
###[ Ethernet ]###
  dst= 6c:96:cf:d8:7f:e7
  src= ac:86:74:a9:56:42
  type= 0x800
###[ IP ]###
     version= 4
     ihl= 5
     tos= 0x20
     len= 60
     id= 0
     flags= DF
     frag= 0
     ttl= 55
     proto= tcp
     chksum= 0x1abd
     src= 17.253.17.209
     dst= 10.255.250.18
     \options\
###[ TCP ]###
        sport= http
        dport= 50653
        seq= 616207835
        ack= 2603062618
        dataofs= 10
        reserved= 0
        flags= SA
        window= 28880
        chksum= 0x21e6
        urgptr= 0
        options= [('MSS', 1456), ('SAckOK', b''), ('Timestamp', (4160359186,
1059821791)), ('NOP', None), ('WScale', 8)]

Write Capture
Writing back to pcap is similarly simple:
>>> wrpcap('written.pcap', capture)

Verification
Checking that Tshark can read the generated written.pcap, we see that it can:
$ tshark -r written.pcap
    1   0.000000 usscz2-vip-bx-009.aaplimg.com → 10.255.250.18 TCP  74 http(80) → 50653 [SYN, ACK] Seq=0 Ack=1 Win=28880 Len=0 MSS=1456 SACK_PERM=1 TSval=4160359186 TSecr=1059821791 WS=256 6c:96:cf:d8:7f:e7 ← ac:86:74:a9:56:42


text:
Q: Problem sending email from php I'm trying to setup a server so that I can send email from PHP using the mail() function. I tried running a script that I know works but never got the email. Here is the log file:
Sep  1 13:58:27 server1 postfix/master[5318]: daemon started -- version 2.5.5, configuration /etc/postfix
Sep  1 13:59:21 server1 dovecot: Dovecot v1.0.15 starting up
Sep  1 13:59:21 server1 dovecot: Generating Diffie-Hellman parameters for the first time. This may take a while..
Sep  1 13:59:22 server1 dovecot: Killed with signal 15
Sep  1 13:59:22 server1 dovecot: Dovecot v1.0.15 starting up
Sep  1 13:59:22 server1 dovecot: Generating Diffie-Hellman parameters for the first time. This may take a while..
Sep  1 13:59:22 server1 dovecot: Killed with signal 15
Sep  1 13:59:22 server1 dovecot: Dovecot v1.0.15 starting up
Sep  1 13:59:22 server1 dovecot: Generating Diffie-Hellman parameters for the first time. This may take a while..
Sep  1 14:12:37 server1 postfix/master[5318]: terminating on signal 15
Sep  1 14:12:37 server1 postfix/master[5998]: daemon started -- version 2.5.5, configuration /etc/postfix
Sep  1 14:12:41 server1 dovecot: Killed with signal 15
Sep  1 14:12:41 server1 dovecot: Dovecot v1.0.15 starting up
Sep  1 14:21:16 server1 postfix/master[5998]: terminating on signal 15
Sep  1 14:21:18 server1 dovecot: Killed with signal 15
Sep  1 14:22:14 server1 postfix/master[2031]: daemon started -- version 2.5.5, configuration /etc/postfix
Sep  1 14:24:31 server1 postfix/master[2033]: daemon started -- version 2.5.5, configuration /etc/postfix
Sep  1 14:25:22 server1 dovecot: Dovecot v1.0.15 starting up
Sep  1 14:39:44 server1 postfix/master[2033]: terminating on signal 15
Sep  1 14:39:48 server1 dovecot: Killed with signal 15
Sep  1 14:40:43 server1 postfix/master[2033]: daemon started -- version 2.5.5, configuration /etc/postfix
Sep  1 14:40:44 server1 dovecot: Dovecot v1.0.15 starting up
Sep  1 14:43:28 server1 postfix/pickup[2042]: 5FAEE256327: uid=33 from=<www-data>
Sep  1 14:43:28 server1 postfix/cleanup[2214]: 5FAEE256327: message-id=<20090901184328.5FAEE256327@server1.dev.com>
Sep  1 14:43:28 server1 postfix/qmgr[2044]: 5FAEE256327: from=<www-data@server1.dev.com>, size=418, nrcpt=1 (queue active)
Sep  1 14:43:28 server1 postfix/smtp[2216]: connect to gmail-smtp-in.l.google.com[209.85.210.23]:25: No route to host
Sep  1 14:43:28 server1 postfix/smtp[2216]: connect to alt1.gmail-smtp-in.l.google.com[209.85.212.8]:25: No route to host
Sep  1 14:43:28 server1 postfix/smtp[2216]: connect to alt2.gmail-smtp-in.l.google.com[209.85.219.43]:25: No route to host
Sep  1 14:43:28 server1 postfix/smtp[2216]: connect to alt3.gmail-smtp-in.l.google.com[209.85.129.114]:25: No route to host
Sep  1 14:43:28 server1 postfix/smtp[2216]: connect to alt4.gmail-smtp-in.l.google.com[209.85.222.4]:25: No route to host
Sep  1 14:43:28 server1 postfix/smtp[2216]: 5FAEE256327: to=<blackarmadillo@gmail.com>, relay=none, delay=0.26, delays=0.11/0.04/0.11/0, dsn=4.4.1, status=deferred (connect to alt4.gmail-smtp-in.l.google.com[209.85.222.4]:25: No route to host)

I'm guessing it has something to do with the "No route to host"... any ideas?

A: You need to resolve the "No route to host" issue before you can get e-mail through.  You can test it by running the following command from the server:
   telnet 209.85.222.4 25
It should look something like:
   guin:~$ telnet 209.85.222.4 25
   Trying 209.85.222.4...
   Connected to 209.85.222.4.
   Escape character is '^]'.
   220 mx.google.com ESMTP 4si19030170pzk.29
   quit
   221 2.0.0 closing connection 4si19030170pzk.29
   Connection closed by foreign host.
   zsh: exit 1     telnet 209.85.222.4 25
   guin:~$
Where I typed "quit" to exit.  If you don't get the "220" line, your server
has problems connecting to the remote mail server.
If that is the case, I'd guess it's either a routing problem (missing
default route?  Check "netstat -nr" output), or a firewalling issue (check
"iptables-save | less" output).
Sean

A: FYI: Google Mail was down earlier today. You didn't specify if this was causing trouble with other hosts.
If it's still causing you trouble, then perhaps your network administrator is blocking outgoing port 25. Some ISPs do this to stop spam. You can contact your network administrator for details about that.

A: those ip's are reachable from your server; I guess you don't have connection to them, though your dns resolves mx for gmail
try telnetting to port 25 to at least one of those ip addresses
please check your routing and firewall rules

A: On your sever you can try this command :
sendmail someaddress@email.com
Subject: test
CTRL +D
then cat /var/log/mail.info
and check if you mail is sent. If you have any issue by sending an email from terminal then that won't work with php.
Tell us what the command gives you


text:
Q: Operator for Multiple Points in One Struct I have a struct that stores two points that should be interchangeable.
struct Edge
{
    unsigned short firstIndex;
    unsigned short secondIndex;
    Edge(unsigned short firstIndex, unsigned short secondIndex) :
        firstIndex(firstIndex), secondIndex(secondIndex) {}
};

The operator== method should be as follows (To make them interchangeable)
bool operator == (const Edge& e2) const
{
    return
        first == e2.first && second == e2.second ||
        first == e2.second && second == e2.first;
}

I am looking to create an operator< and operator> method in order to use the struct in a std::map
I have tried the following (using multiplication) but it does not work since there are many cases in which different edges return the same value
bool operator < (const Edge& e2) const
{
    return first * second < e2.first * e2.second;
}

The code that I would like to use is the following:
std::map<Edge, unsigned int> edgePoints;
Edge e1(0, 1);
Edge e2(1, 2);
Edge e3(2, 0);

edgePoints[e1] = 2;
edgePoints[e2] = 0;
edgePoints[e3] = 1;

Although the code does not work with my operator< method because 0 * 1 == 2 * 0 so the map returns 2 when I call edgePoints[e3]
Does anyone know of an operator< and operator> method that I could use or even some other way of mapping the edges in order to use the std::map

A: I would store the indices of the edge in such a way, that the smaller index always is the first index. It looks like the internal representation is irrelevant in your application. You don't need operator== for maps. Here is the example struct:
struct Edge
{
    typedef unsigned short Idx; // prefer strong typedef cf boost
    Edge(Idx a, Idx b)
    :
        firstIndex(std::min(a, b)),
        secondIndex(std::max(a, b))
    {}

    Idx firstIndex;
    Idx secondIndex;

    bool operator<(Edge const & other)
    {
        if (firstIndex != other.firstIndex)
            return firstIndex < other.firstIndex;
        return secondIndex < other.secondIndex;
    }
}; // Edge

If you want to make your implementation even nicer, some minor suggestions:

*

*Prefer std::array<unsigned short, 2> over separate variables firstIndex and secondIndex. Doing so allows iterating over the indices.

*If you are using array, you can shorten the operator< using std::lexicographical_compare.

A: Consider compairing them as sorted pairs.
bool operator < (const Edge& e2) const
{
    if (min(first, second) != min(e2.first, e2.second))
        return min(first, second) < min(e2.first, e2.second);
    return max(first, second) < max(e2.first, e2.second);
}

Edit: Of course that can be written nicelier with saving mins and maxes as local variables, but the idea should be clear.
Edit: The idea in other answer is better: force your struct to always have first less then second, and it will eliminate all mins and maxes, and make comparation run fast like hell)


text:
Q: HTML  has locked CSS applied, and I want it to display as browser defaults I can't edit the CSS file, which has the following values:
font-size: 13px;
padding: 6px 4px;
background-color: rgb(238, 238, 238);
border: 1px solid rgb(204, 204, 204);
clear: both;
margin-bottom: 4px;

I know I can use the !important tag, but when I try to override with the default values, it still doesn't display the same was a CSS-less (clean) <select> drop-down would.
Thanks

A: You cannot set a property of an element to browser default, once there is any CSS rule in effect that assigns a value to the property of the element. For example, if any style sheet sets font-size: 13px on a select element, there is no way to tell a browser to behave as if that setting just didn't exist and use its default instead.
What you can do is to set a property to an explicit value, e.g. select { font-size: 18px }, and this will override other settings by normal cascade rules. If this did not work for you, then there is some problem in the specific way you used.
You might try to set properties to explicit values that you believe to be browser defaults, but there is no guarantee that all browsers, current and future, will have those values as their defaults.
In an earlier draft for CSS Cascading and Inheritance Level 3, there was a proposed default keyword that would "roll back the cascade". But it has been dropped in the current version of the draft, which proposes the unset keyword instead, but its definition does not mean using browser defaults (but initial values as per CSS specifications).


text:
Q: Matlab Image Quantization not working I loaded a gray scale image to Matlab to perform the quantization. Unfortunately the output is nothing.
I = imread('asa.jpg');
imshow(I)
axis off
title('Grayscale Image')
thresh = multithresh(I,7);
valuesMax = [thresh max(I(:))]
[quant8_I_max, index] = imquantize(I,thresh,valuesMax);
valuesMin = [min(I(:)) thresh]
quant8_I_min = valuesMin(index);
imshowpair(quant8_I_min,quant8_I_max,'montage')
title('Minimum Interval Value           Maximum Interval Value')

A: I believe there is a problem with the image. I tried your code, and it seems to work...

Can you please show a screen shot to explain better what the issue is? You should also include your Matlab version number in the question.


text:
Q: Git submodules with separate work_tree I followed the tutorial on this page to make deploying my websites via Git simple: http://toroid.org/ams/git-website-howto. Up til now it's being fine, however I've recently started using Kohana and followed this tutorial to set it up in Git: http://kohanaframework.org/3.1/guide/kohana/tutorials/git.
My problem is: when I push to my web server, none of the submodules are deployed. So, how can I pull the submodules into my working tree on my webserver?
If I run
git --git-dir /srv/www/mysite.com/src/project.git --work-tree /srv/www/mysite.com/public_html submodule init

it says
fatal: working tree '/srv/www/mysite.com/public_html' already exists
Clone of 'git://github.com/kohana/auth.git' into submodule path 'modules/auth' failed`.

Does anyone know how to checkout these submodules? If I can't find a way I'll have to resort to manually FTPing them up which isn't ideal.

A: You need to push the submodules separately. Submodules are their own repositories.
A simpleminded go at this would be
git sub-module for-each git push

(_add the --recursive flag to make it really work on steroids)
You'd have to look for yourself whether this is what you desire. Also, note that each submodule will push to it's designated upstream (push branch) by default
You can also fetch
Within the receiving worktree:
git submodule update

The first you may have to
git submodule init

A: Try CD'ing into the submodule directory and just doing a git push.
Make sure you did git submodule init and git submodule update in the root project folder when you enabled the submodule.


text:
Q: How did Aladdin trick Genie inside the cave with his first wish? In Aladdin (2019), by rewinding, Genie reminds Aladdin that he already used his first wish to get out of the cave but Aladdin argues that it didn't count as his wish.
How did Aladdin trick Genie inside the cave ?

A: He didn't rub the lamp.

Distracted by his own lighter-than-desired shade of blue, the Genie didn't notice as Aladdin deftly slipped the lamp out of his hands and into the outstretched hand of Abu. With the lamp safely out of his hands, he nodded. "Genie," he said, "I wish you to get us out of this cave."
...
"I'll do it," Aladdin said, cutting him off. "I've got three, right?"
"Two—" the Genie corrected. "You already used one."
Aladdin raised an eyebrow, a mischievous smile tugging at his lips. "Did I?" he said. "Or did you? Thought I had to rub the lamp."
Aladdin - Official Novelisation.

A: It's essentially the same trick as the animated film. Aladdin challenges Genie's pride, Genie gets them out of the cave voluntarily to prove that he can. Aladdin successfully argues that he never actually asks Genie to do so, so it's not a wish.


text:
Q: How to find Duplicate documents in Cosmos DB I have seen like a huge amount of data write to cosmos DB from stream analytics job on a particular day.
It was not supposed to write huge amount of documents in a day. I have to check if there is duplication of documents on that particular day.
Is there any query/any way to find out duplicate records in cosmos DB?

A: It is possible if you know the properties to check for duplicates.
We had a nasty production issue causing many duplicate records as well.
Upon contacting MS Support to help us identify the duplicate documents, they gave us the following query;
Bear in mind: property A and B together define the uniqueness in our case. So if two documents have the same value for A and B, they are duplicate.
You can then use the output of this query to, for example, delete the oldest ones but keep the recent (based on _ts)
SELECT d.A, d.B From
   (SELECT c.A, c.B, count(c._ts) as counts FROM c
    GROUP BY c.Discriminator, c.EndDateTime) AS d
WHERE d.counts > 1

A:
Is there any query/any way to find out duplicate records in cosmos DB?

Quick answer is YES.Please use distinct keyword in the cosmos db query sql.And filter the _ts(System generated unix timestamp:https://learn.microsoft.com/en-us/azure/cosmos-db/databases-containers-items#properties-of-an-item)
Something like:
Select distinct c.X,c.Y,C.Z....(all columns you want to check) from c where c._ts = particular day

Then you could delete the duplicate data using this bulk delete lib:https://github.com/Azure/azure-cosmosdb-bulkexecutor-dotnet-getting-started/tree/master/BulkDeleteSample.


text:
Q: PHPCS exit code based on threshold Im trying to implement PHPCS in my project which has an huge technical depth. I have for example one module with 378 sniffs (both errors and warnings combined). However the fact is that i also have like 29 modules which makes it nearly impossible to finish this technical depth in a short period of time.
What i want is to keep it at least stable so that one of the teams can keep developing where the other can clean up some mess on the spot. The question is how can i enable PHPCS scans but for example let if only fail when it hits more than 378 hits in this case on that module. This way i can ensure that my depth stays the same and a long the way i can ensure that it will be lowered.
As far as i can see the only way with PHPCS itself is to set the severity levels and let it break on there but i'd rather stay as close as possible to the default coding standards and keep it as strict as possible.
Thanks a lot
Pim

A: I build an own script like Greg above also mentioned that checks the outcome of the --report=summary via a regex. The regex outcome then determines the exit code 0 or 1 from there.
Would be helpfull if PHPCS could do something like that itself but its not there


text:
Q: Converting an str object into keyword in Python For some reason, I have a list of strings that happen to be python built-in functions/methods. Example,
somelist = ['list', 'insert', 'append']
I have some data, like data = 'I am a cat'
Now, I want to do an operation from somelist on data. Example, list(data)
If I try to index from somelist[0], I am getting the str object 'list'. But I want the keyword list instead.
Is there any way to convert str object to keyword datatype? (Is there even a datatype for keywords?)

A: One way you can achieve what you're looking for is with eval()
somelist = ['list', 'insert', 'append', 'pop']
data = 'I am a cat'

lst = eval(somelist[0] + '(data)')
print(lst)

ind = 2
eval('lst.' + somelist[1] + '(ind, data)')
print(lst)

eval('lst.' + somelist[2] + '(data)')
print(lst)

As you can see, eval() literally executes the command - in the form of string - that it got as an argument. This is very dangerous, and depending on your application, should be avoided (unless you check what you're executing very rigorously, or there are some other ways to maintain safety). Read this for a complete list of issues with eval(). You still need to, as far as I know, provide the framework for each command as above.
Another, safer way is the use if statements that recognize (or not) the element in somelist and turn them into a proper call,
somelist = ['list', 'insert', 'append', 'pop']
data = 'I am a cat'

lst2 = []
for op in somelist:
    if op == 'list':
        lst2 = list(data)
        print(lst2)
    elif op == 'insert':
        lst2.insert(3, data)
    elif op == 'append':
        lst2.append(data)
    else:
        print(op + ' is not defined')

This is safe since you have control over what can be called. You can turn it into a function, with optional or keyword arguments, and improve it's robustness. This is just an example to show you the concept.


text:
Q: R data.table lapply split by segment: expecting wrong data type I am working on a medical data set.  Each patient has time-updated records across different rows.  For each patient, we want to compute the time of their first hospitalization, first heart attack, or death.  For those without any records during the time of the study, we'll return NA as a missing value.
This seems like a great opportunity to use R's data.table package, but I am getting a strange error.  Here is an example:
library(data.table)
dat <- data.table(id = c(1,1,2,2), begin = c(0, 20, 0, 50),
                  hospital = c(1,0,0,1), heart.attack = c(0,0,0,1),
                  death = c(0,1,0,1))
print(dat)

    id begin hospital heart.attack death
1:  1     0        1            0     0
2:  1    20        0            0     1
3:  2     0        0            0     0
4:  2    50        1            1     1

This function calculates the minimum time that an event occurred.  If no event occurred, return a missing value.
first.calc <- function(outcome, time){
        w <- which(as.logical(outcome) == TRUE)
        if(length(w) > 0){
            return(min(time[w]))
        }
        else{
           return(NA)
        }
}

Note: these variables are used because I'm actually writing a function to apply these techniques on multiple data sets with unknown names.
time.name = "begin"
id.name = "id"
outcome.names = c("hospital", "heart.attack", "death")

res <- dat[, lapply(X = .SD, FUN = "first.calc",
             time = get(time.name)),
             .SDcols = outcome.names,
             by = id.name]

**Error in `[.data.table`(dat, , lapply(X = .SD,
              FUN = "first.calc", time = get(time.name)),  :
     Column 2 of result for group 2 is type
     'double' but expecting type 'logical'. Column types must
     be consistent for each group.**

Meanwhile, the function seems to work on a single patient or without subsetting:
dat[id == 1, lapply(X = .SD, FUN = "first.calc",
                    time = get(time.name)),
             .SDcols = outcome.names,
              by = id.name]
    id hospital heart.attack death
1:  1        0           NA    20

dat[id == 2, lapply(X = .SD, FUN = "first.calc",
                     time = get(time.name)),
                     .SDcols = outcome.names,
                     by = id.name]
    id hospital heart.attack death
1:  2       50           50    50

dat[, lapply(X = .SD, FUN = "first.calc",
                      time = get(time.name)),
            .SDcols = outcome.names]

         hospital heart.attack death
1:        0           50    20

So why is this error occurring when I use by = id.name on the full data set?
I have read through most of the Similar Questions.  There was not much information about this specific issue.  Sorry if this question is a duplicate.  Thanks for looking at it!


text:
Q: How to get touch feedback from RecyclerView? I implemented a RecyclerView and I can't figure out how to get touch feedback (the ripple effect from it).
Here is what i did for the onClickListener:
holder.itemView.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            //start Intent
        }

    });

And I added both clickable and focusable to my XML. This is what the recycler view inflates:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:padding="4dp" >

A: You have to set a ripple drawable as the background:
android:background="@drawable/ripple"

ripple.xml:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#ffa0a0a0"/>

You may need to mask the drawable:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#ffa0a0a0">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="#ffa0a0a0"/>
        </shape>
    </item>
</ripple>

This will create a simple grey ripple upon touch (here's a guide if you need more instructions).
RippleDrawable was added in SDK version 21 (Lollipop). Using Ripple drawable on pre-lollipop will crash the app. Either use a simple selector on pre-lollipop devices or use libraries that recreate the effect. (GitHub)
UPDATE: You can get the ripple effect easily with this piece of code:
android:background="?attr/selectableItemBackground"

or if you don't want the rectangle mask:
android:background="?attr/selectableItemBackgroundBorderless"

This is compatible with pre-lollipop devices and will us a simple selector. I believe this will create light ripples in apps with dark theme and vice versa, so if you want a custom colored ripple you will still need to create a ripple drawable.

A: In addition to @Longi's answer: If you want your RecyclerViews's Item to have its own background, and at the same time to have the ripple effect, you can do as shown in the example below:
recycler_view_item.xml:
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/recyclerview_item_background">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="?attr/selectableItemBackgroundBorderless">
       ...
    </LinearLayout>
</LinearLayout>

In this example @drawable/recyclerview_item_background is a nine-patch png, but you can use any background here.
In my case when I used android:background="?attr/selectableItemBackground", the RecyclerView Item's root Linear Layout did have the ripple effect, but the child Linear Layout's background was overlapping thus hiding the ripple effect.


text:
Q: After 1 year and a half, my windows now decided to say its not genuine On 18/06/2015 I bought a windows 7 ultimate key. I activated it, connected to microsoft, updated, and everything was nice.
However, to my surprise, today it started saying that its not genuine.
My first reaction was "I'm going to contact the seller! I'm sure he can help me!". Nope. Website doesn't exist anymore. I now think my Windows is actually not genuine indeed.
If I try to apply the activation backup, it doesn't work.
If I try to insert the key again, it says that the key is blocked by microsoft.
If I say I want to buy a new license, it doesn't offer me the option for windows 7, only windows 10.
I use some acessibility things, so I can update for free to windows 10. However when I try to install it, it says my windows need to be activated in order to install it.
What are my other options? 2016 is here to say "I'm not over yet". Dammit.
I'm from Brazil, and the automated call is not an option.

A: So, I found a youtube video that mentioned to run slmgr -rearm on cmd with administrator privileges and restart the pc.
Just that. No installing things or deleting things. And it worked.


text:
Q: Adding AFP protocol to Windows Server shares Is there a way to add the Apple File Protocol (AFP) to Windows Server for shares, currently Windows uses SMB but the transfer rate to OSX clients is ridiculously slow, I am currently running an Ubuntu server box with AFP but would like to know if there is an option or way to get it working on Windows Server (2008 R2).

A: Microsoft used to include Services for Macintosh, but it's no longer supported in Server 2008, so you'll have to go for a third party solution.
There's no Windows port of netatalk, but you could of course run it virtualized. Otherwise, the only options appear to be the commercial products MacServerIP and ExtremeZ-IP. Unfortunately ExtremeZ-IP is quite expensive, at $795 for a 3 client license. MacServerIP has no listed price that I could find, which suggest it's also priced rather highly.


text:
Q: applying any formula by column wise Now how to apply ifelse statement on all columns dynamically starting from column 3
Date    name   A      B    C    XYZ
2014    sam    22     0    -1   20
2015    john   -1     29    0   40

We can do it by hard coding , excluding 1 and 2 columns
df1$A = ifelse(df$A <= 0 ,NA,df$A)   #to
df1$XYZ = ifelse(df$XYZ <= 0 ,NA,df$XYZ)

Thanks in advance

A: Using dplyr/tidyverse:
library(tidyverse)

df1 = df1 %>%
    mutate_at(vars(A:XYZ), function(x) { ifelse(x <= 0, NA, x)})

Output:
  Date name  A  B  C XYZ
1 2014  sam 22 NA NA  20
2 2015 john NA 29 NA  40

A: With base R, we can loop through the columns of interest, apply the ifelse and assign it back to those columns
df1[3:ncol(df1)] <- lapply(df1[3:ncol(df1)], function(x) ifelse(x <=0, NA, x))

However, we can do this more easily without any looping or ifelse
df1[3:ncol(df1)][df1[3:ncol(df1)] <=0] <- NA


text:
Q: Windows Phone heap size limit Does Windows Phone have a limit on the amount of heap memory an app can use?
Android has a heap limit of 24 mb. Does WP7 have a similar limit on heap?

A:
An application must not exceed 90 MB of RAM usage, except on devices that have more than 256 MB of memory ...

For details check out technical certification requirements here:
http://msdn.microsoft.com/en-us/library/hh184840(v=VS.92).aspx


text:
Q: Update Element in ArrayList I have problem with updating elements in arraylist. I have class ViewLabelINScreen and I build an arraylist of elements from this class, but when I update elements in this arraylist, with out another element in same object get value Default. How can I change only this element with out changeing other elements too.
I changed this element in different class which add this element and I need this array list static.
ViewLabelINScreen:
public class ViewLabelINScreen {
    public int xP;
    public int yP;
    public String nameLabel;
    public int stringWidth4;
    public int fontHeight;
    public boolean stored;

    public ViewLabelINScreen(int XP,int YP,String NameLabel,int StringWidth4 ,int FontHeight )
    {
        xP=XP; yP=YP; nameLabel=NameLabel;stringWidth4=StringWidth4;fontHeight=FontHeight;
    }

    //this contractor for change namelabel
    public ViewLabelINScreen (String Namelabel)
    {
        nameLabel=Namelabel;
    }

    public ViewLabelINScreen () {

    }
}

The following class adds the element into the arraylist.
public class WgsGrid {
    //Added by A.B
    MapSelection mapSelection;
    public static ArrayList<ViewLabelINScreen> INFOLable = new ArrayList<ViewLabelINScreen>();
    for (int i4 = hMin; i4 <= hMax; i4++)
    {
        INFOLable.add(new ViewLabelINScreen(labelRectX, labelRectY - yOffset4, SetLabels.getYlabels()[counter2],stringWidth4,fontHeight));
    }
}

This class NeedChangeArrayList change an element:
class NeedChangeArrayList {
    public void ChangeAraay()
    {
        if (WgsGrid.INFOLable.isEmpty() != true)
        {
            for (int s = 0; s < ylabels.length; s++)
            {
                WgsGrid.INFOLable.set(s, new ViewLabelINScreen(ylabels[s]));
            }

            //ylabels[s] string array get value from array and put in nameLabel
        }
    }
}

A: Are you changing all the nameLabel values in the array list? If so, you can try this in your for loop:
for(int s =0; s< WgsGrid.INFOLable.size();s++){
    WgsGrid.INFOLable.get(s).setNameLabel("whatever");
}

You need to create a setter method for nameLabel though.
public void setNameLabel(String nameLabel){
    this.nameLabel = nameLabel;
}

(I've changed from ylabels.length to the arraylist's size. Not sure what you were doing with ylabels)


text:
Q: consul balance the traffic cross regions with consul At this point, I have found a few well-documented blogs about how to set up service failover to a different datacenter. However, I am yet to find a way to load balance traffic between 2 different datacenters. This may look like an extreme design issue; however, it seems that due to capacity issues on regions, and dc's we need to look for this.
In the image above we are trying to run primary DC in Oregon, while we have reserver capacity for GPU, we can never possibly reserve 100%. At the same time, cloud providers can not guarantee availability for nonreserved instances for GPUs and c5 type instances.
In this context, we would need to run on multiple regions and transfer traffic to GPU instances running on other regions only when we see capacity crunch in the local region. Not sure how to achieve that.

A: Are you trying to achieve this using Consul's service mesh, or just service discovery?


text:
Q: converting user details stored in a text file into a dictionary I have tried converting the text file into a dictionary using the following code below:
d = {}
with open('staff.txt', 'r') as file:
    for line in file:
        (key, val) = line.split()
        d[str(key)] = val
print(d)

The contents in the file staff.txt:
username1 jaynwauche
password1 juniornwauche123
e_mail1 juniornwauche@gmail.com
Fullname1 Junior Nwauche

Error: too many values to unpack
What am I doing wrong?

A: According to your file, the last line you have three words and you want to split them by space so you will have three words but just two variables.

A: You need to specify the split condition. Right now you are splitting each character, there for you get a list with a lot of elements. Try line.split(' ') like this:
d = {}
with open('staff.txt', 'r') as file:
    for line in file:
        (key, val) = line.split(' ')
        d[str(key)] = val
print(d)

This will split the lines where there's an space, so you get only words on the list.


text:
Q: How many are too many nested function calls? Quoted from MSDN about StackOverflowException:

The exception that is thrown when the execution stack overflows because it contains too many nested method calls.

Too many is pretty vague here. How do I know when too many is really too many? Thousands of function calls? Millions? I assume that it must be related in some way to the amount of memory in the computer but is it possible to come up with a roughly accurate order of magnitude?
I'm concerned about this because I am developping a project which involves a heavy use of recursive structures and recursive function calls. I don't want the application to fail when I start using it for more than just small tests.

A:
I'm concerned about this because I am developping a project which involves a heavy use of recursive structures and recursive function calls. I don't want the application to fail when I start using it for more than just small tests.

Unless your language environment supports tail call optimization (and your recursion is a tail call), a basic rule of thumb is: recursion depth should be guaranteed to be O(log n), i.e. using algorithms or data structures based on divide-and-conquer (like trees, most sorting alogorithms, etc.) is OK, but anything linear (like recursive implementations of linked list handling) is not.

A: Since Cole Campbell noted memory size and Michael Borgwardt noted tail call optimization I won't cover those.
Another thing to be aware of is CPS which can be used to optimize several interwoven functions where tail call optimization is for single functions.
You can increase the size of the stack as we did here, and be aware that 64-bit code eats the stack faster than 32-bit code.
Of note is that we ran one of the examples under F# interactive for more than 40 hours without blowing the stack. Yes it was one function call that ran by itself continuously to successful completion.
Also, if you need to do code coverage to figure out where the problems occur and don't have code coverage with VS you can use, TestDriven.NET

A: By default, the CLR allocates 1 MB to the stack for each thread (see this article).  So, it's however many calls it takes to exceed this amount.  That will vary depending on how much space on the stack each call is using for things like parameters and local variables.
You can even make it throw a StackOverflowException with a single call if you're willing to be a bit unorthodox:
private static unsafe void BlowUpTheStack()
{
    var x = stackalloc byte[1000000000];
    Console.WriteLine("Oh no, I've blown up the stack!");
}


text:
Q: Spring security with soap I need to make a SOAP webservice and a web client. I have been trying for several days to implement and configure spring security on the ws to control authentication with a database but without success.
I use spring boot 2.2 with spring security.
I would like the user to authenticate only on certain actions and from a database and not by putting the password in hard.
Could you explain me how works spring security with soap ? I didn't find good and simple explanation.
Thanks for your help


text:
Q: Piping data to Gnuplot from C I've managed to create some code which will continuously send data points from a C program to gnuplot to show evolution of a time dependent Schrodinger equation. This is the function I've made which is iterated in a loop which updates the WF[] values each time:
(Both x[] and WF[] are 1d)
void gnuprint(FILE *gp, double x[], int N)
{
    int i;
    fprintf(gp, "plot '-' with lines\n");

    for (i=0; i<N; i++){fprintf(gp, "%g %g\n", x[i],WF[2*i+1]);}
    fflush(gp);
    fprintf(gp, "e\n");
}

What I really want to do next is plot the imaginary points on the same plot which are next to the real in the array:  x[i], WF[2*i+2]
If I simply just add a
fprintf(gp, "%g %g\n", x[i],WF[2*i+2]); //The imaginary values

into the loop, when 'with lines' specified, the two plots link together (plot points join up). Using dots solves this but I would like both plots to be separately linked with lines and hopefully different colours. Can someone help?
This is the form of the plot i'd like:

A: Data which is piped to gnuplot can be used only once. So, if you want to have two plots, with different colors, you must use '-' twice and then send your data sets one after the other, separated by an e:
void gnuprint(FILE *gp, double x[], int N)
{
    int i;
    fprintf(gp, "plot '-' with lines, '-' with lines\n");

    for (i=0; i<N; i++){fprintf(gp, "%g %g\n", x[i],WF[2*i+1]);}
    fflush(gp);
    fprintf(gp, "e\n");

    for (i=0; i<N; i++){fprintf(gp, "%g %g\n", x[i],WF[2*i+2]);}
    fflush(gp);
    fprintf(gp, "e\n");
}