text:
Q: Concat array of nested documents in MongoDB I am trying to concat some nested documents inside an array using MongoDB shell:
What I have
"id": 1,
"instructions": [
{"text": "A"},
{"text": "B"},
{"text": "C"}
]

What I want to obtain
"id" : 1
"instructions": "ABC"

What I have tried
{
        $project: {
                "instructions": {
                    $reduce: {
                        input: "$instructions.text",
                        initialValue: [],
                        in:  {
                            $concat : ["$$value", "$$this"]
                        }
                    }
                }
        }
    }

What I obtain
$concat only supports strings, not array

A: What you have tried was correct. But you need to make initailValue as String, not array
{
    $project: {
      "instructions": {
        $reduce: {
          input: "$instructions",
          initialValue: "",
          in: {
            $concat: [
              "$$value",
              "$$this.text"
            ]
          }
        }
      }
    }
  }

Working Mongo playground


text:
Q: ASP.NET C# Webcam Integration I'm curious, how do you integrate a webcam with an ASP.NET C# application in a 'live broadcast' type scenario? I have no idea where to start with this but really interested to learn how it works in terms of detection and live streaming. A point in the right direction would be great, thanks.

A: Nothing to do with ASP.NET MVC really. The camera's on the client, so you need to use client scripting such as Flash or Silverlight to access it. Here's for example a jquery plugin (based on Flash) which allows you to control the camera (once the client authorizes the site to do so).
HTML5 might also be an option one day.

redpajama_set_name: RedPajamaStackExchange


text:
Q: gdb, breakpoint in multiple locations I've set a breakpoint in one of the .h files which has an implementation of a small method,
(gdb) break SmallVector.h:141

And here is what I got from gdb:
Breakpoint 5 at 0x416312: SmallVector.h:141. (38 locations)

Why is the breakpoint set in 38 locations instead of a single location?
I'm not new to debugging as well as C++ but unfortunately I've never worked with anything complex like I'm working now (compiler). So I've never encountered anything like this before.
Any help is appreciated.

A: There are several ways that this can happen.
One main way, as you've found, is an inline function.  Some compilers (like gcc) will emit debugging information about the inlining it has done.  gdb sees this information and will try to set a breakpoint at every inlined location.
Another typical way for this to happen is with templates.  Each template instantiation will have the same location, so break file:line will result in a breakpoint in every instantiation.
Yet another way for this to happen is if you use break function and there are multiple functions of the same name.  One scenario here that often confuses new users is that, under the hood, the compiler often emits multiple copies of a constructor (look up "in charge constructor" for the gory details).
One final way this can happen is if the compiler does other sorts of optimization, like partial inlining.  These are more rarely seen.

A: This happens to me whenever I add a breakpoint in a header file with a template implementation..
The answer would be that every time there is an inline function call the breakpoint will be set at that location, this often happens with template implementations in a header file :)
To force a function to be inline you will have to specify an __attribute__ function flag for the compiler! For example
#include <iostream>
using std::cout;
using std::endl;

__attribute__ ((always_inline))
inline void function() {
    cout << "Hello World" << endl;
}

int main() {
    cout << "Hello World" << endl;

    return 0;

}

Credits to @IwillnotexistIdonotexist


text:
Q: Finding multiple solution of a matrix I have this matrix from a book's exercise.
$$
\left[
\begin{array}{@{}cccc@{}}
a&0&b & 2 \\
a& a& 4 & 4 \\
0&a& 2 & b\\
\end{array}
\right]
$$
be the augmented matrix for linear system. Find for what values of ${a}$ and ${b}$ the system has:

*

*a unique solution

*a one parameter solution

*a two parameter solution

*no solution

My questions:

*

*How do i solve this? what should i use? gauss-jordan elimination? row operation?
crammer's rule?

*Can someone please explain what one parameter means? i have hard time comprehending it

Please help.
Thanks.

A: I like to think of $a$ and $b$ as being real numbers I don't happen to know.
Your task is to write something like "There is a unique solution if and only if [some conditions on $a$ and $b$]" and so on for the other cases.
You can determine the number of solutions from the row echelon form (found via Gaussian elimination, i.e., row operations).

*

*It might not be consistent (no solutions).  This occurs if and only if there is a row such as $[0\ 0\ 0\ 1]$ in the row echelon form (which is equivalent to the equation $0=1$).

*There might be a unique solution.  In this case, there will be three leading entries (one in each row) in row echelon form.

*There might be a one-parameter solution.  In this case, there will be two leading entries (and thus a row of zeroes) in row echelon form.
And so on.
A "one-parameter solution" is when the solution space is a line.  As a more simple example
$$
\left(
\begin{array}{cc|c}
1 & -1 & 0 \\
2 & -2 & 0 \\
\end{array}
\right)
$$
has infinitely many solutions: $(x,y)=(t,t)$ for all $t \in \mathbb{R}$.  Here we have one parameter: $t$.  The solution space is the line $\{(t,t):t \in \mathbb{R}\}$.
The system of equations
$$
\left(
\begin{array}{ccc|c}
1 & -1 & 0 & 0 \\
2 & -2 & 0 & 0 \\
\end{array}
\right)
$$
would have a two-parameter solution space: $\{(t,t,u):t,u \in \mathbb{R}\}$.

A: By preformin row operations we reduce the matrix to
$$\begin{pmatrix}
a&0&2&4-b\\
0&a&2&b\\
0&0&b-2&b-2\\
\end{pmatrix}$$
Now the system has a unique solution iff the matrix has rank $3$ and this happens when
$a\neq 0$ and $b\neq 2$.
For a one parameter solution the matrix must have rank $2$ and its easy to see that this happens only when $b=2$ and $a\neq 0$.
For a two parameter solution we need rank of $1$ and if we set $a=0$ we see that
$$\begin{pmatrix}
0&0&2&4-b\\
0&0&2&b\\
0&0&b-2&b-2\\
\end{pmatrix}$$
and in order for this to be consistent we need $4-b=b$ so $b=2$
and we have
$$\begin{pmatrix}
0&0&2&2\\
0&0&2&2\\
0&0&0&0\\
\end{pmatrix}$$ which has rank of $1$. In order for no solution as remarked we have $a=0$ and $b\neq 2$.


text:
Q: Anonymous subroutine call in Perl Trying to understand a piece of code in Perl as follows
    my @a = qw(A B C D E F F A K O N D);
    my @b = qw(S F S T F F S);

$s=sprintf "%s %s %d %d:%d:%d %d: %s" ,   sub { ($a[$_[6]], $b[$_[4]], $_[3], $_[2], $_[1], $_[0], $_[5]+1900) }->(localtime), $s;

This code is in a method in a package  which has been called with three arguments, arrays a and b have been defined in the method above in this code and s is a defined string.
All I can understand is that it is an anonymous subroutine which is expected to return multiple values due to localtime function but I just cannot understand the mechanism that this code follows. I assume I have given enough information to ask this question if not let me know.

A: The syntax is an unusual way of encapsulating the modification of several values at once inside of one statement.
This code is probably used at the end of a subroutine, as it returns a list of values. The real code might look like this.
sub foo {
    my @a = qw(Sun Mon Tue Wed Thu Fri Sat);
    my @b = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);

    my $s = q{foobar};

    #                  wday         month    mday   hour   min    sec    year
    return sub { ( $a[ $_[6] ], $b[ $_[4] ], $_[3], $_[2], $_[1], $_[0], $_[5] + 1900 ) }
        ->(localtime), $s;
}

Let's go through that. I added the return to make it more clear what's happening.
There is an anonymous subroutine sub { ... }, which is defined and directly being called sub { ... }->(). This is like a lambda function. The arrow operator -> in this form is used for calling a code reference. It differs from the direct object syntax (e.g. $foo->frobnicate()) in that there is no method name after the arrow.
my $code = sub { print "@_" };
$code->(1, 2, 3);

This will output:
1, 2, 3

The localtime return value in list context is passed. That's a bunch of values for the current time, as mentioned in the documentation.
#     0    1    2     3     4    5     6     7     8
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
                                            localtime(time);

Without arguments, localtime implicitly uses time as its argument. Inside of the anonymous subroutine, those values end up in @_, which is the argument list of the sub. So $_[0] is the seconds part of the current local date.
Then there is @a and @b, which are really badly chosen names. If it's supposed to be short, I'd at least have called them @d and @m for weekdays and months.
The anonymous sub returns a list of values. It's the current weekday, as looked up in the @a array, where Sunday is index 0, the current month as looked in @b, the day, hour, minute and second, and the year as a four-digit number (hence the + 1900).
The overall function foo returns this list, and another value $s as the last element of its return value list.
If you were to print all of that, you would get:
print join q{ }, foo();

__END__
Mon Sep 25 16 10 33 2017 foobar

In the context of the sprintf, this becomes more clear. It's likely for adding a timestamp to a log entry.
sub log {
    my $s = shift;

    my @a = qw(Sun Mon Tue Wed Thu Fri Sat);
    my @b = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);

    #             0  1  2  3  4  5  6   7
    $s = sprintf "%s %s %d %d:%d:%d %d: %s",
        #        wday        month        mday   hour   min    sec    year
        #        0           1            2      3      4      5      6
        sub { ( $a[ $_[6] ], $b[ $_[4] ], $_[3], $_[2], $_[1], $_[0], $_[5] + 1900 ) }
        #              7
        ->(localtime), $s;

    return $s;
}

print &log('stuff happened'); # we need the & because CORE::log

I've marked each value with the position of the argument inside the sprintf pattern. $s seems to be the log message, which is replaced by the new string with the timestamp, and itself as the last argument.
However, this is a very unusual implementation, given that localtime will return the exact same thing in scalar context.
print &log("stuff happened\n");
print ''.localtime . ": stuff happened\n";

__END__
Mon Sep 25 16:24:40 2017: stuff happened
Mon Sep 25 16:24:40 2017: stuff happened

It's the return value of ctime(3). I first thought maybe it's a reimplementation because on the target system that kind of timestamp does not exist, but the localtime docs also say that this is not system-dependent.

The format of this scalar value is not locale-dependent but built into
  Perl. For GMT instead of local time use the gmtime builtin. See also
  the Time::Local module (for converting seconds, minutes, hours, and
  such back to the integer value returned by time), and the POSIX
  module's strftime and mktime functions.

The implementation with the sub is elegant, though not very Perl-ish. However, it's completely useless because Perl already brings this exact same format.
You could easily replace my log function with this.
sub log {
    my $s = shift;

    $s = localtime . " $s";

    return $s;
}

But then again, if @a and @b are maybe localized, this makes makes sense. You give them as letter, which is probably not your real code, but I could see this being used as for example translating it to German like this.
use utf8;

sub log {
    my $s = shift;

    my @a = qw(So Mo Di Mi Do Fr Sa);
    my @b = qw(Jan Feb Mär Apr Mai Jun Jul Aug Sep Okt Nov Dez);

    #             0  1  2  3  4  5  6   7
    $s = sprintf "%s %s %d %d:%d:%d %d: %s",
        #        wday        month        mday   hour   min    sec    year
        #        0           1            2      3      4      5      6
        sub { ( $a[ $_[6] ], $b[ $_[4] ], $_[3], $_[2], $_[1], $_[0], $_[5] + 1900 ) }
        #              7
        ->(localtime), $s;

    return $s;
}

print &log("stuff happened\n");

Now it makes a lot more sense.


text:
Q: Why the energy distance function give me null result? As mention here https://cran.r-project.org/web/packages/energy/energy.pdf
the e.dist returns Returns the E-distances (energy statistics) between clusters.
And as inputs it accepts data matrix of pooled sample or Euclidean distances.
I want to compute the e-distance between 100 observations of my data set.
Look what I did:
> disteuc<-dist(DATABASE,method = "euclidean")
> edist(disteuc,sizes=100)
dist(0)

Why I get null value ??
This is the first 100 rows of my data set:
> dput(DATABASE[1:100,])
structure(list(TYPE_PEAU = c(2L, 2L, 3L, 2L, 2L, 2L, 2L, 4L,
3L, 2L, 2L, 2L, 2L, 1L, 4L, 2L, 2L, 2L, 4L, 2L, 3L, 3L, 2L, 2L,
2L, 2L, 2L, 4L, 3L, 4L, 2L, 2L, 2L, 2L, 4L, 2L, 1L, 2L, 2L, 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L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L), PROFIL_SELECTIONNE = c(1L, 32L, 21L, 23L, 34L, 31L,
15L, 6L, 1L, 20L, 14L, 34L, 9L, 28L, 28L, 32L, 42L, 20L, 32L,
14L, 20L, 32L, 1L, 5L, 3L, 13L, 32L, 7L, 34L, 14L, 21L, 19L,
34L, 18L, 34L, 31L, 5L, 8L, 1L, 13L, 15L, 32L, 12L, 6L, 19L,
35L, 4L, 36L, 34L, 6L, 31L, 32L, 25L, 4L, 18L, 9L, 23L, 13L,
20L, 34L, 39L, 5L, 9L, 34L, 9L, 34L, 34L, 35L, 18L, 31L, 20L,
3L, 27L, 36L, 1L, 5L, 15L, 18L, 35L, 6L, 31L, 31L, 4L, 34L, 23L,
23L, 20L, 7L, 31L, 3L, 33L, 3L, 2L, 2L, 13L, 7L, 23L, 32L, 32L,
32L), NOMBRE_ACHAT = c(14L, 6L, 3L, 9L, 8L, 13L, 10L, 14L, 4L,
3L, 10L, 8L, 12L, 3L, 7L, 6L, 4L, 13L, 3L, 3L, 6L, 13L, 3L, 4L,
6L, 7L, 4L, 12L, 5L, 6L, 16L, 3L, 14L, 4L, 4L, 6L, 9L, 13L, 3L,
5L, 12L, 4L, 3L, 6L, 3L, 6L, 6L, 3L, 6L, 4L, 3L, 3L, 7L, 3L,
12L, 12L, 10L, 3L, 6L, 7L, 14L, 3L, 18L, 7L, 5L, 4L, 7L, 17L,
6L, 6L, 3L, 6L, 17L, 10L, 12L, 5L, 13L, 15L, 6L, 3L, 11L, 6L,
7L, 7L, 16L, 3L, 3L, 3L, 3L, 6L, 3L, 4L, 3L, 10L, 3L, 4L, 6L,
5L, 14L, 3L), NOMBRE_CADEAU = c(2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L,
1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 3L, 1L, 1L,
2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L,
3L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 2L,
1L, 1L, 1L, 1L, 2L, 1L, 3L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L,
2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 1L,
1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L)), .Names = c("TYPE_PEAU",
"SENSIBILITE", "IMPERFECTIONS", "BRILLANCE", "GRAIN_PEAU", "RIDES_VISAGE",
"ALLERGIES", "MAINS", "PEAU_CORPS", "INTERET_ALIM_NATURELLE",
"INTERET_ORIGINE_GEO", "INTERET_VACANCES", "INTERET_ENVIRONNEMENT",
"INTERET_COMPOSITION", "AGE_INTERVAL", "ATTENTE_BEAUTE_1", "ATTENTE_BEAUTE_2",
"MILIEU_VIE", "PROFIL_SELECTIONNE", "NOMBRE_ACHAT", "NOMBRE_CADEAU"
), row.names = c(NA, 100L), class = "data.frame")
>

A: You are only specifying a cluster size, if you have 100 data and they are all in the same cluster there are no distances to other clusters.
> edist(disteuc,sizes=100)
dist(0)
> edist(disteuc,sizes=c(10, 90))
         1
2 42.51959
> edist(disteuc,sizes=c(10, 40, 50))
         1        2
2 44.32714
3 39.80484 35.26888


text:
Q: How to remove elements from a list on the basis of the rows in Python without messing up the indexes? Le't assume I have a list with elements, from which I want to remove a few rows on the basis of a list of row indexes. This is an example:
l = ['ciao','hopefully','we','are','going','to','sort','this','out']
idx = [1,3,5]

If I do the following, it doesn't work as the loop doesn't consider that the lenght of the list after the nth remove object is n-i:
for x in idx:
            del l[x]

# what happens? The code only removes correctly the first element of idx, then it doesn't take into account that the list has shrunk and therefore the nth index no longer corresponds to the updated row list.

Note, I cannot turn the list into an array and then use np.delete as my list is coming from webscraping and it fails when I try to do so.
Can anyone suggest me a way to remove list's elements on the basis of its rows in one shot without messing up with the shifting of the index?
Thanks!

A: You can use list comprehension and enumerate.
# enumerate give:
# :    0   ,   1       ,  2 ,  3  ,  4    , 5  ,  6   , 7    ,  8
l = ['ciao','hopefully','we','are','going','to','sort','this','out']
idx = set([1,3,5])
out = [el for i, el in enumerate(l) if not i in idx]
print(out)

['ciao', 'we', 'going', 'sort', 'this', 'out']

A: Another approach without enumerate
new_l = [item for item in l if l.index(item) not in idx]

A: If you must delete them in place:
>>> lst = ['ciao', 'hopefully', 'we', 'are', 'going', 'to', 'sort', 'this', 'out']
>>> idx = [1, 3, 5]
>>> for i in sorted(idx, reverse=True):
...     del lst[i]
...
>>> lst
['ciao', 'we', 'going', 'sort', 'this', 'out']

If do not need, you can use list comprehension to create a new list:
>>> lst = ['ciao', 'hopefully', 'we', 'are', 'going', 'to', 'sort', 'this', 'out']
>>> idx = [1, 3, 5]
>>> idx_set = set(idx)
>>> [v for i, v in enumerate(lst) if i not in idx_set]
['ciao', 'we', 'going', 'sort', 'this', 'out']

Of course, you can also achieve the effect of deleting in place through slice assignment:
>>> lst[:] = [v for i, v in enumerate(lst) if i not in idx_set]


text:
Q: Why we don't directly assign values for layout views in android? In creation of UI in android projects ,why we have to refer values of string from the values folder's string.xml?
why eclipse shows warning if we assign values straight away?
I want to know the logic behind this,It's a very basic question but i couldn't find answer for this from google!

A: Another reason that is not covered in the older post pointed out by KenWolf, is that now when uploading your application to the Google Play Store, you can easily make your app more accessible to other languages/locations by uploading just your strings.xml to their new translation service announced at I/O 2013. This just has to do with localizing your resources like was stated here.
You can read more about it here.

A: There are many different advantages to using a string resource file, rather than hardcoding strings. While it may seem pointless and convoluted in small projects, it is incredibly useful in larger projects.

*

*If you know that you want the same string to appear in multiple places, possible occurring in separate activities, the string resource file allows you to reference one source, rather than type the string over and over again.

*If you decide to change a string in you app, or have a dynamically changing string, it is much easier to modify the resource file than it is to manually change all instances of that string in you app

*It is great for localization and translation. If someone wants to port your app to a different language, all you have to do is substitute the strings.xml with a translated version
Thus, it may seem useless in small applications, but for large scale applications, it makes your life much simpler and allows you to more easily reach foreign language users.

A: The reason we are referring from String.xml is we can reuse the same string where ever we want.


text:
Q: Reading a file just by its name, without knowing its directory I am currently working on a project in which I am trying to read some files by only knowing their name, and not the directory in which they belong. The script file might be in the same or in a different folder than the text files (text file directories are unknown).

A: Warning: The following code will run for days, but you asked for it.
# If you would like to limit your search to something reasonable
# replace "/" with your subdirectories.
res = os.subprocess.check_output(["find", "/", "-name", f]).decode("utf-8").split("\n")
for candidate in res:
    with open("candidate", YOUR_FLAGS):
        ... do something

... where f is your file name, and YOUR_FLAGS is whether you want to read it("r") or write("w"), append, etc.
The reasoning behind using os.subprocess for this is that os.walk on giant file systems are not efficient. The overhead of creating a process is alleviated by the fts backend from find, and it will end up costing much less as the number of files scale.

A: If you're asking how to search for a file with a given name, you can use os.walk and check the names match what you're looking for.  Naturally, there may be multiple files with the name you're looking for.

A: This is impossible in one line, but you can use the os module to search for a file in all directories, for example using os.walk().
https://www.tutorialspoint.com/python/os_walk.htm


text:
Q: JMeter CSV datasource tilde character becomes null I am reading variables from a CSV datasource. My typical line is:
1234567890;~
Problem is the tilde is making the second variable null in JMeter. If I replace with this it works:
1234567890;123
I Need the tiled to work because its part of our MVC URL design. Is there an escape or something?
Thanks

A: For the following data it worked for me:
1234567890;~
1234567890;123

view results tree:

CSV Config:

Usage in HTTP sampler:

A: I see some French in your JMeter GUI so it might be something connected with file encoding, the universal one is UTF-8

*

*To verify the encoding:

*

*Add Debug Sampler to your Test Plan and configure it to display System Properties

*Add View Results Tree listener and look for file.encoding property value

*To set the encoding use one of the following approaches

*

*add the next line to system.properties file (located in JMeter's "bin" folder)
file.encoding=UTF-8

*you can also do the same via -D command-line argument (see Apache JMeter Properties Customization Guide for details)
jmeter -Dfile.encoding=UTF-8 -n -t ....

If above steps don't help it might be a problem with your CSV file (some invisible control character, missing line break, etc)


text:
Q: Why use the __all__ variable in Python? I know what it does, how it works and all, but why might we ever want to use it?
I mean if a programmer wanted to import the objects from a module, he could then just use the simple
import <module>

syntax. It's not like the all variable is hiding anything, right?

A: from <module> import * and help(<module>) both use the __all__ attribute of a module to limit what is imported or documented.
Note that from <module> import * is generally considered bad practice unless you are building a central API for a package with the implementation dispersed over various contained modules.


text:
Q: Standard script database variables (Oracle vs Sql Server Terminology) What are the differences/equivalences between Microsoft Sql and Oracle connection parameters, and are there some common names they map to?  Things like "database", "instance", "username", "tablespace".
From Help me put Oracle terminology into SQL Server terminology we get:

| Oracle       | Sql Server    | Universal|
===========================================
| Tablespace   |               |          |
| Database     |               |          |
| Listener     |               |          |
| Instance     | Instance      |          |
| Schema       | Database      |          |
| Service Name | Database Name |          |
| SID          | Database Name |          |
-------------------------------------------

But I'm looking for a universal naming scheme that I can use in application upgrade scripts (as we need to use connection substitution parameters for both databases...).
Is Java's DatabaseMetaData a reasonable object to study?
Is the above table even appropriate? Using connection parameters, the oracle username is the schema name (yes?), and so I'd have a db.user property, and never 'db.schema`?

A: I believe the following is reasonably ok:

| Oracle        | Sql Server    | Universal|
============================================
| machine-name  | machine-name  | Server   |
| Instance      | Instance      | Instance |
| Schema (User) | Database      | Name     |
| User (Schema) | User          | User     |
| Password      | Password      | Password |
--------------------------------------------

Are there any additions anyone else can see?


text:
Q: ASP.NET Authentication POST Policy I am currently working on a POST controller. In the past I've handled logic regarding authentication in the controller itself like this:
    [HttpPost]
    public HttpResponseMessage Post([FromBody] Foo foo)
    {
        if (foo.bar !== user.bar){
            return;
    }

I am not the best c# programmer, so have no clue how this should be handled. While researching I stumbled upon Policies. So I already use a [Authenticated] tag above the controller, but based on if the foo.bar in this example is the same as me.bar I am not allowed to make this post. (So the authenticated tag is for authentication but I want to change the Authorization)
Is it possible that I can make a [Policy=("fooPoster")] and can use the body of the post in there to determine whether I am authorized or not to access the post, or can I only access the global state to determine it?

A: You can try custom authorization. Refer to the code below.
    [HttpPost]
    [CustomAuthorization(Foo.bar)]
    public HttpResponseMessage Post([FromBody] Foo foo)
    {
        if (foo.bar !== user.bar)
        {
            return;
        }
    }

    public class CustomAuthorizationAttribute : AuthorizeAttribute
{
    private readonly string allowedroles;
    public CustomAuthorizationAttribute(string roles)
    {
        this.allowedroles = roles;
    }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool authorize = false;
        if (Me.bar != allowedroles)
        {
            authorize = true;
        }
        return authorize;
    }
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new HttpUnauthorizedResult();
    }
}

For more details you can go through here :


text:
Q: How to select unique strings from a concat of characters I have some columns stored in a dataframe that have the following schema when I call a specific row:
str(df[5,9]) #Output: chr "bike,bike,car"
df[5,9] #Output: "bike,bike,car"

I am trying to find the distinct strings in each row in my dataframe. So the output that I am expecting is: "bike,car"
Similarly, when I call df[5,10], I get: 9,9,10. I would like to only have: 9,10
Is there any way I can find distinct on these strings/integers?
Any help would be great!

A: We can loop through the columns, do a split at the , and get the unique elements and paste it together
df[] <- lapply(df, function(x) sapply(strsplit(as.character(x), ",\\s*"),
                               function(y) toString(unique(y))))


text:
Q: Angular 2 Output Binding not working I try to write my first Angular 2 App. I'm trying to create an Output Binding, but it doesn't work and I found no helpfull solution.
I trigger the function setZoom() from the inner component, and now the zoomChanged() function from the outer component should be triggert, but nothing happens. Same with setSize().
Here's my inner component:
import {Component, EventEmitter, OnInit, Output} from '@angular/core';

@Component({
  selector: 'vk-editor-layer-manager',
  templateUrl: './layer-manager.component.html',
  styleUrls: ['./layer-manager.component.styl']
})
export class LayerManagerComponent implements OnInit {
  @Output('zoomChange') zoomChangeEvent: EventEmitter<number>;
  @Output('sizeChange') sizeChangeEvent: EventEmitter<any>;

  prefZoom: number = 50;

  constructor() {
    this.zoomChangeEvent = new EventEmitter();
    this.sizeChangeEvent = new EventEmitter();
  }

  ngOnInit() {
  }

  setZoom(newZoom: number){
    this.prefZoom = newZoom;
    this.zoomChangeEvent.emit(newZoom);
  }
  setSize(newWidth: number, newHeight: number){
    this.sizeChangeEvent.emit({Width: newWidth, Height: newHeight});
  }

}

Inner components template

    Einstellungen

    Breite:
    <input type="number" id="prefWidth" #EPrefWidth value="1024" />

    Höhe:
    <input type="number" id="prefHeight" #EPrefHeight value="1024" />

    <button (click)="setSize(EPrefWidth?.value, EPrefHeight?.value)">Speichern</button>

    Zoom
    <input type="range" min="0" max="300" id="prefZoom" #EPrefZoom (change)="setZoom(EPrefZoom.value)" [value]="prefZoom" />
    50%
    100%
    150%
    200%
    250%
    300%

    Layer hinzufügen

    Lorem ipsum

And here is the outer component:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'vk-editor-rendering-engine',
  templateUrl: './rendering-engine.component.html',
  styleUrls: ['./rendering-engine.component.styl']
})
export class RenderingEngineComponent implements OnInit {

  canvas = {
    width: 1024,
    height: 1024,
    zoom: 50
  }

  constructor() { }

  ngOnInit() {
  }

  zoomChanged(newZoom: number){
    this.canvas.zoom = newZoom;

    console.log(this.canvas);
  }

  sizeChanged(newWidth: number, newHeight: number){
    this.canvas.width = newWidth;
    this.canvas.height = newHeight;

    console.log(this.canvas);
  }

}

And outer component template:

<vk-editor-layer-manager (zoomChange)="zoomChanged($event)"
                         (sizeChange)="sizeChanged($event.Width, $event.Height)"
></vk-editor-layer-manager>

A: Through the comment of @AJT_82 I found the answer.
In the app.module.ts file (the main file) I removed LayerManagerComponent from bootstrap array. And now it works fine. But I don't know, why.

A:     import {Component, EventEmitter, OnInit, Output} from '@angular/core';

    @Component({
      selector: 'vk-editor-layer-manager',
      templateUrl: './layer-manager.component.html',
      styleUrls: ['./layer-manager.component.styl']
    })
    export class LayerManagerComponent implements OnInit {
      @Output() zoomChangeEvent: EventEmitter();
      @Output() sizeChangeEvent: EventEmitter();

      prefZoom: number = 50;

      ngOnInit() {
      }

      setZoom(newZoom: number){
        this.prefZoom = newZoom;
        this.zoomChangeEvent.emit(newZoom);
      }
      setSize(newWidth: number, newHeight: number){
        this.sizeChangeEvent.emit(new setSizeEventObject(newWidth, newHeight});
      }

    }

   export class setSizeEventObject {
      public Width: number;
      public Height: number;
      constructor(_width : number , _height : number){
         this.Width = _width;
         this.Height = _height;
      }
   }

 sizeChanged(event : setSizeEventObject){
    this.canvas.width = event.newWidth;
    this.canvas.height = event.newHeight;

    console.log(this.canvas);
  }


text:
Q: Source file exists on a broken HDD, can't uninstall program Currently I'm trying to install a program I used a long time ago. It's a newer version of the old program. The problem lies with the previous install. I installed it on an external HDD that no longer works. There are some residual files on my internal store--enough that the computer recognizes the program as having been "installed"; however, because the source file only existed on the external (I was like 14 when I last used that HD, and an irresponsible user, at that), I can't modify/uninstall/repair the old version. Now when I try to install the new version, I get an error reading along the lines of "Make sure the source file exists and that you can access it."
So what do I do if the source file doesn't exist, and I can't access it?
tl;dr: source file is stored on a broken HDD, can't uninstall program from my internal HDD or install new version of broken program

A: Use the "Program Install and Uninstall Troubleshooter" and follow the prompts to fix the issue.
https://support.microsoft.com/en-us/help/17588/windows-fix-problems-that-block-programs-being-installed-or-removed
I recommend starting by choosing the option that you can not uninstall a program.

A: I've had good results from using the registry cleaner in CCleaner to purge all "useless" registry entries. Of course, when the program suggests to back up the registry, it's wise to do so. Add another layer of protection by creating a restore point prior to these operations.
Also, I've had to run the registry clean sequence multiple times to get all the dead wood out.
That will usually remove remnants of broken software. It's also a good idea to search for file folders that contain the program name in advance.

A: I've personally used a utility called Revo Uninstaller to forcibly remove the files and registry entries a bad Uninstaller cannot remove.
A nice feature of this tool is that it tries to create a Restore Point before each process, and you can backup the registry files it will remove before removing them, making it easy to recover if you remove something incorrectly.


text:
Q: AnyDesk on Windows Server My employees connect to work using RDP to a server. I want to monitor what work they are doing on the company's server. AnyDesk or TeamViewer do not work as request returns to same server. Any solutions?

A: RDP Shadowing is the most probable solution in this case. You can set RDP shadowing powers in GPEDIT.MSC at - Policies -> Administrative Templates -> Windows components -> Remote Desktop Services -> Remote Session Host -> Connections. Then type in the command in cmd with administrative rights -
Mstsc.exe /shadow:<Session ID> /Control
Get session id by this command - query session.


text:
Q: Haskell Tokens in expression `A._` How does Haskell interpret the expression A._?
E.g. in main = print $ A._.
Haskell throws the following error error:
source_file.hs:1:16:
    Found hole '_' with type: r0
    Where: 'r0' is an ambiguous type variable
    Relevant bindings include
      main :: IO ()
        (bound at source_file.hs:1:1)
    In the second argument of '($)', namely 'A._'
    In the expression: print $ A._
    In an equation for 'main': main = print $ A._

However, according to Haskell's Syntax Reference, A._ should be interpreted as consym (A), varsym (.) and reservedid (_), since _ is not a valid varid (varids cannot be reservedids).
Haskell throws the same error for main = print $ A._t:
source_file.hs:1:16:
    Found hole '_t' with type: r0
    Where: 'r0' is an ambiguous type variable
    Relevant bindings include
      main :: IO ()
        (bound at source_file.hs:1:1)
    In the second argument of '($)', namely 'A._t'
    In the expression: print $ A._t
    In an equation for 'main': main = print $ A._t

In this case however, the token sequence should be qvarid (A._t) as A matches modid and _t matches varid.
Can anybody help me out and explain what is going on?

A: These are typed holes, which are part of a GHC extension enabled by default. From this link:

Typed holes are a feature of GHC that allows special placeholders written with a leading underscore (e.g., "_", "_foo", "_bar"), to be used as expressions. During compilation these holes will generate an error message that describes which type is expected at the hole's location, information about the origin of any free type variables, and a list of local bindings that might help fill the hole with actual code. Typed holes are always enabled in GHC.

That means that A._ gets parsed as an application of composition, (.), to the constructor A and the typed hole expression _. The same holds for A._t.
The purpose of typed holes is mostly debugging: it lets you know what type GHC infers an expression in that position should have and reports that in an error message.


text:
Q: How to ignore NA in ifelse statement I came to R from SAS, where numeric missing is set to infinity. So we can just say:
positiveA = A > 0;

In R, I have to be verbose like:
positiveA <- ifelse(is.na(A),0, ifelse(A > 0, 1, 0))

I find this syntax is hard to read. Is there anyway I can modify ifelse function to consider NA a special value that is always false for all comparison conditions? If not, considering NA as -Inf will work too.
Similarly, setting NA to '' (blank) in ifelse statement for character variables.
Thanks.

A: Try this:
positiveA <- ifelse(!is.na(A) & A > 0, 1, 0)

A: This syntax is easier to read:
x <- c(NA, 1, 0, -1)

(x > 0) & (!is.na(x))
# [1] FALSE  TRUE FALSE FALSE

(The outer parentheses aren't necessary, but will make the statement easier to read for almost anyone other than the machine.)

Edit:
## If you want 0s and 1s
((x > 0) & (!is.na(x))) * 1
# [1] 0 1 0 0

Finally, you can make the whole thing into a function:
isPos <- function(x) {
    (x > 0) & (!is.na(x)) * 1
}

isPos(x)
# [1] 0 1 0 0

A: Replacing a NA value with zero seems rather strange behaviour to expect. R considers NA values missing (although hidden far behind scenes where you (never) need to go they are negative very large numbers when numeric ))
All you need to do is A>0 or as.numeric(A>0) if you want 0,1 not TRUE , FALSE
# some dummy data
A <- seq(-1,1,l=11)
# add NA value as second value
A[2] <- NA
positiveA <- A>0
positiveA
 [1] FALSE    NA FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE

 as.numeric(positiveA) #
 [1]  0 NA  0  0  0  0  1  1  1  1  1

note that
ifelse(A>0, 1,0) would also work.
The NA values are "retained", or dealt with appropriately. R is sensible here.

A: If you are working with integers you can use %in%
For example, if your numbers can go up to 2
test <- c(NA, 2, 1, 0, -1)

other people has suggested to use
(test > 0) & (!is.na(test))
or
ifelse(!is.na(test) & test > 0, 1, 0)

my solution is simpler and gives you the same result.
test %in% 1:2

A: YOu can use the missing argument i if_else_ from hablar:
library(hablar)

x <- c(NA, 1, 0, -1)

if_else_(x > 0, T, F, missing = F)

which gives you
[1] FALSE  TRUE FALSE FALSE


text:
Q: Power Supply Output Voltage Query I have been given a small board which consists of 4 photodiodes and a precision amplifier.
To power the opamp I need to supply it with +2V and -37V according to the schematic I've been given.
Below is the schematic of the power supply that supplies this board and I was having difficulty understanding it completely

simulate this circuit – Schematic created using CircuitLab
The parts I think I understand is the 4 diodes that make the bridge rectifier. C3 and C4 are ripple smoothing capacitors and that V+ will be ~14V (10V x √2 - 0.7Vf) and V- will be ~-14V (-10V x √2 - 0.7Vf) although please correct me if I'm wrong.
The part I have trouble with is the voltage I've labelled 'X'. It has to be more negative than -37V otherwise the LM337 wouldn't be able to regulate it to -37V.
I'm going to make an assumption that it's something to do with C1 and C2 being connected to the AC input lines of the bridge made from the S1ML diodes connected to 'X' but I can't quite figure out the last bit myself.

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. (a) Charging the C1. (b) Transferring charge to C2.
For simplicity I will ignore all diode drops in this explanation.

*

*The 10 V secondaries of your transformer will peak to \$ +10 \sqrt{2}~V \$ and \$ -10 \sqrt{2}~V \$.

*At peak voltage the top end of C1 will be at +14 V and the bottom will be pulled to -14 V via D3. The capacitor will be charged to 28 V.

*As the polarity reverses the voltage at the top of C1 is pulled down. The voltage at the bottom will attempt to maintain the 28 V difference. D3 will be reverse biased and will effectively be out of circuit (Figure 1b).

*As the top of C1 reaches -14 V the bottom will have been pushed down to -42 V.

*C2 will charge to -42 V via D6.

Your circuit has two of these charge pumps running on alternate half-cycles to improve the output current.
Drop a few volts for the diodes and you've still got enough to run the LM337.

A: Looks like voltage summing, from common reference between C3 and C4 -14V being added. Check Voltage multiplier
BTW, there are 2 diode voltage drops at rectifier.


text:
Q: how can i send an email when user register but to the specific email in Laravel 8 I need when a user registers successfully to send notification email to the reference email field
the notification include one line text with link buttom and when he click on the buttom will redirect to my website
I need to send that notification to the referance_email field
public function create(array $input)
    {   $massage = ['tc_no_pasaport_no.unique'=> 'Sorry, internal error .',
        'phone.unique'=>'Sorry, internal error .' ];

       Validator::make($input, [
            'phone' => ['required', 'string', 'max:255','unique:users'],

            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],

            'tc_no_pasaport_no' => ['required','max:11','unique:users'],
            'place_of_birth' => ['required'],
            'date_of_birth' => ['required'],
            'educational_status' => ['required','string'],
            'school_department' => ['required'],
            'address' => ['required'],

            'password' => $this->passwordRules(),
            'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
        ],$massage)->validate();

        $users = User::where('email', '=', $input['email'])->first();
            if ($users === null) {
            return User::create([

            'name' => $input['name'],
            'email' => $input['email'],
            'phone' => $input['phone'],

            'password' => Hash::make($input['password']),
            'membership_status' =>'pasif',
            'membership_type' =>'standard',
            'last_activation_date' =>  Carbon::now(),
            'membership_end_date' =>  Carbon::now(),
            'temporary_id' => random_int(1000000, 9999999),
            'tc_no_pasaport_no' => $input['tc_no_pasaport_no'],
            'place_of_birth' => $input['place_of_birth'],
            'date_of_birth' => $input['date_of_birth'],
            'educational_status' => $input['educational_status'],
            'school_department' => $input['school_department'],
            'Institution_and_unit' => $input['Institution_and_unit'],
            'address' => $input['address'],
            'referance_email' => $input['referance_email'],
            'letter_of_Intent'=>$input['letter_of_Intent'],
            'created_at' => Carbon::now(),

        ]);

    }

A: You can use PHP Mailer library to send email in PHP.


text:
Q: How to reset the input css to the defaults in Bootstrap 3.2 I changed the default border css for a specific input element in bootstrap 3.2 to be green by using the following code:
$('#' + fieldID).css({
    'border-color': '#00b300',
    'border-width': '1px',
    'box-shadow': 'none',
    'outline': 'none',
    '-webkit-box-shadow': 'none'
});

where fieldID is the name of the input field
Now in a specific scenario, I would like to reset this field to the default behaviour/styling.
I managed to get it to look like a default focused in field by using the following:
$('#' + fieldID).css({
    'border-color': '#9ecaed',
    'border-width': '1px',
    'box-shadow': '0 0 10px #9ecaed',
    '-webkit-box-shadow': '0 0 10px #9ecaed',
    'outline': 'none'
});

this however does not restore the default behavior where the default field has a grey border and focused one has blue (as shown below)

Please guide me if there is a way to restore normal behavior, I have even tried cloning the element in jQuery, but that copies the styling and thus in vain.
Thanks for reading this

A: Simply we can do like this
<style>
    .myClass {
            border-color:#9ecaed;
            border-width: 1px;
            box-shadow: 0 0 10px #9ecaed;
            -webkit-box-shadow: 0 0 10px #9ecaed;
            outline:none;
     }

</style>

jquery be . if you add the class like this
$('#'+fieldID).addClass("myClass");

reset you want to remove the class
$('#'+fieldID).removeClass("myClass");

A: Do not style that via jQuery. Create new CSS class, for example default-input and in your jQuery, you will do this to set default:
$('#'+fieldID).addClass('default-input');

and to reset to bootstrap-default:
$('#'+fieldID).removeClass('default-input');


text:
Q: Get post title by Alphabet I try to call this function to get a list of posts by alphabet. But for some reason i keep getting an error. Call to a member function get_col() on a non-object.
What am i doing wrong?
{function get_post_by_alphabet($the_char){
$first_char = $the_char;

$postids=$wpdb->get_col($wpdb->prepare("
SELECT      ID
FROM        $wpdb->posts
WHERE       SUBSTR($wpdb->posts.post_title,1,1) = %s
ORDER BY    $wpdb->posts.post_title",$first_char));

if ($postids) {
$args=array(
  'post__in' => $postids,
  'post_status' => 'publish',
  'posts_per_page' => -1,
  'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
 echo 'List of Posts Titles beginning with the letter '. $first_char;
  while ($my_query->have_posts()) : $my_query->the_post();
    echo '
<'.the_title().'
';
  endwhile;
}
wp_reset_query();  // Restore global post data stomped by the_post().
}
}

get_post_by_alphabet('H');
}

A: You have two problems. First need to global $wpdb;.  Then you are using the_title() and the_permalink() both of which automatically echo out a value. So you need to switch them to get_the_title() and get_permalink().
function get_post_by_alphabet($the_char){

global $wpdb;

$first_char = $the_char;

$postids=$wpdb->get_col($wpdb->prepare("
SELECT      ID
FROM        $wpdb->posts
WHERE       SUBSTR($wpdb->posts.post_title,1,1) = %s
ORDER BY    $wpdb->posts.post_title",$first_char));

if ($postids) {
$args=array(
  'post__in' => $postids,
  'post_status' => 'publish',
  'posts_per_page' => -1,
  'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
 echo 'List of Posts Titles beginning with the letter '. $first_char;
  while ($my_query->have_posts()) : $my_query->the_post();
    echo '
<'.get_the_title().'
';
  endwhile;
}
wp_reset_query();  // Restore global post data stomped by the_post().
}
}

get_post_by_alphabet('H');


text:
Q: kubernetes pod name rule In process install of my kubernetes cluster, I ran into the problem of naming pods.
How to add to the name of the container the name of the node on which it is was deployed?
Exemple of my Daemon Set yaml:
....
spec:
  template:
    spec:
      name: CONTAINER-NAME-HOST-NAME
....

A: Naming convention falls under the RFC 1123 definition of a DNS label.
Starting from v1.4 names must not be longer than 253 characters.
Name should be expressed by the regular expression: [a-z0-9]([-a-z0-9]*[a-z0-9])?
Underscore "_" is not allowed.
You can see applicable code in GitHub for checking container names, defining acceptable names.


text:
Q: Redirect stderr through grep -v in LSF batch job I'm using a library that generates a whole ton of output to stderr (and there is really no way to suppress the output directly in the code; it is ROOT's Minuit2 minimizer which is known for not having a way to suppress the output). I'm running batch jobs through the LSF system, and the error output files are so big that they exceed my disk quota. Erk.
When I run locally on a shell, I do:
python main.py 2> >( grep -v Minuit2 2>&1 )

to suppress the output, as is done here.
This works great, but unfortunately I can't seem to get that or any variation of it to work when running on LSF. I think this is due to LSF not spawning the necessary subshell, but it's not clear.
I run on batch by passing LSF a submit script. The relevant line is:
python main.py $INPUT_FILE

which works great, aside from the aforementioned problem of gigantic error files.
When I try changing that line to
python main.py $INPUT_FILE 2> >( grep -v Minuit2 2>&1 )

I end up with
./singleSubmit.sh: line 16: syntax error near unexpected token `>'
./singleSubmit.sh: line 16: `python $MAIN $1 2> >( grep -v Minuit2 2>&1 )'

in the error log file.
Any idea how I could accomplish what I want, or why this is not working?
Thanks a ton!

A: The syntax you're using works in bash, not in csh/tcsh.  Try changing the first line of your submission script to
#!/bin/bash


text:
Q: Slideshow overlaps footer I'm working on a responsive page, and tried everything (including the search function here) but the footer keeps sliding under the  content/slideshow. What am I doing wrong?

Style-sheet:

#wrapper { width: 900px; margin: 0 auto 0 auto; }
#content { padding: 20px 30px 0 30px; height: auto; }
.slideshow { position:relative; height:auto; max-width: 100%; margin-bottom: 10px; }
.slideshow img { max-width:100%; height: auto; }
#footer { padding: 20px 0 0 0; }

A: There is no way to make absolute element take space on a page, because they don't do that by definition.  However you can give a height to the #content to fix.
Since you know the height of your images (according to your jsfiddle in the comments), so you can add height:450px; to your #content because height:auto will not see any height on your absolute positioned elements.
#content { padding: 20px 30px 0 30px; height:450px;}
JSFiddle: http://jsfiddle.net/0qe47o5e/3/
OR Code Snippet

* { margin: 0; padding: 0; }
#wrapper { width: 900px; margin: 0 auto 0 auto; }
#content { padding: 20px 30px 0 30px; height: 450px; }
.slideshow { position:relative; height:100%; max-width: 100%; margin-bottom: 10px; }
.slideshow img { max-width:100%; }
#footer { padding: 20px 0 0 0; }

   Footer HERE


text:
Q: Will class method referencing the class instance but not via self cause circ dependency, and how to fight it? if class B is a child of A, would the following code cause circular dependency?
(I don't make difference between A, B, and A(), B() for simplicity)
def random_function(B):
    # get parent
    par = B.A

    do_stuff(par, B)

class A:

    def method(self):
        # get B
        b = A.B
        random_function(b)
        # random_function will reference A now, but not via self, is this a problem?

I know, that is easily solved with
def random_function(A,B):
    do_stuff(A, B)

class A:

    def method(self):
        # get B
        b = A.B
        random_function(self, b)

... but I wonder whether I can still keep the signature with only one argument.
if this is too abstract, here is why I am asking: in Blender, there is a socket class and a node class, with sockets being children of a node. I have a subclass of node and a function like follows:
def func(socket):
    # get parent
    node = socket.node
    do_stuff(node, socket)

class sub_class(Node):

    def method(self):
        func(self.Socket)

is there a way to keep the function signature with only one argument and not run into circular dependency here?
EDIT: an edit to supply some actual code and context, following suggestions in comments
I'll start with the description of the classes that, as I believe, are causing the circular reference.
Class ShaderNodeCustomGroup represents a node - a thing from visual programming. It has sockets and it's listetning to what is happening on those sockets. User connects inputs to input sockets, can get output from output sockets. Basically a visual representation of a function for non-programming users. Unreal has this as well, but mine is from Blender.
Class Socket, already mentioned above - this is what can take input and what gives you output.
I do not know, how exactly they interact - that's defined in source code, and I am just using API but somehow I crash entire application if I do the following:
function causing the crash:
def get_socket_neighbor(socket, offset):
    """
        get the neighbor of this socket, whose position is specified by the offset
        RETURNS: a socket or OUT_OF_RANGE
        NOTE: offset is not for the Blender socket order, it's acual movement by 'offset' socket up or down in world coordinates
    """
    sock_ind = get_socket_index(socket, socket.node)
    desired_position = sock_ind - offset # <--- the actual position in 'blender coordinates'
    if desired_position > (len(socket.node.inputs)-1) or desired_position < 0:
        return OUT_OF_RANGE
    else:
        return socket.node.inputs[desired_position]

This one, for a socket in a node, finds its neighbor: for example, a socket one position up, or one position down (see the illustration for nodes and sockets, sockets are the small circles). What it does, it takes a socket, gets the node, to which it belongs, deduces the position of the socket (sock_ind = get_socket_index(socket, socket.node)), and returns a neighbor socket.
Now, I construct a subclass of ShaderNodeCustomGroup (in the following SUBCLASS). This subclass can spawn its UI and have sockets and do all the stuff that a node can do. It just has several additional features that I can define. From this class's method, the above function is called. SUBCLASS gives one of its sockets as input to this function. The function is then getting the socket's node (this is simply SUBCLASS itself). This crashes the application.
class LayerStackNode(bpy.types.ShaderNodeCustomGroup):
            bl_label = "Layer Stack"

       .
       .
       .

        def insert_link(self, link):
    # runs on the insert of a link,
    # this is a preferred method when
    # it gets repaired by blender devs

        # check if the user is connecting mask
        if link.to_socket.name == "mask_layer":
            # simply draw a link from this socket to its mixer
            my_index = mf.get_socket_index(link.to_socket, self)
            relevant_layer = mf.get_socket_neighbor(link.to_socket, 1)
            relevant_mixer = mf.get_node_by_type(self.node_tree.nodes, 'GROUP_INPUT').outputs[my_index - 1].links[0].to_node
            self.node_tree.links.new(relevant_mixer.inputs[0], mf.get_node_by_type(self.node_tree.nodes, 'GROUP_INPUT').outputs[my_index])
            return

        def is_insert_input(self, link):
        # determines whether the iserted link is input
            if link.to_socket.name == 'layer':
                return True
            else:
                return False

        if not is_insert_input(self, link):
            return

        # if trying to insert on top of an empty layer, cancel and return
        if mf.get_socket_neighbor(link.to_socket, -1) != mf.OUT_OF_RANGE and \
            mf.get_socket_neighbor(link.to_socket, -1).is_NULL_layer:
            # TODO: find a way to undo the operation
            return

        if self.is_NULL_layer(link.to_socket): # proceed only if it's empty
            if not mf.get_socket_index(link.to_socket, self) == (len(self.inputs)-1): # <--- private case for the lowest layer in the stack
                if not self.is_NULL_layer(mf.get_socket_neighbor(link.to_socket, -1)):
                    self.initialize_layer(link.to_socket)
                else:
                    print("CANNOT MIX ONTO NULL LAYER")
            else:
                # when base layer, create a single link from input to output
                sock_index = mf.get_socket_index(link.to_socket, self)
                out = mf.get_node_by_type(self.node_tree.nodes, 'GROUP_INPUT').outputs[sock_index]
                inp = mf.get_node_by_type(self.node_tree.nodes, 'GROUP_OUTPUT').inputs[0]
                self.node_tree.links.new(inp, out)
        else:
            print("no action needed, the layer is not NULL")

       .
       .
       .

Relevant for you is mf.get_socket_neighbor(link.to_socket, -1).is_NULL_layer.
Here the class of the node gives one if its sockets to the function, and it then tries to find the node of this socket, which is the calling class itself.
To sum up, SUBCLASS's method gives SUBCLASS's socket to a function, which then is trying to access the socket's node, which is SUBCLASS itself. If I rebuild the code, so that the function simply takes self, and does not have to access socket.node, everything works.
So, my question is: is this circular reference? If yes, are there ways to overcome it? I do care because that makes using classes less sensible: for example, I cannot define a property of socket which accesses its node. Because if I use this property from inside a node method, this will crash application as well.

A: There is no parent/child relationship here, either explicitly shown or implied.  B.A and A.B do not suggest parent/child relationships.  They just say that B contains an attribute name 'A' and A contains an attribute named 'B'.  There's nothing wrong with this at all (naming conventions aside).  The two names have nothing to do with each other, nor do they have anything to do with a parent/child relationship. In the case of B.A, the 'A' has nothing to do with the class named 'A'.
Regarding:
# random_function will reference A now, but not via self, is this a problem?

no, random_function will not reference A.  random_function will reference whatever the A class's B attribute contains.


text:
Q: Green's function for free scalar field theory as an inverse of $-(\partial^2+m^2)$ In his book [QFT in a Nutshell], Zee argues that the functional integral
$$Z= \int D\varphi \; e^{i\int d^4x[ -\frac{1}{2}\varphi(\partial^2+m^2)\varphi + J\varphi]}$$
can be evaluated by discretizing the spacetime. To be specific, we imagine a grid of spacing $a$ and replace the function $\varphi(na)$ by the vector $\varphi_n = \varphi(na)$, the derivative $\partial\varphi(na)$ by $(1/a)(\varphi_{n+1}-\varphi_{n})$, and so on.
Then the discrete analog of the path integral is just a Gaussian integral
$$\int dq_1\cdots dq_N e^{(i/2)q\cdot Aq + iJ\cdot q} = \left( \frac{(2\pi i)^N}{\det[A]}\right)^{1/2} e^{-(i/2)J\cdot A^{-1}J}.$$
Motivated by this, Zee writes the final answer,
$$Z = C e^{-(i/2) \int d^4x d^4y J(x)D(x-y)J(y)},$$
where $D(x-y)$ is the Green function $-(\partial^2+m^2)D(x-y)=\delta^{(4)}(x-y).$
However, since the differential operator $(\partial^2+m^2)$ has a nonzero kernel, I'm curious about how the operator can be replaced by an invertible matrix $A$. This might be answered by the line of thoughts in this note. That is, by encoding appropriate boundary conditions into $A$. What should be the boundary condition here? Would $\varphi(x)\rightarrow 0$ as $\|x\|\rightarrow\infty$ be the answer?
Furthermore, how do I figure out the explicit form of $D(x-y)$, which is the continuum limit of $A^{-1}_{ij}?$ What is the reasoning behind Zee's assertion that
$$D(x-y)= \int \frac{d^4k}{(2\pi)^4} \frac{e^{ik(x-y)}}{k^2-m^2+i\epsilon}
= -i\int \frac{d^3k}{(2\pi)^3 2\omega_k}[e^{-i(\omega_k t-\vec{k}\cdot\vec{x})}\theta(x^0)+e^{i(\omega_k t-\vec{k}\cdot\vec{x})}\theta(-x^0)],$$
and not one of the other solutions, e.g. the retarded and advanced propagators $D_{ret}(x-y), D_{adv}(x-y)$? This question is closely related to this one, which was answered comparing the canonical and path integral formulations. Could it be done by imposing a boundary condition without referring to the canonical approach?

A: In general you may choose whatever boundary conditions you like for your fields. The condition you mention is standard, but certainly not the only kind of condition that appears in application. It really depends on what you're looking to do.
To compute $D$, the standard procedure is to being Fourier transforming everything into momentum space. Once you do so, you'll note that the Fourier transform of $D$ may be solved for algebraically. Then simply Fourier transform back. This is precisely what Zee what done to obtain the expression you've noted for $D$. This will always work for Poincare invariant quadratic terms in the Lagrangian because explicit spacetime coordinate dependence is prohibited by translation symmetry, and hence the Fourier transform of the kinetic term will always be algebraic in momentum space.
You are correct that the operator $k^2-m^2$ is generically not invertible and indeed will not be invertible on-shell since then $k^2=m^2$. This is why the $i\epsilon$ is there. The operator $k^2-m^2+i\epsilon$ is invertible (for real-valued momenta) because it has no zeros on the real line as they have been shifted off it by the addition of the small complex number $i\epsilon$.
The proper way of introducing this $\epsilon$ into the action is to note that the partition function produces vacuum expectation values, and hence there is technically an insertion of $\Psi_0\Psi_0^*$ into the path integral, where $\Psi_0$ is the vacuum wave functional. Using canonical methods, you can show that the free theory vacuum wave functional is a functional Gaussian and hence this insertion would contribute a term like $\epsilon \int\phi^2$ to the action (there are some fine points about how this should be done. Not sure of a good source that shows this.). This is usually left out, but should be included in a careful analysis. So essentially it is the vacuum wave functional which is ensuring that our kinetic term is invertible.
The assertion about which propagator this represents is dependent only on the direction in which the two zeros in the kinetic term have been moved off the real line. The way these zeros are shifted is fixed by the vacuum wave functionals so there is no ambiguity if the calculation is carried out carefully.
As a final point, I will note that while there are many very interesting things that can be said about boundary conditions in QFT, essentially all of them lead to non-perturbative considerations and can be ignored almost entirely for the sake of a perturbative treatment of the theory (which is what I believe Zee, and essentially all introductory texts on the topic, do). By the way, the demand that the field vanish at infinity can be seen as equivalent to the demand that the action be finite. If you were to Wick rotate the action, you would very quickly see that configurations for which the rotated action (slightly different than the Lorentzian action) diverges have zero contribution to the path integral anyway (since the integrand is $e^{-S_E}$).


text:
Q: AlertDialog not closing when inforamtion is saved My previous question is solved, but now I have another one.
My If condition not working properly
Scenario:
1. If user has not filled up his Name, then Alert Dialog is displayed
2. If user has filled up his Name, then Alert Dialog should NOT displayed
In my case, I will get Alert Dialog in any case, it does not care if Name is filled or not.
ArtistProfileView.Java
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_artist_profile_view, container, false);
        prefrence = SharedPrefrence.getInstance(getActivity());
        userDTO = prefrence.getParentUser(Consts.USER_DTO);
        paramsRate.put(Consts.ARTIST_ID, userDTO.getUser_id());
        parms.put(Consts.ARTIST_ID, userDTO.getUser_id());
        parms.put(Consts.USER_ID, userDTO.getUser_id());
        baseActivity.headerNameTV.setText(getResources().getString(R.string.my_profile));
        if(artistDetailsDTO.getName().isEmpty()) {
            new AlertDialog.Builder(getActivity())
                    .setView(getLayoutInflater().inflate(R.layout.test5, null))
                    .setPositiveButton(R.string.okaypopup22,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    my_tag = 1;
                                    dialogPersonalProfile();
                                }
                            })
                    .show();
        }
        setUiAction(view);
        return view;
}

In the same Class, method which calls profile editing
@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivEditPersonal:
                my_tag = 1;
                dialogPersonalProfile();
                break;
            case R.id.ivEditAbout:
                my_tag = 2;
                dialogAbout();
                break;
            case R.id.ivEditQualification:
                dialogQualification();
                break;
            case R.id.ivEditSkils:
                my_tag = 3;
                dialogSkills();
                break;
            case R.id.ivEditProduct:
                dialogProduct();
                break;
            case R.id.ivEditGallery:
                dialogGallery();
                break;

        }
    }

A: At first I misunderstood your question, so I have edited it.
I guess you should try adding equals() method in if condition
if(artistDetailsDTO.getName().toString.equals(""))


text:
Q: Keep external disk spinning I have a very annoying problem with my notebook. I have an internal SSD drive with system and an external old HDD drive (in optical disk bay) for large games mostly. The problem is, that the HDD drive keeps spinning down, after every 10 seconds of inactivity. This happens no matter what - tried everything (windows power management included), without luck - disk totally ignores all the settings every time. This makes unbearable lags when trying to access new data after spindown, thing that makes most games unplayable. These constant spinups/downs also shortens disk life.
So after trying some methods i decided to write a C# application, which will simply count  lines in a random file from the list below - located on external drive, by reading file line-by-line. Its a winforms app, but method keepSpinning is called in a separated thread.
    List<string> filesToSpin = new List<string>();
    public Form1()
    {
        filesToSpin.Add(@"D:\book\Generic_User_Guide.pdf");
        filesToSpin.Add(@"D:\book\Quick Guide.pdf");
        filesToSpin.Add(@"D:\book\pck_ls.pdf");
        filesToSpin.Add(@"D:\book\guide_amd64.pdf");
    }

    private void keepSpinning()
    {
        while(someKeepAliveVariable)
        {
            Random r = new Random();
            int index = r.Next(filesToSpin.Count);
            string spinThis = filesToSpin[index];
            int counter = 0;
            string line;
            Console.WriteLine("Reading file: " + spinThis);
            System.IO.StreamReader file =
                new System.IO.StreamReader(spinThis);
            while ((line = file.ReadLine()) != null)
            {
                counter++;
            }
            file.Close();
            Console.WriteLine("Read {0} lines.", counter.ToString());
            Thread.Sleep(2000);
        }
    }

Well. Surprisingly, this also doesn't work. It works for a while, but then it keeps printing the info of read file but disk stops. I guess the drive is caching those files somehow. Also lines-counting method is quite CPU intensive.
Any advice on code changes would be helpful, also looking forward for any other solutions.

A: Write to a file on the disk instead of reading. Remember to clear those files out every once in a while to.
Plus on a side note, that HDD doesn't sound good.

A: First of all, thank you all for all the responses. I tried some different approach and finally, after a year of struggling found a solution. Sorry for not giving the HDD name. Here it is: WD750BPVT. I also didn't mention about second problem: the drive was clicking when idle, few times before disk spindown.
I'll answer my own question to save hair on someone's head. The problem was not easy to track.
Writing a C# app was quite good approach, but it has its drawbacks. When I changed the code to write data instead of read, it was quite a success (none spindowns) but the drive was constantly clicking when idle (each 2-3 secs).
Someone would say, that the HDD is ready to die because of clicking sound and I should backup my data while getting ready to trash the device. However I found an explanation. The reason of all these things is a feature, designed to save some power and disk lifetime (sic!). This feature, or actually two of them are:
Automatic Acoustic Management (AAM)
Advanced Power Management (APM)

Power management regulates spindowns and acoustic management is responsible for head parking (clicking noise).
All you have to do is simply disable both of these.
You can do this for example in CrystalDiskInfo: functions -> advanced -> AAM/APM control, select the drive you want and click both disable buttons. Problem solved until reboot. Its not permanent, so adding CrystalDiskInfo to startup is a good move.
This solution might also work for other devices / manufacturers, so if you have similar problem I strongly suggest to try that out.

A: It probably fails because the OS reads a large buffer of the file and puts it in cache.
You can:
*

*write to a file rather than read, flushing the file each time.

*use FILE_FLAG_NO_BUFFERING (then you need to use the win32 API CreateFile).


text:
Q: Navigation Menu Dropdowns Stuck Behind Other Elements I'm having what I believe to be a simple problem but I'm not sure how to fix it.
Basically, while hovering over links on the menu, the drop-down menus "go behind" the other elements on my page. I've tried implementing float css but it doesn't seem to work.
If you visit my site just for a second and hover on the navigation menu you'll see what I mean.
How do you fix something like this?
Will appreciate any help.
Thanks.

A: In your css, set your z-index to a really big number like 9005, so it's above everything else on the page.
Like: z-index: 9005;

A: add z-index:9999; to the #page-bar css
it solves the problem (tested in chrome)


text:
Q: Loading a 3D image and patchifying it on the fly in a DataLoader (Keras) I'm currently trying to train a network with dozens of 3D images. But, these images can't fit in the memory at once that's why I chose to use a pipeline (tf.keras.sequence). This pipeline helps me load he images sequentially. What i want to do next is to patchify these images into patches of size 128x128x128, and I want to do it on the fly, meaning that i want to load an image, divide it to patches and then feed it to the model.
Is there a way in Keras to do this?
PS: I don't want to write the patches to the disk, I wan't to do the patchifying on the fly.


text:
Q: FlutterError (No MediaQuery widget ancestor found. I had used the MaterialApp, but still got error Where has problems in my main.dart? I had used the MaterialApp, but still got error FlutterError (No MediaQuery widget ancestor found.
Do I miss something? But if I remove the MaterialApp, still got error
void main() async {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage('assets/images/my_bg.png'),
                fit: BoxFit.cover),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Container(
                padding: const EdgeInsets.all(16),
                width: MediaQuery.of(context).size.width,
                child: AuthGate(),
              )
            ],
          ),
        ),
      ),
    );
  }

A: Try separating materialApp from app widget context.
void main() async {
  runApp(
    MaterialApp(
      home: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
              image: AssetImage('assets/images/my_bg.png'), fit: BoxFit.cover),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Container(
                padding: const EdgeInsets.all(16),
                width: MediaQuery.of(context).size.width,
                child: Text("AA")
                // AuthGate(),
                )
          ],
        ),
      ),
    );
  }
}

A: runApp(MaterialApp(
    home: MyApp(),
    debugShowCheckedModeBanner: false,
  ));


text:
Q: Understanding the google play console statistics we are currently starting to evaluate the metrics of our app. For june we have the following statistics:

*

*Daily Device Installs: 1696

*Daily Device Uninstalls: 0

*Daily User Installs: 1421

*Install events: 1857

*Uninstall events: 1511

As far as I understood the documentation and various sources on Google the metrics are defined as follows:

*

*Device Installs: First time the app was installed on the device

*Device Uninstalls: First time the app was uninstalled on the device

*User Installs: The first time a user installs this app

*Install events: How often the app was installed (could also be multiple times on the same device)

*Uninstall events: How often the app was uninstalled (could also be multiple times on the same device)

If those are the right definitions then those numbers don't make sense to me.
If we have 1696 new devices with the app and 1857 install events that means that 1857-1696 = 161 times the app was installed more than one time on the device. If now the uninstall events are that much higher (1511-161 = 1350) it means that we have a lot of user who uninstalled our app. Since the device uninstalls equals 0 this mus mean that those user regularly delete our app, right?
When comparing those numbers to the months before we have a similar picture (also device uninstalls = 0  and the uninstall events much higher.
So I assume I have some misunderstanding somewhere.. can anyone explain where I'm wrong in my assumptions?
Best regards,
André


text:
Q: How can I receive SQL Server profiler events? I was tried like so:
using System;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Trace;

namespace SqlProfiller
{
    public partial class Form1 : Form
    {
        TraceServer reader = new TraceServer();
        SqlConnectionInfo connInfo = new SqlConnectionInfo();

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            connInfo.ServerName = @".\SQLR2";
            connInfo.DatabaseName = "DB";
            connInfo.UserName = "sa";
            connInfo.Password = "123";

            reader.InitializeAsReader(connInfo, @"Standard.tdf");

            while (reader.Read())
            {
                Console.WriteLine("SPID  : " + reader["SPID"]);
                Console.WriteLine("Login : " + reader["SessionLoginName"]);
                Console.WriteLine("Object: " + reader["ObjectName"]);
                Console.WriteLine("Text  : " + reader["TextData"]);
                Console.WriteLine();

                textBox1.Text += "Event : " + reader["EventClass"] + Environment.NewLine;
                textBox1.Text += "SPID  : " + reader["SPID"] + Environment.NewLine;
                textBox1.Text += "Login : " + reader["SessionLoginName"] + Environment.NewLine;
                textBox1.Text += "Object: " + reader["ObjectName"] + Environment.NewLine;
                textBox1.Text += "Text  : " + reader["TextData"] + Environment.NewLine;
                textBox1.Text += "----------------------------------------------------------";
                textBox1.Text += Environment.NewLine;
                Application.DoEvents();
            }
        }
    }
}

Error:

Microsoft.SqlServer.Management.Trace.SqlTraceException: Failed to
  initialize object as reader. ---> System.IO.FileLoadException: Mixed
  mode assembly is built against version 'v2.0.50727' of the runtime and
  cannot be loaded in the 4.0 runtime without additional configuration
  information.

Failed to initialize object as reader.
What does this mean?
Thanks in advance

A: What does this mean?
System.IO.FileLoadException: Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
It means that your process in running as a .NET 4 process and the assembly you are loading is .NET 2 compiled (Microsoft.SqlServer.Management).
Either recompile your application to use .NET 2 or add a hint for .NET 4 in config to allow .NET 2 assemblies.

A: If running your code (build in VS 2013 using .NETFramework v 4.5 against Microsoft SQL server 2008, you are getting the following error:
Failed to initialize object as reader.
Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additiona
l configuration information.
You can fix it by changing your App.config in VS project, from default:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

to this one (small addition)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup  useLegacyV2RuntimeActivationPolicy="true">
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

Plus, when I added Assembly using Solution -> add Assembly -> Browse, I used "100" folder, instead of "110" in the path below:
C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.ConnectionInfoExtended.dll

But, may be it will be working with 110 as well.
I hope, this solution will help.


text:
Q: ASP.NET Core view location ignore case on linux Controller:
 [Area("cp"), Route("[area]/[controller]"), Authorize]
 public class AuthController: Controller

Action:
[Route("login"), AllowAnonymous]
public async Task<IActionResult> Login() {return View();}

Real view location is areas\cp\auth\login.cshtml (lowercase)
I found that on linux razor engine trying to find path like this areas\cp\Auth\Login.cshtml (Upper letter)
And result of action is 404 NotFound.
All working find on windows.
 An unhandled exception has occurred while executing the request.
 System.InvalidOperationException: The view 'Login' was not found. The
 following locations were searched:
 /areas/cp/views/Auth/Login.cshtml <--- there is view exist
 /Areas/cp/Views/Auth/Login.cshtml
 /Areas/cp/Views/Shared/Login.cshtml
 /Views/Shared/Login.cshtml
 /Pages/Shared/Login.cshtml

Enabling lowercaseurls not helped
services.AddRouting(options => options.LowercaseUrls = true);

Adding custom IViewLocationExpander too
public class ViewLocationExpander : IViewLocationExpander
{

    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        //{2} is area, {1} is controller,{0} is the action
        var locations = new[]
        {
            "areas/{2}/views/{1}/{0}.cshtml".ToLower(),
        };
        return locations.Union(viewLocations);          //Add mvc default locations after ours
    }

    public void PopulateValues(ViewLocationExpanderContext context)
    {
        context.Values["customviewlocation"] = nameof(ViewLocationExpander);
    }
}

How can i solve this? I dont want to rename my locations to match with upper letter
UPD:
I think that is the best solution for me is get implementation RazorViewEngine from asp.net git repo and add some ToLower() cases to FindView() and GetView() and register it like default engine. But is it ok about license?


text:
Q: Subset vector based on increasing/decreasing trend I have a vector in R defined as c(2,3,4,6,5,3,1,3,5,6).
I want to subset the vector based on all increasing/decreasing trends in the vector.
The desired output should be 3 sub vectors (in this example)
1) (2,3,4,6)
2) (6,5,3,1)
3) (1,3,5,6)

A: x = c(2, 3, 4, 6, 5, 3, 1, 3, 5, 6)
r = cumsum(rle(sign(diff(x)) >= 0)$lengths) + 1
lapply(seq_along(r), function(i){
    x[max(1, r[i - 1]):r[i]]
})
#[[1]]
#[1] 2 3 4 6

#[[2]]
#[1] 6 5 3 1

#[[3]]
#[1] 1 3 5 6

A: Here is an answer that discriminates between up and down trends
dummy_vector = c(2,3,4,6,5,3,1,3,5,6)

# Loop to mark the trend
index = rep(1,length(dummy_vector))  # Pre allocate output vector
for (i in 2:length(dummy_vector)) {
  if (dummy_vector[i] > dummy_vector[i-1]) {
    index[i] = 1 # trend up
  }
  else if (dummy_vector[i] < dummy_vector[i-1]) {
    index[i] = 2 # trend down
  }
  } # end loop

# Mark changes in trend
change_trend = rep(0,length(index))  # Pre allocate output vector
for (i in 2:length(index)) {
  if (index[i] == 2 && index[i-1] == 1) {
    change_trend[i-1] = 3
  }
  else if (index[i] == 1 && index[i-1] == 2) {
    change_trend[i-1] = 3
  }
} # end loop

# Grab index positions
up_trend_index_start = rep(0,length(index))
up_trend_index_end = rep(0,length(index))
dn_trend_index_start = rep(0,length(index))
dn_trend_index_end = rep(0,length(index))

for (i in 1:length(index)) {
  if (index[i] == 1 && i == 1) {
    up_trend_index_start[i] = i
  }
  if (index[i] == 2 && i == 1) {
    dn_trend_index_start[i] = i
  }
  if (index[i] == 1 && change_trend[i] == 3 ) {
    up_trend_index_end[i] = i
  }
  if (index[i] == 2 && change_trend[i] == 3 ) {
    up_trend_index_start[i] = i
  }
  if (index[i] == 1 && change_trend[i] == 3 ) {
    dn_trend_index_start[i] = i
  }
  if (index[i] == 2 && change_trend[i] == 3 ) {
    dn_trend_index_end[i] = i
  }
  if (index[i] == 1 && i == length(index)) {
    up_trend_index_end[i] = i
  }
  if (index[i] == 2 && i == length(index)) {
    dn_trend_index_end[i] = i
  }
  }

# Reduce to remove all 0
up_trend_index_start = up_trend_index_start[up_trend_index_start != 0]
up_trend_index_end = up_trend_index_end[up_trend_index_end != 0]
dn_trend_index_start = dn_trend_index_start[dn_trend_index_start != 0]
dn_trend_index_end = dn_trend_index_end[dn_trend_index_end != 0]

# find maximum vector length
max_i = max(length(up_trend_index_start),length(up_trend_index_end),length(dn_trend_index_start),length(dn_trend_index_end))

# For loop to make subsets
up_trend = list()
dn_trend = list()
for (i in 1:max_i){
  up_trend[[i]] = dummy_vector[up_trend_index_start[i]:up_trend_index_end[i]]
  dn_trend[[i]] = dummy_vector[dn_trend_index_start[i]:dn_trend_index_end[i]]
  if (i >= length(dn_trend_index_end) | i >= length(up_trend_index_end)) { # Break loop if uneven lengths
break
}
}

# Vector output
up_trend_one = up_trend[[1]]
dn_trend_one = dn_trend[[1]]
up_trend_two = up_trend[[2]]

For the output
> up_trend_one
[1] 2 3 4 6
> dn_trend_one
[1] 6 5 3 1
> up_trend_two
[1] 1 3 5 6


text:
Q: Every real-valued continuous function on a closed set of compact Hausdorff space has an extension. I've noted, that the following fact can be proven in a few lines using $C^*$-algebra theory. I wonder if it has a simple elementary proof or not. Probably you can give me a reference.

Suppose $X$ is a compact Hausdorff space, $V\subset X$ is a closed subset, $f\colon V\to \mathbb{R}$ is a continuous function. Then there exists a continuous function $g\colon X\to \mathbb{R}$, whose restriction on $V$ is $f$.

C*-algebraic proof is the following.
First note, that it is enough to find $g\colon X\to \mathbb{C}$ (then we can take its real part). Consider restriction map $\phi\colon C(X)\to C(V)$. It is a * -homomorphism, and therefore its image $\phi(C(X))$ is a commutative $C^*$-algebra. Moreover $\phi(C(X))$ separates points of $V$ (because $C(X)$ does). By Stone-Weierstrass theorem $\phi(C(X))=C(V)$.

A: I think this is a special case of the Tietze extension theorem
(since any compact Hausdorff space is normal). (Here is one proof.)

A: If you like to see the Tietze theorem from a Functional Analysis viewpoint, another possibility is by means of the following basic lemma, stating that a certain "approximate surjectivity" actually implies "surjectivity"; this allows to prove a kind of dual result too.

Iteration Lemma. Let $X$ and $Y$ be Banach spaces, $T$ a linear bounded
  operator, $B_X$ the unit closed ball
  of $X$, $U$ a bounded nbd of $0\in Y$,
  $0\le t <1$ such that $$U\subset
> TB_X+tU.$$ Then, $T$ is onto and in
  fact $$(1-t)U\subset TB_X\\ .$$

You may have nice time applying it to prove the following results, in which we assume wlog that the functions are bounded, so that we can work with the Banach space $C_b$.

*

*Tietze-Dugundji extension theorem. Let $M$ be a metric space, $V\subset M$ closed, $E$ a Banach space. Then the restriction operator $C_b(M,E)\to C_b(V,E)$ is surjective.

*Bartles-Groves lifting theorem. Let $L:E\to F$ a bounded linear surjective operator; $M$ a metric space. Then the composition operator $C_b(M,E)\to C_b(M,F)$, such that $f\mapsto L\circ f,$ is surjective.


text:
Q: How can I test an Aggregate that relies on time? I am trying to model a time keeping application.
Ordinarily when I have a class that depends on time, I can provide an overloaded constructor or method to be able to inject a Clock into that method or class and be able to test its behavior.
If I have a command that needs to be able to pass the current time into an event, how can this work in the aggregate of an axon based application?
@Aggregate
@Slf4j
public class TimeCard {

  @AggregateIdentifier
  private String employeeName;
  private Instant clockInTime;

  public TimeCard() {
    //Axon requires empty constructor on aggregate
  }

  @CommandHandler
  public TimeCard(ClockInCommand cmd) {
    AggregateLifecycle.apply(new ClockInEvent(cmd.getEmployeeName(), Instant.now()));
  }

  @EventSourcingHandler
  public void on(ClockInEvent event) {
    this.employeeName = event.getEmployeeName();
    this.clockInTime = event.getClockInTime();
  }
}

It seemed that the test fixture handled that cleanly for me by providing methods to provide the time. Here is my test method:
@Test
void testClockInCommand() {
  testFixture.givenNoPriorActivity()
    .andGivenCurrentTime(clock.instant())
    .when(new ClockInCommand("GoldFlsh"))
    .expectEvents(new ClockInEvent("GoldFlsh", testFixture.currentTime()));
}

But my event did end up being different by a fraction of a second.
Expected <2020-02-02T13:47:20.684344700Z> but got <2020-02-02T13:47:20.954347700Z>

What's the best way to handle this? Should commands only take in time from upstream? Or can I inject a clock somehow for testing.

A: When relying on time in Aggregates (and other axon types) you can use the GenericEventMessage.clock which defaults to System.UTC in most runtime configurations.
The Testfixture will override this to be a fixed time during tests. Update the use of Instant.now() to use this clock.
@CommandHandler
public TimeCard(ClockInCommand cmd) {
  AggregateLifecycle.apply(new ClockInEvent(cmd.getEmployeeName(), GenericEventMessage.clock.instant()));
}


text:
Q: Conversion from array to vector - Interface with C library I need to use some low-level C functions provided by a library, to wrap them and provide a 'more high-level layer' ; in this case , my problem is to get a data contained within a buffer, and at least to learn how to do it right, I would like to know what you think would be the thing to do in C++03 AND in C++11.
FYI, I am working under Red Hat Linux, with GCC 4.4.7 (so not really C++11-compliant, https://gcc.gnu.org/gcc-4.4/cxx0x_status.html).
Here is a snippet of what I am trying to do :
#define DATA_BLOCKS 4096 // the numbers of 16-bit words within the buffer

std::vector<uint16_t> myClass::getData()
{
    uint16_t buffer[DATA_BLOCKS];
    getDataBuf(fd, dma, am, buffer[]); //C-function provided by the library

    // pushing buffer content into vector
    std::vector <uint16_t> myData;
    for(int i=0; i<DATA_BLOCKS; i++)
         myData.pushback(buffer[i]);
    return myData;
}

Within the link I provided, I am not able to find if it's a good idea to proceed like in C++11 to return the 'whole' vector.
For a vector, is there a best method to fill 'myData' than using the method 'pushback()' within a loop ?

A: You can do that, it's safe :
std::vector<uint16_t> myClass::getData()
{
    std::vector <uint16_t> myData(DATA_BLOCKS);
    getDataBuf(fd, dma, am, myData.data()); //C-function provided by the library
    // Old interface, before c++11 : getDataBuf(fd, dma, am, &myData[0]);

    return myData;
}

or if you want fill given vector:
void myClass::getData(std::vector<uint16_t> &myData)
{
    myData.resize(DATA_BLOCKS);
    getDataBuf(fd, dma, am, myData.data()); //C-function provided by the library
    // Old interface, before c++11 : getDataBuf(fd, dma, am, &myData[0]);
}

Personnally, I have no opinion about returning vector (which will probably use move semantic) or fill a given vector
EDIT
instead of using vector, because you know precisly the size, you can use std::array<std::uint8_t, DATA_BLOCKS> container (new in C++11). This use is same as vector in my examples
EDIT2
vector and array use contiguous storage locations (reference for vector class), so if you get address from first elements, you can access to the second one by incrementing address. The only dangerous point for vector is to be sure to have allocated memory. In both case, I manage to have enough allocated memory : in first example, vector is instanciate with the fill constructor, and in second one I resize vector to corresponding size. This method is describe in the book "Effective STL - 50 Specific Ways to Improve Your Use of the Standard Template Library" [Scott Meyers]. For array, no problem (on condition to declare array with enough memory of course).

A: data() came with C++11. Using it makes the code more ledgibe in my opinion, and aparently others though so too or it wouldn't have been added.


text:
Q: Intellij IDEA + Groovy + better static validation? I have a method in a Grails service:
void methodA(Car car) { }

and a second method in the same class calling this method:
void methodB() {
    methodA("A string")

}

But intellij doesnt even warn for this clearly incorrect usage.
I understand that a methodA can be injected with a String signature, but is there a way to make Intellij act or expect less dynamic behavior?
It would be nice to code statically with Groovy yet continue to have some kind of flag.
It would be a real downer if one has to choose so drastically between Java and Groovy.
I am using Grails 2.3.7, and I believe it is using Groovy 2.x.y

A: I am using IntelliJ IDEAD 12.1.6 and it does provide a warning for your example:

On the Idea Groovy Plugin page it states the following:

Inapplicable method calls marked as warnings

Do you have that plugin installed/enabled? (check under file->settings->plugins)


text:
Q: How can I remove a file from my svn working copy without deleting it? I accidentally added a file to my svn working copy that I don't want to check in (a test image).  I haven't commited yet, so how do I remove the file from my svn working copy without deleting it?

A: svn revert filename

A: If it's in A state, then simple svn revert is what you need.

A: In case it happens to a folder you can use the same command adding the desired  level to apply recursivity
svn revert --depth infinity [folder_name]

It may useful to add the folder to the ignore list in case you are interested in maintaining it under the same folder structure without worrying about an accidental add/commit. A helpful post about this aspect
can be found here How do I ignore a directory with SVN?


text:
Q: Pitest (PIT Mutation Testing) exception with local dynamodb I'm recieving the following pi-test exception when I have local dynamoDB lib files in my java project with a gradle build. Seems pi-test tries to open the lib file. Could not find a way to exclude lib files from pi-test either.

:pitest
Exception in thread "main" org.pitest.util.PitError: error in opening zip file (/Users/user1/.gradle/caches/modules-2/files-2.1/com.almworks.sqlite4java/libsqlite4java-linux-i386/1.0.392/b193c62571061e68bddeaf8ee7d3a8569b945ea6/libsqlite4java-linux-i386-1.0.392.so)

How can I solve this issue and have the mutation test on the gradle project?

A: This issue supposed to be fixed in the PI-test Gradle plugin v 1.1.11
(issue open: https://github.com/szpak/gradle-pitest-plugin/issues/52)