text:
Q: Gulpfile.js watch best practice here is my current watchlist for my gulpfile.js
// Gulp watchlist
gulp.task('watch', ['browserSync', 'sass'], function(){
    gulp.watch('app/scss/**/*.scss', ['sass']);
    gulp.watch('app/*.html').on('change', browserSync.reload);
    gulp.watch('app/js/**/*.js').on('change', browserSync.reload);
    //add more watchers here
});

and this works.
but a tutorial i am following has something slightly different:
gulp.task('watch', ['browserSync', 'sass'], function (){
  gulp.watch('app/scss/**/*.scss', ['sass']);
  // Reloads the browser whenever HTML or JS files change
  gulp.watch('app/*.html', browserSync.reload);
  gulp.watch('app/js/**/*.js', browserSync.reload);
});

do I need the .on('change', browserSync.reload)? it works; I'm just curious if what i'm doing isn't good practice.  Thanks!

A: Gulp watch always returns an EventEmitter that emits change events, so the call gulp.watch('app/*.html').on('change', browserSync.reload) can be written as:
var watcher = gulp.watch('app/*.html');
watcher.on('change', browserSync.reload);

watch function can be called with the following params:
gulp.watch(glob [, opts], tasks) or gulp.watch(glob [, opts, cb]).
So you can use both variants, but the shorter method is preferable.

A: No, you don't need to add custom on('change'). You should pass the event handler when initializing the watcher like the tutorial. Otherwise, it's sort of like telling gulp to do nothing on change by default then add your listener afterwards.
Another advantage is you can pass in multiple event handlers in one go as an array if your handlers are gulp tasks themselves gulp.watch(..., ['task1', 'task2']) instead of chaining on('change', task1Function).on('change', task2Function)


text:
Q: How to add input box to sas sql query which ask user about parameter? How to add input box to sas sql  query which ask user about parameter ? (Something aka Access input box) (in Enterprise Guide)

A: Here is a solution using BASE -
You could use the %Window procedure with the %display
DATA _NULL_;
%LET BATCH1=;

%WINDOW BATCH_ANALYSIS COLOR = WHITE

ICOLUMN = 30 IROW = 11
COLUMNS = 88 ROWS = 20

  #1 @28 "CLIENT BATCH REPORT"
  #4 @12 "Date must be entered YYYY-MM-DD Format, ascending order."
  #6 @28 "Example = '2015-01-31'"
  #9 @5 "Enter Batch Date - [ENTER] when complete:"
  #11 @5 BATCH1 12 attr=underline
  #13 @5 "Reports will be written to 'location'";

%DISPLAY BATCH_ANALYSIS;
STOP;
RUN;

%put %batch1;

This above is an example of using the "user input" to operate on your query/data step. In this case, I am prompting the user to enter a date, which creates that string value as a macro variable that can be passed anywhere in your SAS code (I am only using the string date format because it gets passed to an RSUBMIT in a DB2 environment). May be a good idea to play with the Input Lines/etc to display the text you want in your prompt window...

A: Are you using Enterprise Guide?
If thats the case, you can create prompts which will create macro variables when you run your code.
You will just have to use those macro variables in your code.
Right click your program > Properties > Prompts > Prompt Manager and so on.
Have a look at it and see if it solves your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Codefluent Entities and .net Identity Now that CodeFluent Entities blog has disappeared, and after the refurbishing of the SoftFluent site, there is no more documentation available for this framework?
How it's supposed to get information about, let me say, ASP.NET Identities, jwt, aspects, templates and all that valuable information at the blog?
And what about all those we have projects tied to this platform?

A: https://www.softfluent.com/documentation/ is still available.
The blog was discontinued because too many of its articles relate to obsolete technologies but were considered by some in the public as up to date view or as valid recommendations even in nowadays context not considering their publishing dates. In 2018 it generated too many support by itself and it was decided to put it as private and provide answers to customers through support for those having support licenses or through StackOverflow only.
SoftFluent supports existing customers through their support program if they have one ( fixes, VS2019 support, questions on their usage/code, link to specific blog article if accurate or with comments).
Existing licenses are still valid, including Free and Personal.
Specific question can still be answered through this StackOverflow channel by the community of its users and sometimes support.


text:
Q: 2 Factor Authentication in Web Api project I am trying to implement 2 Factor Authentication in a Web Api project. But it seems that 2FA cannot be implemented in Web Api where AccountController inherits ApiController. Is it possible to implement 2FA in Web Api solution and not MVC?

A: The question is very broad, however to answer your questions yes it is possible.
See here - http://bitoftech.net/2014/10/15/two-factor-authentication-asp-net-web-api-angularjs-google-authenticator/
Code from link that is responsible for generating verification code-
public static class TimeSensitivePassCode
{
    public static string GeneratePresharedKey()
    {
        byte[] key = new byte[10]; // 80 bits
        using (var rngProvider = new RNGCryptoServiceProvider())
        {
            rngProvider.GetBytes(key);
        }

        return key.ToBase32String();
    }

    public static IList<string> GetListOfOTPs(string base32EncodedSecret)
    {
        DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);

        long counter = (long)Math.Floor((DateTime.UtcNow - epochStart).TotalSeconds / 30);
        var otps = new List<string>();

        otps.Add(GetHotp(base32EncodedSecret, counter - 1)); // previous OTP
        otps.Add(GetHotp(base32EncodedSecret, counter)); // current OTP
        otps.Add(GetHotp(base32EncodedSecret, counter + 1)); // next OTP

        return otps;
    }

    private static string GetHotp(string base32EncodedSecret, long counter)
    {
        byte[] message = BitConverter.GetBytes(counter).Reverse().ToArray(); //Intel machine (little endian)
        byte[] secret = base32EncodedSecret.ToByteArray();

        HMACSHA1 hmac = new HMACSHA1(secret, true);

        byte[] hash = hmac.ComputeHash(message);
        int offset = hash[hash.Length - 1] & 0xf;
        int truncatedHash = ((hash[offset] & 0x7f) << 24) |
        ((hash[offset + 1] & 0xff) << 16) |
        ((hash[offset + 2] & 0xff) << 8) |
        (hash[offset + 3] & 0xff);

        int hotp = truncatedHash % 1000000;
        return hotp.ToString().PadLeft(6, '0');
    }
}

public static class StringHelper
{
    private static string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

    public static string ToBase32String(this byte[] secret)
    {
        var bits = secret.Select(b => Convert.ToString(b, 2).PadLeft(8, '0')).Aggregate((a, b) => a + b);

        return Enumerable.Range(0, bits.Length / 5).Select(i => alphabet.Substring(Convert.ToInt32(bits.Substring(i * 5, 5), 2), 1)).Aggregate((a, b) => a + b);
    }

    public static byte[] ToByteArray(this string secret)
    {
        var bits = secret.ToUpper().ToCharArray().Select(c => Convert.ToString(alphabet.IndexOf(c), 2).PadLeft(5, '0')).Aggregate((a, b) => a + b);

        return Enumerable.Range(0, bits.Length / 8).Select(i => Convert.ToByte(bits.Substring(i * 8, 8), 2)).ToArray();
    }

}


text:
Q: AccountHistory not deleting immediately after an update As part of the GDPR compliance process, we are updating a few name fields in Account with a random text and then calling the AccountHistory delete function for the tracked field.
We are running the Spring '18 release with 'Enable Delete from Field History' and 'Delete from Field History Archive' user permissions enabled on the account executing this code.
However, we are facing a weird situation where the last change made in AccountHistory is not visible even when we are deleting in a separate method after the update was completed and verified.
All the previous AccountHistory entries are deleted without issue. Just the last update made does not even show up until a subsequent and separate call is made.
Interestingly, it does delete if I run the delete operation again in a separate stack.
Has anybody else faced this issue?
Simplified code sample below. You can run this in Workbench if you put it in a class.
    public static void SequencerforPubliclyPostedCode()
{
    // Data Note: AccountHistory: 6 rows at this point
    UpdateMethodforPubliclyPostedCode('******************', 'Redacted');
    // Data Note: AccountHistory: 6 Acct History rows at this point. Does not seem to have updated yet.
    HistoryDeleteMethodforPubliclyPostedCode('******************');
    // Data Note: AccountHistory: 0 Acct History rows at this point.
    // Data Note: However on the page there are 3 Acct History rows for the updates made above.
    // Data Note: Running HistoryDelete... again in a separate stack, deletes the 3 created in the update above.
}
public static void UpdateMethodforPubliclyPostedCode(Id pAccountId, String pRedactedText)
{
    // Retrieve Account
    Account acct = [SELECT Id, FirstName, LastName, Preferred_Name__pc, Global_Number__c FROM Account WHERE Id =: pAccountId];
    // Anonymize Name
    acct.FirstName = pRedactedText;
    acct.LastName = pRedactedText;
    acct.Preferred_Name__pc = pRedactedText;
    // UPDATE Account. (Removed error handling for brevity during posting)
    update acct;
}
public static void HistoryDeleteMethodforPubliclyPostedCode(Id pAccountId)
{
    List<AccountHistory> lstAcctHistory = new List<AccountHistory>();
    // Get Applicable Account History rows
    lstAcctHistory.addall([SELECT Id FROM AccountHistory WHERE AccountId =: pAccountId AND Field IN ('FirstName','LastName','Preferred_Name__pc')]);
    // DELETE AccountHistory. (Removed error handling for brevity during posting)
    delete lstAcctHistory;
}

A: History records are not created until the end of the transaction. If you want to make sure those records are available for deletion, use a @future method, instead.


text:
Q: How do I extract DNA sequences from a text file without reading line by line? I'm trying to extract a DNA sequence from a text file and store it. I can do it using the following code, but it's not the best way because I'm reading the text file line by line. I'm wondering if there's an easier way to find each of the DNA sequences in my text file without reading the text file line by line.
example.pl
#!/usr/local/bin/perl
open(MYFILE, 'data.txt');
@entire_file = <MYFILE>;
while (<MYFILE>) {
    chomp;
    print "$_\n";
}

$line1 = <MYFILE>;
chomp $line1;
$line2 = <MYFILE>;
chomp $line2;
$line3 = <MYFILE>;
chomp $line3;
$line4 = <MYFILE>;
chomp $line4;
$line5 = <MYFILE>;
chomp $line5;

#Prints DNA sequence 1
print "$line2";

#Prints DNA sequence 2
print "$line5";

close(MYFILE);

data.txt

gi|171361, Saccharomyces cerevisiae, (CYS3) gene, Lab 1, Joe Bloggs
  GCAGCGATCGACAGCTGTGCTATCCCGGCGAGCCCGTGGCAGAGGACCTCGCTTGCGAAAGCATCGAGTACC
gi|171362, Saccharomyces cerevisiae, (CYS4) gene, Lab 2, Paul McDonald
  GAAGCGCACGACAGCTGTGCTATCCCGGCGAGCCCGTGGCAGAGGACCTCGCTTGCGAAAGCATCGAGTACC

A: Here is an example using BioPerl's module, Bio::SeqIO;
#!/usr/bin/perl
use strict;
use warnings;
use Bio::SeqIO;

my $in  = Bio::SeqIO->new( -file   => "junk.txt" ,
                           -format => 'FASTA');

while ( my $seq = $in->next_seq() ) {
    printf "id: %s\ndescr: %s\nseq: %s\n\n", $seq->id, $seq->desc, $seq->seq;
}

__END__
Contents of junk.txt

>gi|171361, Saccharomyces cerevisiae, (CYS3) gene, Lab 1, Joe Bloggs
GCAGCGATCGACAGCTGTGCTATCCCGGCGAGCCCGTGGCAGAGGACCTCG
CTTGCGAAAGCATCGAGTACC
>gi|171362, Saccharomyces cerevisiae, (CYS4) gene, Lab 2, Paul McDonald
GAAGCGCACGACAGCTGTGCTATCCCGGCGAGCCCGTGGCAGAGGACCTCG
CTTGCGAAAGCATCGAGTACC

And, here is the result of running the ptogram.
C:\Old_Data\perlp>perl t5.pl
id: gi|171361,
descr: Saccharomyces cerevisiae, (CYS3) gene, Lab 1, Joe Bloggs
seq: GCAGCGATCGACAGCTGTGCTATCCCGGCGAGCCCGTGGCAGAGGACCTCGCTTGCGAAAGCATCGAGTACC

id: gi|171362,
descr: Saccharomyces cerevisiae, (CYS4) gene, Lab 2, Paul McDonald
seq: GAAGCGCACGACAGCTGTGCTATCCCGGCGAGCCCGTGGCAGAGGACCTCGCTTGCGAAAGCATCGAGTACC

A: After
@entire_file = <MYFILE>;

you have the entire file saved in the array @entire_file. Everything else you are doing with the readline operators (<..>) afterwards will not work, because the file has already been read in its entirety.
You can loop over the elements in the array and do whatever you want with them, e.g.,
foreach my $line (@entire_file) {
  if ($line =~ /^gi/) { print "Descriptor: $line" }
  else { print "Sequence: $line" }
}

I suggest that you read up on reading files, pattern matching and loops in general.

A: If you have all of your file's lines in an array, you can iterate over that array to grab the id/descriptor and sequence elements w/o using a regex:
use Modern::Perl;
use Data::Dumper;

my ( @id, @des, @dna );
chomp( my @FASTA = <DATA> );

for ( my $i = 0 ; $i < @FASTA ; $i += 3 ) {
    my ( $id, $des ) = split ', ', $FASTA[$i], 2;
    push @id,  $id;
    push @des, $des;
    push @dna, $FASTA[ $i + 1 ];
}

say Dumper \@id, \@des, \@dna;

say @FASTA + 0;

__DATA__
>gi|171361, Saccharomyces cerevisiae, (CYS3) gene, Lab 1, Joe Bloggs
GCAGCGATCGACAGCTGTGCTATCCCGGCGAGCCCGTGGCAGAGGACCTCGCTTGCGAAAGCATCGAGTACC

>gi|171362, Saccharomyces cerevisiae, (CYS4) gene, Lab 2, Paul McDonald
GAAGCGCACGACAGCTGTGCTATCCCGGCGAGCCCGTGGCAGAGGACCTCGCTTGCGAAAGCATCGAGTACC

Output:
$VAR1 = [
          '>gi|171361',
          '>gi|171362'
        ];
$VAR2 = [
          'Saccharomyces cerevisiae, (CYS3) gene, Lab 1, Joe Bloggs',
          'Saccharomyces cerevisiae, (CYS4) gene, Lab 2, Paul McDonald'
        ];
$VAR3 = [
          'GCAGCGATCGACAGCTGTGCTATCCCGGCGAGCCCGTGGCAGAGGACCTCGCTTGCGAAAGCATCGAGTACC',
          'GAAGCGCACGACAGCTGTGCTATCCCGGCGAGCCCGTGGCAGAGGACCTCGCTTGCGAAAGCATCGAGTACC'
        ];

A: If you just want the sequences from the command line, this one-liner would do it:
perl -lane 'print $F[-1] if @F' data.txt

See perlrun(1) for details.
Similar solution using awk:
awk 'NF { print $NF }' data.txt


text:
Q: How to transfer file(s) from a Unix system to a DOS system? What is the simplest way to transfer files from a Unix system to a DOS system? Preferably without any "extra" tools on the DOS side.

A: you can use the ftp command, provided that you have a ftp server running on the Unix side.

A: That would depend on what you consider "extra" tools on the DOS side.
Most versions of DOS came with no networking support at all, and required extra software to do networking.
So that pretty much limits your options to a floppy disk.  Both Unix and DOS natively support floppy discs, though you'll have to work out which file systems and file formats they both support.  FAT12 should be a safe bet at both ends.


text:
Q: Stored procedure (insert data into a table and then insert the generated id into another) SQL Server I want to insert data into table 1, then I want to insert the generated idAddress into table 2, how can I do this?
Table 1
PK-idAddress,
street,
cp
Table 2
PK-idUser,
FK-idAddress,
Thanks in advance.

A: Try this out:
INSERT INTO table1(STREET, CP) VALUES('THIS', 'THAT')
INSERT INTO table2(FK-IDADDRESS) VALUES(@@IDENTITY) -- OR SCOPE_IDENTITY

Well, since I'm not sure of your tables structure and of your full code, that's just an assumption up there (my code, I mean) -- Basically, it's calling @@IDENTITY or SCOPE_IDENTITY -- read into the links below to get an idea of what you might really need.
SCOPE_IDENTITY
@@IDENTITY
DIFFERENCE BETWEEN...
There's another method you can use:
IDENT_CURRENT
And you can read this too:
http://sqlserverpedia.com/wiki/Functions_-_@@IDENTITY,_SCOPE_IDENTITY,_IDENT_CURRENT
*credit goes to @JakeFeasel for bringing up IDENT_CURRENT


text:
Q: C#: Receive incoming mail sent to myaddress@mydomain.com I have my own (Windows) VServer with my own domain and mx record.
Now I want to build a simple mail listener, which listens to all incoming mail to "*@mydomain.com" and stores it in a database.
I spent probably an hour googling, searching stackoverflow and informing about protocols, but I haven't found anything quite close to what I want to achieve.
What I don't want to do:

*

*Receive mails via IMAP/POP3/Exchange from an existing mailbox server

*Send Mails via SMTP

*Install any mailbox server software, e.g. Mercury Mail


text:
Q: Access a special div, generated by a while loop I'll try to be clear. My problem is that i'm using php to get data from mysql. The table has more than one record. To show table records i'm using a while loop that as a condition has mysqli_fetch_array(). The records from the table must be shown in an echo(because i want to show them as html on the page), but every div generated from the while loop has a link to send me to another page, and if the client clicks on that link it will get the current divs information(after the table in database has more than one record the informations will be different) to be shown at the next page. Hope you understood it. Thanks in advance!
while($rows1 = mysqli_fetch_array($query1,MYSQLI_ASSOC))
                            {
                             echo "

".$rows1['Dh_lloji']."

".$rows1['Dh_Pershkrimi']."

Max: ".$rows1['Dh_Kapaciteti']."

Size: ".$rows1['Dh_madhesia']."

Floor: ".$rows1['Dh_Kati']."

                                                $
                                                ".$rows1['Dh_cmimi']."
                                                night
                                            ";
                                            if(isset($_SESSION['Emri_Mbiemri']) != '')
                                            {
                                                echo "Book now";
                                            }else{
                                                $error = "You must be logged in to book!";
                                            }

                                        echo "
".$error."

".$rows1['Dh_cmimi']."

";

                                $count++;
                            }

A: Looks like you need at least your custom counter, that will be increment inside cycle, and set div's id based on this counter plus use it in generated link

A: I made a solution for my problem and i wanted to share it with you guys. I gave a $count to the links defining every link the while loop generates...
Book now

After that i used a multidimensional array to store the current divs variable(in my case rooms price, the count, and the id) of the room from database...
$room_prices[$count][0] = $rows1['Dh_cmimi'];
                                $room_prices[$count][1] = $count;
                                $room_prices[$count][2] = $rows1['ID_Dhoma'];

After the client click a specific link he will get the id so i can make a search at my multidimensional array for the price and the id of that room..
for($i = 0; $i < $count; $i++)
                            {
                                    if($_GET['id'] == $room_prices[$i][1]){
                                      $sess_room_price = $room_prices[$i][0];
                                      $sess_room_id = $room_prices[$i][2];
                                    }
                            }

After i get these i store them at the global session variables to use them at the other page...
$_SESSION['Rooms_Price'] = $sess_room_price;
                    $_SESSION['Rooms_ID'] = $sess_room_id;

So this did the work for me... Hope this helps others.


text:
Q: Uniqueness Proof for solution to $\nabla^2 G(\textbf{r}) = \delta(\textbf{r})$ with $G \rightarrow 0$ when $|\textbf{r}| \rightarrow \infty$ I'm having difficulty understanding the derivation of solution to this equation: $\nabla^2 G (\textbf{r}) = \delta(\textbf{r})$ with $G \rightarrow 0$ when $|\textbf{r}| -> \infty$ in $R^n$ where the boundary condition is defined at infinity.
I suppose that a reasonable approach is to first guess a solution and prove the uniqueness of it, so here's what I've tried to prove the uniqueness:
Assume that $G_1, G_2$ are different solutions, take $G' = G_1 - G_2$ then $\nabla^2 G' = 0$. My purpose is to prove $G' = 0$.
Consider $\int (\nabla G')^2 d^n{\textbf{r}}$ where $d^n{\textbf{r}} \stackrel{\Delta}{=} dV$ is the volume element. In a FINITE space $\Omega$ containing the origin with boundary condition $G'(\textbf{r}) = 0$ when $\textbf{r} \in \partial \Omega$ I can have
$\int_{\Omega} (\nabla G')^2 \cdot dV = \int_{\Omega} \nabla \cdot (G' \cdot \nabla G') \cdot dV - \int_{\Omega} G' \cdot \nabla^2 G' \cdot dV = \int_{\Omega} \nabla \cdot (G' \cdot \nabla G') \cdot dV$
and by divergence theorem
$\int_{\Omega} \nabla \cdot (G' \cdot \nabla G') \cdot dV = \int_{\partial \Omega} (G' \cdot \nabla G') \cdot \textbf{n}(\textbf{r}) \cdot dS = 0$
where $\textbf{n}(\textbf{r})$ is the norm vector of surface element on $\partial \Omega$. Thus $\nabla G' = 0$ in $\Omega$ and $G' = 0$ in $\Omega$.
However when the boundary condition involves $|\textbf{r}| \rightarrow \infty$ I'm not sure whether the step at which I applied divergence theorem is still valid.
Any help is appreciated :)
Edited:
$\delta(\textbf{r})$ here is the Dirac Delta function.

A: Maybe you could use the following argumentation:
Let $B_R =\{x\in \mathbb{R}^n | ||x||\leq R \}$ be a ball of size $R$. Let $\phi_R\in C_0^\infty(B_R)$ with $\phi_R(0)\not = 0$ be arbitrary.
Then from $G(r)=\delta(r)$, we get
\begin{align}
&\langle \nabla^2 G,\phi_R\rangle_{B_R} = \langle \delta,\phi_R\rangle_{B_R}=\phi_R(0)\\
\Leftrightarrow&\langle \nabla G,\nabla \phi_R\rangle_{B_R}=-\phi_R(0) \quad \quad \quad (*)
\end{align}
Now $G'=G_1-G_2$ are all three supposed to be solutions and $G_1\not \equiv G_2$. Further note, that $G'\equiv 0$ is not a solution. Then $(*)$ is true for $G'$, i.e.
\begin{align}
&\langle \nabla G',\nabla \phi_R\rangle_{B_R}=-\phi_R(0) \\
\Leftrightarrow& \langle \nabla G_1,\nabla \phi_R\rangle_{B_R}
-\langle \nabla G_1,\nabla \phi_R\rangle_{B_R}=-\phi_R(0)
\end{align}
But since $G_1$ is a solution and $(*)$ has to hold,
\begin{align}
&\langle \nabla G_2,\nabla \phi_R\rangle_{B_R}=0 \\
\Leftrightarrow & \langle \nabla^2 G_2, \phi_R\rangle_{B_R}=0
\end{align}
Since $\phi_R$ was arbitrary, by the fundaental theorem of variational calculus
\begin{align}
\nabla^2G_2 \equiv 0
\end{align}
has to hold. This means, that $G_2$ is linear in $r$ independent of $B_R$. But since $G\rightarrow 0$ for $|r|\rightarrow \infty$ we have $G_2\equiv 0$ which is a contradiction because the solution is not identically zero. $\blacksquare$
EDIT:
1)
$C^\infty_0(B_R)$ is the set of all functions that are differentiable of arbitrary order (that's what $\infty$ refers to) and have compact support on the set $B_R$, i.e. for $\phi \in C^\infty_0(B_R)$, we have $\phi(x)=0,\forall x \not \in B_R$
2) First, I assumed $\delta(r)$ is the Dirac delta distribution, which has the property, that $\int f(x)\delta(x)\,dx = f(0)$ which explains the right side of the equation for $(*)$. The notation $\langle f,g \rangle_{B_R}$ simply means the scalar product $\int_{B_R}f(x)g(x)\, dx$. Thus \begin{align}
\langle \nabla^2g,\phi \rangle_{B}&=\int_B \nabla^2 g(x)\phi(x)\,dx
\\&{}^*=[\nabla g \phi]_{\partial B}-\int_B \nabla g(x)\nabla\phi(x)\,dx
\end{align}
where we use integration by parts at $*$. The first term $[\nabla g \phi]_{\partial B}=0$ because $\phi(x)=0 \forall x\in \partial B$
2nd EDIT:
Let me give this one last try. I'll keep the fist part, i.e. $\langle \nabla G,\nabla \phi\rangle = -\phi(0)$
Now if $G$ is not a unique solution, then there exists another solution $G'\not \equiv G$. Then $G'=G+H$ with $H\not \equiv 0$. However, $H$ does not have to be a solution. Since $G'$ and $G$ are solutions, we have
\begin{align}
 -\phi(0)&= \langle \nabla G',\nabla \phi\rangle \\
&= \langle \nabla G,\nabla \phi\rangle+ \langle \nabla H,\nabla \phi\rangle \\
&=-\phi(0)+ \langle \nabla H,\nabla \phi\rangle
\end{align}
So we get
\begin{align}
\langle \nabla H,\nabla \phi\rangle=0
\end{align}
Again with integration by party and the fundamental lemma of variational calculus, $H$ has to be linear in $r$. Assume now $H$ is not zero , i.e. $H\not \equiv 0$. Then $H$ is either constant $\not = 0$ or linear with slope $\not = 0$
Since we know, that $G(r)=0$ for $r\rightarrow \infty$, we know that $G(r)+H(r)=H(r)$ for $r \rightarrow \infty$. But $H(r)\not =0 $ for $r \rightarrow \infty$ since it is either constant $\not = 0$ or linear. But then $G'(r)=G(r)+H(r)\not = 0$ for $r \rightarrow \infty$. Which means that $G'$ can't be a solution. This is a contradiction, so $H\equiv 0$ and thus $G'\equiv G$, thus the solution is unique.

A: @sonystarmap, I think I get the idea now: you denote $G'=G_1 - G_2$, a sphere $B_R$ with radius $R$ and functions
$$\phi_R(\textbf{r}) = \{ {\begin{array}{cc} arbitrary & |\textbf{r}| < R \\ 0 & \textbf{r} \ge R \end{array}} $$
Then with $\langle \nabla G', \nabla \phi_R \rangle_{B_R}=\langle \nabla G_1, \nabla \phi_R \rangle_{B_R}=-\phi_R(\textbf{0})$ got (ignoring the intermediate reasoning) $\nabla^2 G_2 \equiv 0$, is it?
In my calculation $\langle \nabla G', \nabla \phi_R\rangle_{B_R}=0$, because $\nabla^2 G'=\nabla^2 G_1 - \nabla^2 G_2 = 0$ and $\langle \nabla G', \nabla \phi_R\rangle_{B_R} = \int_{\partial B_R} \nabla G' \cdot \phi_R \cdot d\textbf{S} - \int_{B_R} \nabla^2 G' \cdot \phi_R \cdot d\Omega = 0$.
So $\langle \nabla G', \nabla \phi_R \rangle_{B_R} = -\phi_R(\textbf{0})$ doesn't seem right to me.


text:
Q: How to create a different process while AndroidTest runs? I'm working to setup my test infrastructure on an Android app. I'm using Android Studio, gradle, Espresso, MonkeyRunner, emulators, and real devices. I run AndroidTest using gradlew connectedAndroidTest.
In setting up proper test fixtures, I'm interested in having a background process that is started up before the tests start, then torn down when they're done. Is there a way to do that with gradle, etc?
Specifically what I'm trying to do right now is do a screen capture with MonkeyRunner in the middle of an Espresso test. Spinning up MonkeyRunner in the middle of the test is time-consuming so having it running as a daemon could speed the test up. (I understand the whole thing is a bit hokey, but ultimately I'm looking for an efficient way to do screen capture compares. If it was built into the Java libs in a more native way I'd do it that way). In this case, the MonkeyRunner process would spin up and connect to the device. The AndroidTest process would then spin up, run a test which may signal the MonkeyRunner process to take a snapshot and compare it to a reference, then AndroidTest continues to the next test which may do the same thing.
Other things the separate process pattern might enable would be external comms, or other things I may need for a test fixture.

A: If you are already creating your tests using Java there's no reason to use MonkeyRunner to take the screenshot. You should use takeScreenshot().
final UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
final String filename = "/path/to/screenshot.png";
device.takeScreenshot(new File(filename));


text:
Q: Using one controller or multiple controllers for a navigation page menu I've noticed that some sites use a separate controller for each menu item on a navigation page.
Here is an example
if I have a menu on a page that looks like this

*

*messages

*profile

*inbox

*items purchased

when each item gets clicked it takes me to a new controller even though I still see the menu at the top of the page
ex.
www.somepage.com/messages
www.somepage.com/profile
www.somepage.com/items purchased

is there any advantage to having a different controller, like above, for each item in the menu. I'm trying to weigh the advantages of having multiple controllers here vs one controller with different actions like below and I'm kinda a newbie to MVC
is this better? 1 controller(menu) with multiple actions that show the different areas of the menu
www.somepage.com/menu/messages
www.somepage.com/menu/profile
www.somepage.com/menu/items purchased

one last thing to keep in mind is that I want to have sub menu items like
in menu/messages I want Incoming/Outgoing, so how would that look?
www.somepage.com/menu/messages/incoming
www.somepage.com/menu/messages/outgoing

or would it be better to have
www.somepage.com/messages/incoming
www.somepage.com/messages/outgoing

A: You can have as many controllers as you want, and you should definitely take advantage of that. You should always break up your code into the smallest possible logical units. That applies to every class, whether it be a controller, an entity, a view model, whatever. One of the golden rules of OOP is that a class should do one thing and do it well. You should never have one massive class that contains all kinds of totally unrelated functionality, and since a controller is just a class, it applies to controllers as well.
Your controller should only contain actions that deal with the one thing your controller is "about". Generally, that ends up being a particular entity, and is reflected in the controller's name. So for messages, you might have a MessagesController and all the actions dealing with messages would go there. But for profile, you should create a new controller, probably called ProfileController and put those actions there.

A: It's all kinda preference, but I think the standard would be different controllers.
Different controllers gives you the default seperation, and if you're using the default routes it works nicely if you want to add on sub-menus.
www.somepage.com/profile -- standard profile page
www.somepage.com/profile/edit -- edit profile page with nice route

Of course you could do the same thing if you had them all in a menu controller, but then the routes get a bit messy, or you have to define how you want to do them in the route config manually.
Advantages to having them in one controller would be you only have one place to look/maintain when editing those specific actions (shrug).
Personally I like the different controllers for each mini 'section', mainly because it produces nice seperation, default routing is pretty decent and each controller can have different dependencies.


text:
Q: Extending another custom element? Trying to extend an custom element :

class ABC extends HTMLDivElement {
  connectedCallback() { console.log('ABC here') }
}

customElements.define("x-abc", ABC, {
  extends: 'div'
})

class XYZ extends ABC {
  connectedCallback() { console.log('XYZ here') }
}

customElements.define("x-xyz", XYZ, {
  extends: 'x-abc'
})

but getting this error :
 Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': "x-abc" is a valid custom element name

The err is confusing because it say 'is valid', not 'is not valid' !!
On the other hand FF says :
  Uncaught DOMException: CustomElementRegistry.define: 'x-xyz' cannot extend a custom element

I want to build hierarchy of custom elements.

A: The error may sound confusing at first, but actually it is very clear. The spec clearly defines that you can only extend built-ins using the is syntax. As it is currently designed, using ABC as a base class is definitely not the brightest idea (until you drop extending HTMLDivElement in favour of HTMLElement).
You have not explained why you need to extend div elements, which is definitely not what you typically build a component hierarchy on. It is not even (and probably never will be) supported in Safari.
Instead, extend HTMLElement, and omit the is-syntax.

class ABC extends HTMLElement {
  connectedCallback() {
    console.log('ABC here')
  }
}

customElements.define('x-abc', ABC)

class XYZ extends ABC {
  connectedCallback() {
    super.connectedCallback();
    console.log('XYZ here')
  }
}

customElements.define('x-xyz', XYZ)
<x-abc></x-abc>
<x-xyz></x-xyz>

If for whatever strange reason you need to keep extending HTMLDivElement (instead of HTMLElement which would be the proper way), here you go:
Just replace the {extends: 'x-abc'} part with {extends: 'div'}.
Both your components extend div (their defining tag name).

class ABC extends HTMLDivElement {
  connectedCallback() {
    console.log('ABC here')
  }
}

customElements.define('x-abc', ABC, {
  extends: 'div'
})

class XYZ extends ABC {
  connectedCallback() {
    super.connectedCallback();
    console.log('XYZ here')
  }
}

customElements.define('x-xyz', XYZ, {
  extends: 'div'
})

A: Actually, the option-name extends:"xxx" is confusing.
As the extended built-in element must be html-marked with the tag of that built-in (accompanied with the is attribute), this option does not determine the direct ancestor ("extending" it) (this is defined by the class-constructor-chain), rather it defines the tag-name, for which the given constructor (together with the whole chain) is used when parsing html/upgrading the element. Strictly speaking, it does extend that tag's class indeed, however not directly. The meaning "extends", is more related to the html is="xxxx" syntax. Think about it as it would have some name like basetag, builtintag, markuptag, builtinbase etc.


text:
Q: Sharpest upper bound on $|f(x)|$ using multivariable Taylor approximation, Hessian, or any other method (Based on a question in University of Pittsburgh's Preliminary examination: Aug 2016, question 5.)
Let $f\colon \mathbb{R}^2 \to \mathbb{R}$ be a $C^2$ function. Let $B=\{x \in \mathbb{R}^2\colon |x|\leq 1\}$ be the closed unit ball. Suppose $f(o)=Df(o)=o$ and that for an $M\geq 0$, we have
$$
\left \vert \frac{\partial^2 f}{\partial_{x_1}^2}(x)\right \vert^2 + 2\left \vert \frac{\partial^2 f}{\partial_{x_1}\partial_{x_2}}(x)\right \vert^2 +\left \vert \frac{\partial^2 f}{\partial_{x_2}^2}(x)\right \vert^2 \leq M^2 , \quad \text{for any $x=(x_1,x_2) \in B$}.
$$

Give the sharpest bound on $|f(x)|$ for $x \in B$.

By that, I mean something in terms of $M$ and (powers of) $|x|$, or maybe a different norm, like, $|x_1|+|x_2|$.
Please include the details of your argument with clear reference to any lemma/theorem you use.
Your time is appreciated!

A: Im assuming "$o$" means $0$. By Taylor's theorem with Lagrange remainder, for $x \in B$,
$$f(x) = \frac{1}{2}x \cdot H(\theta x)x$$
where $\theta \in (0, 1)$ depends on $x$, and $H$ is the hessian of $f$. Note that the bound given in the problem statement is equivalent (by Clairaut's theorem since $f$ is $C^2$) to saying that for $x \in B$,
$$||H(x)||_2^2 \leq M^2.$$
So $||H(x)||_2 \leq M$ for all $x \in B$. Let $x \in B$. Then
\begin{align}
|f(x)| &= \frac{1}{2}|x \cdot H(\theta x)x| \\
&\leq \frac{1}{2}||x|| \cdot ||H(\theta x)x|| \\
&\leq \frac{1}{2}||x|| \cdot ||H(\theta x)||_2 \cdot ||x|| \\
&\leq \frac{1}{2}M||x||^2.
\end{align}
The first inequality is by Cauchy Schwarz. The second inequality uses the result that $||AB||_2 \leq ||A||_2 \cdot ||B||_2$, which can be proved using Cauchy Schwarz. I believe the inequalities are sharp in the sense that they are achieved when $H(x) = MI$ on $B$.


text:
Q: How can i modify the context menu of a CEdit control? Before Windows 7 the solution was easy. Just add your own menu and write your own "Undo,Redo,Cut,Copy,Paste,Delete,Select All" menu items. But now this is not possible anymore because the menu has became really complex with the unicode and input message stuff.

A: You need to subclass the edit control then use a hook, following is an example code:
First is to subclass the edit control, usually in the WndProc:
LRESULT CALLBACK WndProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
    switch (Message)
    {
    case WM_CREATE:
    {
        HANDLE m_editControl; /* Supposing it is created */
        SetWindowSubclass(m_editControl, EditSubclassProc, 0, NULL);
    }
    break;
    default:
        /* default message handling */
    }
}

Then in the subclass function:
LRESULT CALLBACK EditSubclassProc(HWND hWndEdit, UINT Msg, WPARAM wParam, LPARAM lParam, UINT_PTR uIDSubclass, DWORD_PTR dwRefData)
{
    LRESULT ret{};

    switch (Msg)
    {
    case WM_CONTEXTMENU:
    {
        HWINEVENTHOOK hWinEventHook{ SetWinEventHook(EVENT_SYSTEM_MENUPOPUPSTART, EVENT_SYSTEM_MENUPOPUPSTART, NULL,
            [](HWINEVENTHOOK hWinEventHook, DWORD Event, HWND hWnd, LONG idObject, LONG idChild, DWORD idEventThread, DWORD dwmsEventTime)
            {
                if (idObject == OBJID_CLIENT && idChild == CHILDID_SELF)
                {
                    HMENU hMenuContextEdit{ (HMENU)SendMessage(hWnd, MN_GETHMENU, NULL, NULL) };

                    // Do what you want to do
                }
            },
            GetCurrentProcessId(), GetCurrentThreadId(), WINEVENT_OUTOFCONTEXT) };

        ret = DefSubclassProc(hWndEditMessage, Msg, wParam, lParam);

        UnhookWinEvent(hWinEventHook);
    }
    break;
    default:
        {
            ret = DefSubclassProc(hWndEdit, Msg, wParam, lParam);
        }
        break;
    }

    return ret;
}

A: Okay i found how to do it
static bool is_first_time;

case WM_CONTEXTMENU: {
   is_first_time = true;
   original_window_proc(message,wparam,lparam);
   break;

case WM_ENTERIDLE:
    if (wparam == MSGF_MENU) {
        if (is_first_time) {
            is_first_time = false;
            MENUBARINFO mbi;
            memset(&mbi, 0, sizeof(MENUBARINFO));
            mbi.cbSize = sizeof(MENUBARINFO);
            GetMenuBarInfo((HWND)lparam, OBJID_CLIENT, 0, &mbi);
            if (::IsMenu((HMENU)mbi.hMenu)) {
               .... add your menu items here
            }
        }
    }

Unfortunately this does not work because the code uses TrackPopupMenu with the TPM_RETURNCMD and TPM_NONOTIFY flags. So you can add new menu items but there is no way to handle the commands. Bad Microsoft, very bad design.


text:
Q: reverse K node in given linked list The passed list is 1->2->3->4->5 and node is 2 then output should be 2 1 4 3 5 but this code is showing 1 4 3 5
and for 1 2 3 4 5 6 and 3
it is showing 3 6 5 4
Node type
class Node{
    public:
        int data;
        Node* next;
    Node(){
        next = NULL;
    }
};

Node* reverseKNode(Node* head_ref, int k){

    Node* current = head_ref;
    Node* next;
    Node* prev = NULL;
    int count = 0;

    /*reverse first k nodes of the linked list */
    while (current != NULL && count < k)
    {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
        count++;
    }

    /* next is now a pointer to (k+1)th node
    Recursively call for the list starting from current.
    And make rest of the list as next of first node */
    if (next != NULL)
        head_ref->next = reverseKNode(next, k);

    /* prev is new head of the input list */
    return prev;
}

A: The error in your part of code is :

*

*Node* next; , in this the initial value should be set to NULL.
Node* next = NULL ;

*There is no point of using
Node(){
    next = NULL;
}
in your code, you may remove it.
Making the above changes in reverseKNode() the function to reverse k nodes in the the linked list would be correctly executed.
And after this, if the function to push  the node is properly implemented, then you will get the desired output.
Hope this helps!!


text:
Q: Any way to set the WP7 Webbrowser control height Dynamically and lock scrolling? I need to display a html string in a WebBrowser control, but it can be of variable length, and isn't the only thing on the screen. So, I need to be able to set the width corresponding to the actual content of the message.
WebBrowser has the property ActualHeight, but that does not produce any results. Additionally, Once it's displayed properly, I don't want it to scroll, as the user can scroll it completely off the screen.
Any ideas?

A: I'm not 100% sure what you need.
But you can use:
- normal XAML to set the external height and width of the webbrowser
- some header  tags to achieve some fixing of the web-browser's client height and width - see http://blogs.msdn.com/b/mikeormond/archive/2010/12/16/displaying-html-content-in-windows-phone-7.aspx including the comments at the bottom
I've done some of tis in the editor for iron7 - this fixes the client scale and disables zooming - but it's still got some unwanted side effects.
Hopefully the upcoming WP7 releases - including IE9 "soon" - will make the web browser control much better.


text:
Q: Devise override redirect after form submit How can I configure my Rails app such that after the form to create a new user is submitted (through devise), I redirect to my own desired page ?
Thank you

A: After the create user form is submitted the user is created and then logged in so the page you are being redirected to is actually the after log in page.  If you only want to change this page when a user is created you can set session["#{resource_name}_return_to"] in a custom registration controller like this:
class Users::RegistrationsController < Devise::RegistrationsController
  def create
    session["#{resource_name}_return_to"] = some_custom_path
    super
  end
end

You can also create a root route for your user object in routes.rb which will redirect all users whenever they log in:
match "user_root" => "users#home"

Finally you can define the after_sign_in_path_for(resource_or_scope) method in your application_controller and this will allow you to conditionally redirect users:
def after_sign_in_path_for(resource_or_scope)
  if resource_or_scope.is_a?(User)
    some_custom_path
  else
    super
  end
end


text:
Q: CocoaPods: can my framework depend on other frameworks? I'm creating a framework called MyFramework. This framework depends on ZipFoundation.
In order to test MyFramework I've created a new target application called MyFrameworkShowcase.
The workspace looks like the following:

*

*MyFramework.xcworkspace

*

*MyFramework.xcodeproj

*

*MyFramework

*MyFrameworkShowcase

*Pods.xcodeproj
The Podfile looks like the following:
platform :ios, '11.0'
target 'MyFramework' do
  use_frameworks!

  pod 'ZIPFoundation', '~> 0.9'
end

target 'MyFrameworkShowcase' do
  use_frameworks!

end

Running the showcase app I receive the following error:

dyld: Library not loaded: @rpath/ZIPFoundation.framework/ZIPFoundation

Any way I can adjust the Podfile in order to fix this issue?


text:
Q: PHP Mysql Poor performance when Using Key Exists I am having problems with poor performance regarding the time taken to retrieve records using PHP that uses OO techniques.
This is the code that returns the row from MySQL, instantiates and make sure the attributes exist
 public function find_by_sql($sql="") {
            global $database;
            $result_set = $database->query($sql);
            //we can use this later
            $this->sql = $sql;
            $object_array = array();
            while ($row = $database->fetch_array($result_set)) {
              $object_array[] = static::instantiate($row);
            }
            return $object_array;
     }

    private static function instantiate($record) {
            // Could check that $record exists and is an array
            $class_name = get_called_class();
            $object = new $class_name;
            foreach($record as $attribute=>$value){
              if($object->has_attribute($attribute)) {
                $object->$attribute = $value;
              }
            }
            return $object;
    }
    private function has_attribute($attribute) {
          // We don't care about the value, we just want to know if the key exists
          // Will return true or false
          return array_key_exists($attribute, $this->attributes());
    }

          protected function attributes() {
                // return an array of attribute names and their values
              $attributes = array();
              foreach(static::$db_fields  as $field) {
                if(property_exists($this, $field)) {
                  $attributes[$field] = $this->$field;
                }
              }
              return $attributes;
        }

db_fields  array have been defined elsewhere e.g
protected static $db_fields = array('car_id', 'make', 'model', 'reg')

I have tracked the bottleneck to the function where a check is done to see if the key exists. I commented out the code below and the performance is 100% improved:
    private static function instantiate($record) {
            // Could check that $record exists and is an array
            $class_name = get_called_class();
             $object = new $class_name;
            foreach($record as $attribute=>$value){
               ///if($object->has_attribute($attribute)) {
                $object->$attribute = $value;
             /// }
            }
            return $object;
    }

To give you an idea on the affect using the function has regarding performance, it takes 6 seconds longer when it is called.
Can anyone advise me on the impact of not using the function and if there is a way I can keep it but increase performance.
I understand that array_key_exists() is used  to see if the columns returned in the query  are in the attribute array $this->attributes() which is initially declared in the $db_fields.
I checked the $this->attributes() array which  printed the following
array(3) { ["car_id"]=> NULL ["make"]=> NULL ["model"]=>  ["reg"]=> NULL}
isset () is an alternative to array_key_exists() but cant be used because although the key exists it is false as the value is null.  Which brings me back to a work around not to use the function array_key_exists() because of its slow performance

A: Thanks to the comment by Michael Berkowski I narrowed the problem down to the constant calls to the method attributes() from the has_attributes method. Although there are probably more refined ways to do this I added this to the has_attribute method
        private function has_attribute($attribute) {
            ///if this is the first call attr_array will be empty so we will populate it by calling attributes method
              if (empty($this->attr_array)) {
                  $this->attr_array = $this->attributes();
              }
              ///either way, at this point attr_array is populated
              return array_key_exists($attribute, $this->attr_array);
        }

This has reduced the loading time of the page by 70%


text:
Q: Xcode adds ".app" to target names ending with ".cc" Can anyone fix or confirm this behaviour in Xcode (6.3.2):
Ending the name of an iOS project target with ".cc" like "something.cc" automatically adds ".app" to end of the name at runtime…?!
something.cc -> something.cc.app

A: This is now confirmed by others and obviously a bug: http://openradar.appspot.com/21319069
Thanks to Paul Hemetsbeger there is a workaround: Using the unicode letter "․" fixes the problem. Only the "delete this app alert view" gets a little bit messed up…


text:
Q: href to datatables row I have two datatables in the first one, a column contains a string with a href=#id of a row in the second datatable.
Getting the Id works fine but the problem I'm having is how to show the row when it's in another page that is not shown.
code of the first table row:
{% for item in items %}
..

{{item.1}}

...
{% endif %}

Code of the second table row
{% for item in items %}

     {{item.0}}
      {{item.1}}
      {{item.2}}
      {{item.3}}
      {{item.4}}

{% endfor %}

JS:
$(document).ready(function() {
   var 1stTable = $('#firstTable').dataTable(..);
   var 2ndTable = $('#secondTable').dataTable(..);
} );


text: Q: Send mail from Mac/Xampp with php years ago, I was able to send email with php mail() function from my localhost. Today, noI try to reconfigure my macOS 10.12.1 with Xampp 1.7.3. I spent hours doing google search. I haven't found one that really focus on Mac/Xampp. Many of them are for Windows, which does not apply to my set up obviously. I followed some tutorials to modify the php.ini and others to modify /etc/postfix/main.cf etc. Sadly it was all lost causes. I am all confused now, just how many files are needed to get php mail() working? Thanks in advance.


text:
Q: Why should it be hard to generalize Dvir's proof of the finite field Kakeya conjecture to the Euclidean case? Let $q$ be prime and let
$q\delta \sim 1.$ Let $K$ be any set of $C_n\delta$-separated tubes in $B(0,2)$, where $C_n$ is some constant depending on $n$. Let us consider a grid of $q^n$ points scaled with $\delta^n$. We embed this evenly spaced orthogonal grid in $\mathbf{R}^n$ so that the origins of the two sets meet. Let $K' \subset K$ so that each tube in $K$ contains a line from $K'$. The lines  $a + vt \in K'$ are such that if $v \in tu$ then $a + tu = a + vt$. So that we have $q^{n−1}$ lines in $K$ and the directions are $\delta$-separated (edit: not necessarily true if $K' \subset K$) . By Dvir's theorem we have $\lvert K'\rvert \ge \frac{q^n}{2^n}$. So we have at least that many points $x \in K' \subset K$ that are $\delta$-separated. Multiplying above by $\delta^n$ we have $\lvert K\rvert  \ge \lvert K'\rvert\delta^n \ge q^n\delta^n \frac{1}{2^n} \gtrsim \frac{1}{2^n}$ , because the $C_n\delta$-tubes contain the $\delta$−tubes. Isn't this a straightforward generalization? (EDIT) As was pointed out, those "grid lines" are unlike euclidean lines. The grid lines can go to the end of the grid and then reappear somewhere else in the grid. If a grid line contains $m$ points, it seems to me that for those "grid lines" we may even need  (in euclidean sense) $m$ parallel lines to the cover the grid line. This grows the number of (euclidean) lines and solves the mystery (for me). The solution: Let $K$ contain in addition to $\delta$-separated tubes essentially parallel tubes in order to achieve $K' \subset K.$ However, estimating how many parallel tubes you need may be difficult.

A: I don't entirely follow your proposed approach, but let me make a few remarks which might help you think about this:
(1) Clearly this can't work, since this argument purports to show that a Kakeya set must have positive Lebesgue measure which, in contrast to the finite field setting, we know is false in Euclidean space.
(2) Note that the discretization of a tube is not necessary an algebraic line or even approximately an algebraic line. Indeed consider R^2 and a tube oriented along the y axis. Now adjust the angle slightly in either direction. What does a discretization of this tube look like? Well it depends on the scales involved but, roughly in the case of a $\delta$ tube rotated by a $~\delta$ degree angle, the discretization will be the union of long segments of vertical lines (rectangles/blocks) stacked on top of each other slowly drifting in the direction of the rotation. This is not an algebraic line.
(3) In the discrete (finite field) setting two lines intersect at a single point. However, for reasons similar to the discussion in (2), two tubes can have substantial overlap. This is sometimes refereed to as "small angle issues" in the literature.


text:
Q: How to run react-native app in Xcode iOS simulator from htdocs folder of xampp I am trying to build a react-native app on an Xcode iOS simulator. The react-native project folder is in the htdocs folder of xampp. I get this error message:

I can run react-native apps on android emulators without issues and I can run apps on iOS simulators when they are not in the htdocs folder of xampp.


text:
Q: Failed back up restore from Deja-dup backup My Ubuntu crashed and I had to do a complete reinstall.
I have made a full back onto an external hard drive of everything. Deja-dup always verified the backups and I never tested restoring as I trusted that it would work, I trusted the software.
When I run the restore I get an error message which reads;
 "Command line error: One of the arguments must be an URL. Examples of URL strings are "scp://user@host.net:1234/path" and "file:///user/local". See the man page for more information. Enter 'duplicity --help' for help screen."

I ran the suggested command but don't understand it. Also I've copied the files to my desktop and tried to extract but I get an error that the file type 'difftar' is not supported.
Any advice on how to successfully restore my files?

A: *

*If Deja Dup gives errors, open Terminal and try
duplicity --gio file:///media/backup /tmp/restore

*Be sure to use file:/// when on local media because Duplicity expects a URL.


text:
Q: Processor Id Not found I am trying to get a CPU ID Using managementobjectserarcher but I am getting an error of object reference not found instance of an object exception.
The sample code has been written manually so may be some spelling mistake. but it is compiling properly.
please help me to get rid of this.
ManagementObjectSearcher obj = new ManagementObjectSearcher("Select * from Win32_processor")
foreach(ManagementObject ob in obj.Get())
Console.write(ob["ProcessorID"].toString());

A: the code you write may work wrong!
you should find the first not null item and work with that.
in some cases like virtual machines and some multi core processors , it is possible that some item be null.


text:
Q: Database MySQL race condition I am currently building a new object, and I am asking if I have two records to insert at the same time in a database with the same ID and the ID is unique. How will database handle it will it throw exception or undefined behavior will happen?
Could this scenario produced in real projects under a lot of requests from users ?

A: If you have a constraint (ex. Unique Index), one of the transactions will fail.
If you have lot's of transactions, it's given that this will happen at a certain point of time, so you need to handle the failure and generate new id for the failed transaction.


text:
Q: What is the equivalent ASP.NET Web API Message handler for the ASP.NET MVC pipeline? ASP.NET Web API has a very useful asynchronous message handler in the form of
System.Net.Http.DelegatingHandler.
I'm looking for the equivalent of such a handler to ASP.NET MVC. Is there something like that?
Note: I'm aware of Action Filters in both MVC and WebAPI, but that's not what I'm looking for.


text:
Q: Live location data from ASA to Power BI Map I've got a ASA output which sends the GPS coordinates of some devices devices to a Power BI Live datastream.
Data from ASA to Power BI looks something like this:

Device    Lat        Lon        Time
1         1,12345    2,34567    19-1-2018 11:48:00
2         1,34567    2,66666    19-1-2018 11:49:01
1         1,67890    2,55555    19-1-2018 11:49:13
2         1,33333    2,33333    19-1-2018 11:50:23
2         1,23222    2,44444    19-1-2018 11:50:54

I want to show the latest location of the devices on a map.
I can use a measure to show the latest Lat and Lon from a specific Device, like this:
GpsLonLast = CALCULATE(MAX('PowerBI'[lon]);FILTER('PowerBi';PowerBI[time]=[LastTime]))

Where LastTime is a measure to receive the latest time that device sent a message.
This works, when showed in a table, however I cannot map these measures to map control in Power BI, it does not support measures or aggregates.
If I use the plain Lat / Lon and Device fields as location and name on a map control I get all locations the devices were ever found. But that's not what I want, I want only the last location of the devices.
Note that I am using Azure Stream Analytics to send live data to Power BI, in Power BI this is received as a push dataset, so I cannot use custom Modeling in Power BI.

A: What I would suggest is creating a calculated table that only has the last locations for each device and using that table as the data set for your map.
This should give you the table you want:
= ADDCOLUMNS(SUMMARIZECOLUMNS(PowerBI[Device], "LastTime", MAX(PowerBI[Time])),
             "Lat", CALCULATE(MAX(PowerBI[Lat]),
                        FILTER(PowerBI, PowerBI[Time] = [LastTime])),
             "Lon", CALCULATE(MAX(PowerBI[Lon]),
                        FILTER(PowerBI, PowerBI[Time] = [LastTime])))

Now every time your live data updates, this calculated table should also update and give you the latest GPS coordinates to display on the map.

A: I don't think it's possible what you want to do.
You could however use the Power BI API directly to a push dataset instead of Azure Stream Analytics and post the GPS coordinates yourself to the API.
You can clear the table beforehand so you only end up with the latest values. Unfortunately, you cannot remove or update a single row, so you have to post the complete table each time. It's a bit cumbersome, but it works. The performance hit of deleting all rows in the table and adding them again is not that big of a problem if there are a few items on your map.
We use this technique on some projects and it works quite fast. We only update the GPS coordinates every couple of minutes, and only post to the API when they are changed.
You can use the https://github.com/Microsoft/PowerBI-CSharp C# API library to simplify posting to the API.

A: I would first calculate a "helper" column to test for for the latest Time per Device, e.g.
Latest Time per Device =
IF (
    [Time]
        = CALCULATE (
            MAX ( 'PowerBI'[Time] ),
            FILTER ( 'PowerBI', 'PowerBI'[Device] = EARLIER ( [Device] ) )
        ),
    "Is Latest Time per Device",
    "Other"
)

Then I would use that column as a Filter, e.g. add to Visual Level Filter well, then choose the "Is Latest Time per Device" entry.  Then you can use your Lat and Lon columns in the filtered visual.

A: This is probably not the answer you are looking for, but I suggest you a couple of workarounds:

*

*Use a top N filter (you can use one of those in real time datasets) ordered by date. Your map will show only the last points or short paths.

*Modify the RoutMap custom visual to paint only the last value. I think it should be easy if you have the code :) https://github.com/weiweicui/PowerBI-Routemap


text:
Q: How can I wrap a non-Traits model for use with Python Traits? I would like to wrap a non-Traits model class for use with Python Traits.  My goal is to write a Traits-based UI to manipulate an "external" model class.  The external model class has been generated by SWIG and so I cannot add enthought.traits.api.HasTraits as an ancestor (I think, though I may be wrong).
My current best attempt is
from enthought.traits.api import HasStrictTraits, Property, Instance

class ExternalModel():
    foo = 'foo'

class TraitsModel(HasStrictTraits):
    _e = Instance(ExternalModel)

    def __init__(self):
        self._e = ExternalModel()
        self.add_trait('foo', Property(lambda     :getattr(self._e,'foo'     ),
                                       lambda attr:setattr(self._e,'foo',attr)))

which causes the Traits-based class TraitsModel to have a mutable property which delegates to the contained non-Traits ExternalModel instance.  However, TraitsModel.trait_names() doesn't report 'foo' as a recognized trait.
Any suggestions for how to have TraitsModel report a 'foo' trait which is linked to ExternalModel?  enthought.traits.api.DelegatesTo seems to require the target be a Traits class (though I may not have found the right invocation and that is possible).
A more MVC-ish approach is probably to have a Traits-based view of my ExternalModel.  I've been unable to figure out having a non-Traits model for a Traits-based view.  Suggestions in that direction also greatly welcome.
Update I have figured out how to get HasTraits as the ExternalModel superclass using the approach at http://agentzlerich.blogspot.com/2011_05_01_archive.html and it seems to have been a complete waste of time.  Apparently the SWIG voodoo and the Traits hoodoo do not jive.  Wrapping ExternalModel within TraitsModel as this question asks seems the best route.

A: from enthought.traits.api import HasStrictTraits, Instance, Property

class ExternalModel(object):
    foo = 'foo'

class TraitsModel(HasStrictTraits):
    _e = Instance(ExternalModel, ExternalModel())

    def __init__(self):
        '''
        >>> wrapper = TraitsModel()
        >>> wrapper.foo
        'foo'
        >>> wrapper._e.foo = 'bar'
        >>> wrapper.foo
        'bar'
        >>> wrapper.trait_names()
        ['trait_added', '_e', 'foo', 'trait_modified']
        '''
        HasStrictTraits.__init__(self)
        for trait in (name for name in dir(self._e) if not name.startswith('__')):
            self.__class__.add_class_trait(
                trait,
                Property(
                    lambda:getattr(self._e, trait),
                    lambda attr:setattr(self._e, trait, attr)
                )
            )

if __name__ == '__main__':
    import doctest
    doctest.testmod()

A fairly robust solution is to use the add_class_trait of the HasTraits class, coupled with dir(self._e) to get the names of the class attributes of ExternalModel and a generator expression/list comprehension to filter the magic class method names (filter with an appropriate function would work better for wrapping a more complex class).
Also:

*

*ExternalModel should inherit from object

*__init__ should call HasStrictTraits.__init__ (or super(HasStrictTraits, self).__init__())

*_e can also be created in the Instance trait declaration as the second argument using ExternalModel() or even (), or as a method of TraitsModel like:
def __e_default(self): # note preceding underscore
    return ExternalModel()

Lastly, I have an slightly old copy of the Enthought APIs including Traits which can be very handy.


text:
Q: Помогите понять смысл mov qword ptr ss:[rsp+20],rbx Я понял так. Мы записываем значение из rbx в оперативную память по адресу rsp+20. Однако что значит ss? И как это выражение будет выглядеть в машинных кодах? Где-то я читал что ассемблер на этапе ассемблирования сам вычислит значение но ведь значение в регистре rsp ему неизвестно, тогда преобразует ли он это в две инструкции
add rsp 20
mov qword ptr [rsp],rbx

или я что то не понимаю.

A: Это помещение значения из rbx на стек, потому что ss - Stack Segmet как раз. В две инструкции преобразования не будет, потому что имеется тип адресации относительно регистра, который в данном случае и будет использован.


text:
Q: What kind of equation am I trying to make? (factoral with addition type of thing) So say I have a y = 12. Then I'd like to compute:
(x*12)+(x*11)+(x*10)+(x*9)+(x*8)+(x*7)+(x*6)+(x*5)+(x*4)+(x*3)+(x*2)+(x*1)
or say I have y = 4. Then I'd like to compute:
(x*4)+(x*3)+(x*2)+(x*1)
I'd like to know if there is a name for this type of equation and if there is a simpler way to write it. The reason I'd like to know is because I'm trying to do this in Excel with a y of 3,652 (and x is a cell reference). I wrote a python script that writes the formula for me but it crashes excel when I try to paste a forumula that long. Instead I'm looking for a cleaner way to do this type of math so I can translate that to Excel.

A: If you factor $x$ out of your algorithm, you get
$$x(y+(y-1)+(y-2)... + \ 1)$$
What's in the brackets is an arithmetic series. The sum is given by the formula
$$\frac{n(a_1+a_n)}{2}$$
where $n$ is the number of terms, $a_1$ is the first term, and $a_n$ is the $n$th term. If you plug the values  of your series into the formula, you get
$$\frac{y(y+1)}{2}$$
Multiplying this by $x$ will give you the algorithm you want:
$$\frac{xy(y+1)}{2}$$

A:
$(x\cdot y)+...+(x\cdot2)+(x\cdot1)$

can be rewritten as

$x(1 + 2 + ... + y)$ with $y = 4$.

Then $(1 + 2 + ... + y - 1 + y)$ is an arithmetic progression (starting with $1$ with $y$ elements and difference equal to $y$).
To get the sum of this arithmetic progression we can use .
$$y \cdot (y + 1) / 2$$
This comes from $n \cdot (a_1 + a_n) / 2$, where $n$ is the count of elements, $a_1$ is the first element, and $a_n$ is the $n$-th element (in our case, $y$)
What you search should be $x \cdot y \cdot (y + 1) / 2$.


text:
Q: Specifying custom model of decision nodes in HydeNet I am building a Bayesian Decision Network using HydeNet package:

The Market node and the Survey node have custom probability and cpt nature respectively. The idea is to define Found node as a Decision node with following logic: the agent is calculating his Utility according to the Survey node info, and then making a decision whether or not found a company on the market. Here I've calculated the ExpUtility values separately and then just paste them into determ node:
# Found node (how to put down an optimization task on it?)
founding <- data.frame(Found = as.factor(c(rep(0,3), rep(1,3))),
                       Survey = as.factor(rep(c(1,2,3),2)),
                       EV = as.numeric(c(NA,NA,NA,NA,NA,NA)))

expvalue = function(founding_option, survey_option){
  df = outcomes %>%
    left_join(market_status, by = "Market") %>%
    inner_join(survey_cond, by = "Market") %>%
    filter(Found == founding_option) %>%
    filter(Survey == survey_option) %>%
    mutate(expexted = as.numeric(as.character(Utility))*prob_real*prob_surv)
  ev = sum(df$expexted)
  return(ev)
}

for (i in 1:nrow(founding)) {
  founding$EV[i] = expvalue(founding$Found[i], founding$Survey[i])
}

net <- setNode(net, Found, nodeType = "determ", define=fromFormula(),
              nodeFormula = Found~ifelse(Survey == "1", 0, 1))
net <- setDecisionNodes(net, Found)

How can I code the ExpUtility maximizing process in the node?
upd: the formula of ExpValue is:

so the agent decides to found a company if the ExpUtility of founding is greater than 0 (which is the utility of no founding on the definition).
Full code:
library(dplyr)
library(HydeNet)

# 1 - poor, 2 - medium, 3 - perspective
market_status = data.frame(Market = as.factor(c(1,2,3)),
                           prob_real = as.numeric(c(0.5, 0.3, 0.2)))

# the probability of defining the market status
survey_cond = data.frame(Market = as.factor(rep(c(1,2,3),3)),
                         Survey = as.factor(c(rep(1,3), rep(2,3), rep(3,3))),
                         prob_surv = as.numeric(c(0.6, 0.3, 0.1, 0.3, 0.4, 0.4, 0.1, 0.3, 0.5)))

# final utilities
outcomes = data.frame(Found = as.factor(c(rep(0,3), rep(1,3))),
                      Market = as.factor(rep(c(1,2,3),2)),
                      Utility = as.factor(c(0,0,0,-7,5,20)))

net <- HydeNetwork(~ Utility | Found*Market
                   + Found | Survey
                   + Survey | Market)

plot(net)

# Market node
net <- setNode(net, Market, nodeType="dcat",  pi=vectorProbs(p=market_status$prob_real, Market),
               factorLevels = c("1","2","3"))

# Survey node
survey.cpt <- cpt(Survey ~ Market,
                  data = survey_cond,
                  wt = survey_cond$prob_surv)
net <- setNodeModels(net, survey.cpt)

# Found node (how to put down an optimization task on it?)
founding <- data.frame(Found = as.factor(c(rep(0,3), rep(1,3))),
                       Survey = as.factor(rep(c(1,2,3),2)),
                       EV = as.numeric(c(NA,NA,NA,NA,NA,NA)))

expvalue = function(founding_option, survey_option){
  df = outcomes %>%
    left_join(market_status, by = "Market") %>%
    inner_join(survey_cond, by = "Market") %>%
    filter(Found == founding_option) %>%
    filter(Survey == survey_option) %>%
    mutate(expexted = as.numeric(as.character(Utility))*prob_real*prob_surv)
  ev = sum(df$expexted)
  return(ev)
}

for (i in 1:nrow(founding)) {
  founding$EV[i] = expvalue(founding$Found[i], founding$Survey[i])
}

net <- setNode(net, Found, nodeType = "determ", define=fromFormula(),
              nodeFormula = Found~ifelse(Survey == "1", 0, 1))
net <- setDecisionNodes(net, Found)

# Utility node
net <- setNode(net, Utility, "determ", define=fromFormula(),
               nodeFormula = Utility ~ ifelse(Found == 0, 0,
                                              ifelse(Market == 1, -7,
                                                     ifelse(Market == 2, 5, 20))))
net <- setUtilityNodes(net, Utility)

plot(net)

trackedVars <- c("Market","Survey","Found","Utility")
evidence <- NULL
compiledNet <- compileJagsModel(net, data = evidence,
                                n.chains = 3,
                                n.adapt = 5000)
post <- HydeSim(compiledNet,
                variable.names = trackedVars,
                n.iter=10000)

dplyr::sample_n(post, 20)
table(post$Utility)
mean(post$Utility)

A: I do not know HydeNet but with pyAgrum, you can do that quite easily :
infdiag=gum.fastID("Market{poor|medium|perspective}->Survey{poor|medium|perspective}->*Found{nOK|OK}->$Utility[3]<-Market")
infdiag.cpt("Market")[:]=[0.5,0.3,0.2]
infdiag.cpt("Survey")[{"Market":"poor"}]=[0.6,0.3,0.1]
infdiag.cpt("Survey")[{"Market":"medium"}]=[0.3,0.4,0.3]
infdiag.cpt("Survey")[{"Market":"perspective"}]=[0.1,0.3,0.6]
infdiag.utility("Utility").fillWith([0,0,0,-7,5,20])

ie=gum.ShaferShenoyLIMIDInference(infdiag)
ie.makeInference()
print(ie.optimalDecision("Found"))

for this result :

      ||  Found            |
Survey||nOK      |OK       |
------||---------|---------|
poor  || 1.0000  | 0.0000  |
medium|| 0.0000  | 1.0000  |
perspe|| 0.0000  | 1.0000  |

In a notebook :

PS- I changed some values in P(survey|Market) in ordre to have a correct CPT. I can assume that the values in the utility are not the right ones either...


text:
Q: Making a dictionary from file, first word is key in each line then other four numbers are to be a tuple value This dictionary is supposed to take the three letter country code of a country, i.e, GRE for great britain, and then take the four consecutive numbers after it as a tuple. it should be something like this:
{GRE:(204,203,112,116)} and continue doing that for every single country in the list. The txt file goes down like so:
Country,Games,Gold,Silver,Bronze
AFG,13,0,0,2
ALG,15,5,2,8
ARG,40,18,24,28
ARM,10,1,2,9
ANZ,2,3,4,5 etc.;

This isn't actually code i just wanted to show it is formatted.
I need my program to skip the first line because it's a header. Here's what my code looks like thus far:
def medals(goldMedals):
    infile = open(goldMedals, 'r')
    medalDict = {}
    for line in infile:
        if infile[line] != 0:
            key = line[0:3]
            value = line[3:].split(',')
            medalDict[key] = value
    print(medalDict)
    infile.close()
    return medalDict

medals('GoldMedals.txt')

A: with open('path/to/file') as infile:
    answer = {}
    for line in infile:
        k,v = line.strip().split(',',1)
        answer[k] = tuple(int(i) for i in v.split(','))

A: Your for loop should be like:
next(infile)  # Skip the first line
for line in infile:
    words = line.split(',')
    medalDict[words[0]] = tuple(map(int, words[1:]))

A: A variation on a theme, I'd convert all the remaining cols to ints, and I'd use a namedtuple:
from collections import namedtuple

with open('file.txt') as fin:
    # The first line names the columns
    lines = iter(fin)
    columns = lines.next().strip().split(',')
    row = namedtuple('Row', columns[1:])
    results = {}
    for line in lines:
        columns = line.strip().split(',')
        results[columns[0]] = row(*(int(c) for c in columns[1:]))

# Results is now a dict to named tuples

This has the nice feature of 1) skipping the first line and 2) providing both offset and named access to the rows:
# These both work to return the 'Games' column
results['ALG'].Games
results['ALG'][0]

A: I think inspectorG4dget's answer is the most readable...  but for those playing code golf:
with open('medals.txt', 'r') as infile:
    headers = infile.readline()
    dict([(i[0], tuple(i[1:])) for i in [list(line.strip().split(',')) for line in infile]])


text:
Q: Why does DROP TABLE-ing the `wp_options` reset my user session? If I do:
global $wpdb;
$wpdb->query("DELETE FROM wp_options");

Suddenly, I'm logged out. But how come? I thought all sessions are kept locally, surely, a reference to my session must be present on the server, but how can I avoid this issue?
I want to wipe the entire table, just not these things related to the user sessions, as such, I identified certain possible keys that should be kept, but with no success:
logged_in_key
logged_in_salt
auth_key
auth_salt

What could be the issue here?


text:
Q: Redactor intermittently uploading images and files I'm experiencing an intermittent error using the Redactor WYSIWYG editor when uploading images or files (to clarify, it is the same file that it intermittently works with).
Sometimes the upload process works fine and I see this in the logs:
Started POST "/redactor_rails/pictures?authenticity_token=GErdxBU0dPRINvw8ZSj6VfBpPQ7hMbwtL0B4YWu94Mg%3D" for 127.0.0.1 at 2013-11-29 12:30:19 +0100
Processing by RedactorRails::PicturesController#create as HTML
  Parameters: {"file"=>#<ActionDispatch::Http::UploadedFile:0x007f8142445258 @original_filename="fish.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"fish.jpg\"\r\nContent-Type: image/jpeg\r\n", @tempfile=#<File:/var/folders/kq/6krgq50x6y3dsx4c4mf19f_40000gn/T/RackMultipart20131129-24880-availq>>, "authenticity_token"=>"GErdxBU0dPRINvw8ZSj6VfBpPQ7hMbwtL0B4YWu94Mg="}
  User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 4 LIMIT 1
   (0.5ms)  BEGIN
  SQL (1.0ms)  INSERT INTO "redactor_assets" ("assetable_id", "assetable_type", "created_at", "data_content_type", "data_file_name", "data_file_size", "height", "type", "updated_at", "user_id", "width") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING "id"  [["assetable_id", 4], ["assetable_type", "User"], ["created_at", Fri, 29 Nov 2013 06:30:21 EST -05:00], ["data_content_type", "image/jpeg"], ["data_file_name", "fish.jpg"], ["data_file_size", 1961898], ["height", 2448], ["type", "RedactorRails::Picture"], ["updated_at", Fri, 29 Nov 2013 06:30:21 EST -05:00], ["user_id", 4], ["width", 3264]]
   (1.9ms)  COMMIT
  Rendered text template (0.0ms)
Completed 200 OK in 5943ms (Views: 1.0ms | ActiveRecord: 4.0ms)

Other times in the upload hangs and I see this in the logs:
Started POST "/redactor_rails/pictures?authenticity_token=GErdxBU0dPRINvw8ZSj6VfBpPQ7hMbwtL0B4YWu94Mg%3D" for 127.0.0.1 at 2013-11-29 12:30:43 +0100
Processing by RedactorRails::PicturesController#create as HTML
  Parameters: {"authenticity_token"=>"GErdxBU0dPRINvw8ZSj6VfBpPQ7hMbwtL0B4YWu94Mg="}
  User Load (0.5ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 4 LIMIT 1
   (0.2ms)  BEGIN
   (0.2ms)  ROLLBACK
  Rendered text template (0.0ms)
Completed 200 OK in 5ms (Views: 0.4ms | ActiveRecord: 0.9ms)

As you can see it looks like items are missing from the parameters in the failed upload action.
The only error I seem to get is in my browser's console: Uncaught SyntaxError: Unexpected end of input
Did some further investigation into the actual HTTP request that is being sent and it looks like the client isn't correctly sending the file in the request:
A successful POST request:
"rack.request.form_input"=>
<StringIO:0x007ff68cf47f38>, "rack.request.form_hash"=>{"file"=>{:filename=>"fish.jpg", :type=>"image/jpeg", :name=>"file", :tempfile=>
<File:/var/folders/kq/6krgq50x6y3dsx4c4mf19f_40000gn/T/RackMultipart20131129-26808-1jw83tu>, :head=>"Content-Disposition: form-data; name=\"file\"; filename=\"fish.jpg\"\r\nContent-Type: image/jpeg\r\n"}}, "action_dispatch.request_id"=>"db53425e5252ab4045b69e61e076b9d5", "action_dispatch.remote_ip"=>127.0.0.1, "rack.session"=>{"session_id"=>"f5f4102fc79e015efd5abd2ab49156a8", "_csrf_token"=>"Yfvf/glbqZ8RVApod+wFswv84y1sFuiBmtxd9vCG37Q=", "warden.user.user.key"=>["User", [4], "$2a$10$PvP8UOZ27XwZo2fUfQh0H."]}, "rack.session.options"=>{:path=>"/", :domain=>nil, :expire_after=>nil, :secure=>false, :httponly=>true, :defer=>false, :renew=>false, :secret=>"b929602597766546d091f3312aff29d4eb3057308b332bd3dc97be55a810",...

An unsuccessful POST request:
"rack.request.form_input"=>
<StringIO:0x007ff6905e3ec0>, "action_dispatch.request_id"=>"2c37966c55458361c4246178d353fd67", "action_dispatch.remote_ip"=>127.0.0.1, "rack.session"=>{"session_id"=>"f5f4102fc79e015efd5abd2ab49156a8", "_csrf_token"=>"Yfvf/glbqZ8RVApod+wFswv84y1sFuiBmtxd9vCG37Q=", "warden.user.user.key"=>["User", [4], "$2a$10$PvP8UOZ27XwZo2fUfQh0H."]}, "rack.session.options"=>{:path=>"/", :domain=>nil, :expire_after=>nil, :secure=>false, :httponly=>true, :defer=>false, :renew=>false, :secret=>"b929602597766546d091f3312aff29d4eb3057308b332bd3dc97be55a810",...

This would suggest is something to do with the way the HTTP request is being formed on the client side, no?

A: Finally, after much research I found the culprit. In development I was running my app using the Pow server: http://pow.cx/ This seems to have intermittent problems when dealing with file uploads. There are a number of bugs open on this issue.
I migrated to Unicorn (which is what I use in production) and everything has been fine since.


text:
Q: CrudRepository Unsatisfied dependency expressed through field folioRepository I am getting error Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getFolioService': Unsatisfied dependency expressed through field 'folioRepository': No qualifying bean of type [a.b.c.repository.FolioRepository]
I am running Junit test case for my service, which save document in couchbase.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
public class FolioServiceTest {

    @Autowired
    private FolioService folioService;

    @Test
    public void testAddFolioTransaction() {
        Folios folios  = new Folios();
        folios.setUiid("user123");
        List<Order> orders = new ArrayList<Order>();
        Order order = new Order();
        order.set__type("type1");
        order.set__version("version1");
        order.setCreatedDate("09/02/2016");
        order.setCreatedUser("test user");
        OrderPayload orderPayload = new OrderPayload();
        orderPayload.set__type("type payload type");
        orderPayload.set__version("version payload type");
        order.setOrderPayload(orderPayload);
        orders.add(order);
        folios.getOrder().addAll(orders);
        boolean flag= folioService.addFolioTransaction(folios);
        assertTrue(flag == true);
    }

    @Configuration
    public class AppConfig {

        @Bean
        public FolioService getFolioService() {
            return new FolioService();
        }
    }
}

@Service
public class FolioService {
private final static Logger LOGGER = LoggerFactory.getLogger(FolioService.class);

@Autowired
FolioRepository folioRepository;

/**
 * Method will save the folio to the couchbase
 *
 * @param folios
 */
public boolean addFolioTransaction(Folios folios){
    LOGGER.debug("Adding transaction details to folio.");
    Folios newFolio = folioRepository.save(folios);
    if (newFolio != null) {
        return true;
    }
    return false;
}

public Folios getFolioDetailsByUiid(String uiid){
    LOGGER.debug("Get folio details by uiid.");
    Folios folios = folioRepository.findOne(uiid);
    return folios;
}

}
@Repository
public interface FolioRepository extends CrudRepository{
}


text:
Q: Is there a way to separately style components rendered using the .map() function? I am rendering one <Tuner /> component for each item in my this.state.notes array using this.state.notes.map(). I would like to know if there is a way to style each of these components separately. I would like to position them individually on the page but they are all being rendered together, so if im not mistaken, neither inline styling or className will work. How can this be done?
 this.state = {
  notes: [
    { note: "E", tone: E },
    { note: "A", tone: A },
    { note: "D", tone: D },
    { note: "G", tone: G },
    { note: "B", tone: B },
    { note: "e", tone: e }
  ]}

render() {
 const notes = this.state.notes.map(note => (
  <Tuner
    key={note.note}
    note={note.note}
  />
));

return (

Online Guitar Tuner

    {notes}

);

}

EDIT: I have tried a couple of the solutions that were suggested, but none of them seems to be working.
for this solution, the styles show up in the rendered component in the React console, but the actual styling is not being applied. I think maybe I'm just missing something small here, since the styles exist on the component but just aren't being applied.
constructor(props){
  this.noteStyles = {
    E: {
      backgroundColor: "#4caf50",
      border: "none",
      color: "white",
      padding: "15px 32px",
      textAlign: "center",
      textDecoration: "none",
      fontSize: "16px"
    }
  };

 this.state = {
  notes: [
    { note: "E", tone: E },
    { note: "A", tone: A },
    { note: "D", tone: D },
    { note: "G", tone: G },
    { note: "B", tone: B },
    { note: "e", tone: e }
  ]}
}

const notes = this.state.notes.map(note => (
  <Tuner
    key={note.note}
    playSound={e => this.playSound(e)}
    note={note.note}
    styles={this.noteStyles[note.note]}

  />
));

A: You can use predefined styles and generate them with className or inline styles but less recommended like so:
import React from 'react';
import ReactDOM from 'react-dom';
import './noteStyles.css';

const notes = [{ note: 'A' }, { note: 'B' }];

const NOTE_STYLE = {
  B: {
    color: 'pink'
  },
  A: {
    color: 'palegreen'
  }
};

const App = () => {
  return (
    <>
      {notes.map(({ note }) => (
        <div className={`noteStyle${note}`} style={NOTE_STYLE[note]}>
          {note}

      ))}
    </>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

A: This is a really broad question since you haven't really described what styles you want but I'll assume you want to do something simple like change a color of a note. There are a few approaches you could take:

*

*Pass style along with your object:

this.state = {
  notes: [{
    note: "E",
    tone: E,
    color: "#ff0000",
  }, {
    note: "A",
    tone: A,
    color: "#ff00ff",
  }, {
    note: "D",
    tone: D,
    color: "#ff00aa",
  }, {
    note: "G",
    tone: G,
    color: "#112233",
  }, {
    note: "B",
    tone: B,
    color: "#ff0011",
  }, {
    note: "e",
    tone: e,
    color: "#ff1100",
  }]
}

*Render in the function itself

render() {
 const notes = this.state.notes.map((note, index) => {
  const colors = [
    "#ff0000",
    "#ff00ff",
    "#ff00aa",
    "#112233",
    "#ff0011",
    "#ff1100",
  ];

  return (
    <Tuner
      key={note.note}
      note={note.note}
      color={colors[index]}
    />
  );
});

*Use CSS

.note:nth-child(1) { color: ... }


text:
Q: Update column values based on another two tables (MySQL) I have three tables, the goal is to increase the ClassPrice by 10% for all 'Pilates' and 'Hatha' classes which are held in 'Kyoto Room'.
**YogaRooms**

RoomNum |  RoomName     | RoomCapacity | Branch       | CostPerHour
--------------------------------------------------------------------
  001   | Surya Room    |      20      | Sydney       |    100.00
  002   | Chandra Room  |      10      | North Sydney |     50.00
  003   | Ashtanga Room |      25      | North Sydney |    150.00
  004   | Yin Room      |      15      | Sydney       |     70.00
  005   | Kyoto Room    |      30      | Sydney       |    130.00
--------------------------------------------------------------------

**YogaTimeTable**

YogaId | StartTime | Day   | RoomNum | Instructor | Duration
-------------------------------------------------------------
  DRU  |   10.30   |  Wed  |   001   |    Mark    |  60.00
  DRU  |   17.00   |  Tue  |   002   |    Julie   |  90.00
  HAT  |   18.30   |  Mon  |   004   |    Cora    |  60.00
  HAT  |    7.30   |  Tue  |   004   |    Mark    |  90.00
  PIL  |   17.00   |  Thu  |   004   |    Julie   |  60.00
  PIL  |   18.30   |  Wed  |   003   |    Nicky   | 120.00
  SUN  |    7.30   |  Mon  |   003   |    Mark    |  60.00
  HAT  |   18.30   |  Mon  |   005   |    Cora    |  60.00
  HAT  |    7.30   |  Tue  |   005   |    Mark    |  90.00
  PIL  |   17.00   |  Thu  |   005   |    Julie   |  60.00
-------------------------------------------------------------

**YogaTypes**

YogaId | YogaName | ClassPrice
-------------------------------
  BHA  |  Bhakti  |   17.00
  DRU  |   Dru    |   18.50
  HAT  |  Hatha   |   20.00
  PIL  |  Pilates |   15.50
  SUN  |  Sunrise |   15.00
--------------------------------

I've tried this code and changing it into different variations but it doesn't work. It updated the prices for all 'Pilates' and 'Hatha' classes but not specifically for only 'Kyoto Room'. Please i need help.
UPDATE YogaTypes
SET ClassPrice = ClassPrice * 1.1
WHERE YogaId IN (select T.YogaId
                 from YogaRooms R, YogaTimeTable T, YogaTypes YT
                 where R.RoomNum = T.RoomNum
                 and YT.YogaId = T.YogaId
                 and R.RoomNum = '005')

A: Use join:
UPDATE YogaTypes yt JOIN
       YogaTimeTable ytt
       ON yt.YogaId = ytt.YogaId
    SET yt.ClassPrice = yt.ClassPrice * 1.1
WHERE yt.YogaName in ('Pilates', 'Hatha') AND
      ytt.RoomNum = '005';


text:
Q: Two-finger scroll not working in some apps Starting yesterday the two-finger scroll on my laptop seems to be acting up. It works perfectly in almost everything, except gedit and nautilus. I wasn't able to find any reference to this issue, albeit searching for a few hours.
Has anybody experienced this issue? Any ideas what could be the cause?
I'm running Ubuntu 12.04 (upgraded from 11.10) on an Asus U36SD with a Synaptics touchpad.

A: The issue is now fixed. I upgraded the xserver-xorg-input-synaptics package from precise-proposed.
For more information check https://bugs.launchpad.net/bugs/982771 (comment #6 for enabling precise-proposed).


text:
Q: Wordpress Register options when plugin is activated I want to register an option when my plugin is activated to be used in the settings page.
My code is like this:
function jpsNews_activate_plugin() {
    // REGISTER SETTINGS
    register_setting( 'jps_settings_group', 'jps_test');
    ...
}
register_activation_hook(__FILE__, 'jpsNews_activate_plugin');

When i go to the database and search for that option, nothing is found. What am i missing? Can i do it like this?
Thanks in advance.

A: Your option will only get stored to the database after you go to the setting pane and submit new values.
You have to remember that in Wordpress - like in any PHP application - stuff gets loaded only when a code runs to load it. And the settings API allows you to create settings pages for the current admin page being used - the register_setting() method doesn't "register your new settings in the database" or something, it just displays the settings to the admin if the admin is currently in the admin screen and looking at the settings page!
The correct way to create new settings is to register the settings under the admin_init action, which happens just before the admin pages are shown to the admin. See the register_settings() documentation for a simple example on how to do this correctly.


text:
Q: Find all $M \subset \Bbb R^n$ s.t. $ \exists r>0 \; \forall x \in M: K_r(x) \subset M$
Find all of the subsets $M \subset \Bbb R^n$ such that $ \exists r>0 \; \forall x \in M: K_r(x) \subset M$.

(Where $K_r(x) = \{a \in \Bbb R^n : ||a-x||<r\}$)
My attempt:
After thinking about this for a while, the only two sets I could come up with were the empty set and $\Bbb R^n$. I think these are the only sets that have this property. My intuition is that such an $M$ would have to be unbounded in every direction or empty.
I want to prove it.
My idea is to show that the only sets that can have such property would have to be open and closed, hence only $\emptyset$ and $\Bbb R^n$.
It is clear that such a subset $M$ is open, just pick $\epsilon = r$.
It is not clear to me that such a set $M$ is closed.
We have
$$m \in M^c \iff \forall r >0 \; \exists x \in M \; K_r(x) \not \subset M $$
How can we conclude that $M^c$ is open? Is that even the case?

A: It's clear that such an $M$ is open (all points are interior points with the same $r>0$ even). If $M$ is not closed, we can find $p \in \overline{M}\setminus M$. Then $p \in \overline{M}$ allows us to find some $m \in M$ with $d(x,p) < \frac{r}{2}$, and then $p \notin M$, yet $p \in K_r(m)$ contradicting $K_r(m) \subseteq M$.
So $M$ is also closed. Connectedness tells us that $M=\emptyset$ or $M=\mathbb{R}^n$. This argument works in any connected metric space.


text:
Q: How to make two range price input have space between each other? hey guys I'm creating a Slider Price input
and I have two ranges one from the left side and the right side, they both are connected to each other
but they touch each other, how I can create limited space between them at least 50$
so the right does not pass the left and the left not pass the right
and to not merge?

(function() {
  const parent = document.querySelector('.range-slider');

  if (!parent) {
    return;
  }

  const rangeS = parent.querySelectorAll('input[type="range"]'),
    numberS = parent.querySelectorAll('input[type="number"]');

  rangeS.forEach((el) => {
    el.oninput = () => {
      let slide1 = parseFloat(rangeS[0].value),
        slide2 = parseFloat(rangeS[1].value);

      if (slide1 > slide2) {
        [slide1, slide2] = [slide2, slide1];
      }

      numberS[0].value = slide1;
      numberS[1].value = slide2;
    }
  });

  numberS.forEach((el) => {
    el.oninput = () => {
      let number1 = parseFloat(numberS[0].value),
        number2 = parseFloat(numberS[1].value);

      if (number1 > number2) {
        let tmp = number1;
        numberS[0].value = number2;
        numberS[1].value = tmp;
      }

      rangeS[0].value = number1;
      rangeS[1].value = number2;
    }
  });
})();
.range-slider {
  width: 480px;
  margin: auto;
  text-align: center;
  position: relative;
  height: 6em;
}

.range-slider svg,
.range-slider input[type="range"] {
  position: absolute;
  left: 0;
  bottom: 0;
}

input[type="number"] {
  border: 1px solid #ddd;
  text-align: center;
  font-size: 1.6em;
}

input[type="number"]:invalid,
input[type="number"]:out-of-range {
  border: 2px solid #ff6347;
}

input[type="range"] {
  -webkit-appearance: none;
  width: 100%;
}

input[type="range"]:focus {
  outline: none;
}

input[type="range"]:focus::-webkit-slider-runnable-track {
  background: #2497e3;
}

input[type="range"]:focus::-ms-fill-lower {
  background: #2497e3;
}

input[type="range"]:focus::-ms-fill-upper {
  background: #2497e3;
}

input[type="range"]::-webkit-slider-runnable-track {
  width: 100%;
  height: 5px;
  cursor: pointer;
  animate: 0.2s;
  background: #2497e3;
  border-radius: 1px;
  box-shadow: none;
  border: 0;
}

input[type="range"]::-webkit-slider-thumb {
  z-index: 2;
  position: relative;
  box-shadow: 0px 0px 0px #000;
  border: 1px solid #2497e3;
  height: 18px;
  width: 18px;
  border-radius: 25px;
  background: #a1d0ff;
  cursor: pointer;
  -webkit-appearance: none;
  margin-top: -7px;
}

input[type="range"]::-moz-range-track {
  width: 100%;
  height: 5px;
  cursor: pointer;
  animate: 0.2s;
  background: #2497e3;
  border-radius: 1px;
  box-shadow: none;
  border: 0;
}

input[type="range"]::-moz-range-thumb {
  z-index: 2;
  position: relative;
  box-shadow: 0px 0px 0px #000;
  border: 1px solid #2497e3;
  height: 18px;
  width: 18px;
  border-radius: 25px;
  background: #a1d0ff;
  cursor: pointer;
}

input[type="range"]::-ms-track {
  width: 100%;
  height: 5px;
  cursor: pointer;
  animate: 0.2s;
  background: transparent;
  border-color: transparent;
  color: transparent;
}

input[type="range"]::-ms-fill-lower,
input[type="range"]::-ms-fill-upper {
  background: #2497e3;
  border-radius: 1px;
  box-shadow: none;
  border: 0;
}

input[type="range"]::-ms-thumb {
  z-index: 2;
  position: relative;
  box-shadow: 0px 0px 0px #000;
  border: 1px solid #2497e3;
  height: 18px;
  width: 18px;
  border-radius: 25px;
  background: #a1d0ff;
  cursor: pointer;
}

  from <input type="number" value="3000" min="0" max="100000" step="500"> to <input type="number" value="75000" min="0" max="100000" step="500">
  <input value="3000" min="0" max="100000" step="500" type="range">
  <input value="50000" min="0" max="100000" step="500" type="range">
  <svg width="100%" height="24">
        <line x1="4" y1="0" x2="480" y2="0" stroke="#444" stroke-width="12" stroke-dasharray="1 28"></line>
      </svg>


text:
Q: How to configure the HttpClient from the Microsoft.Extensions.Http package? I'm using the Microsoft.Extensions.Http package for my .NET Core project. When sending requests to an API I have to deactivate the certificate validation. Unfortunately I don't know where to configure the client for this. When setting up the DI container I tried this
private static IServiceCollection ConfigureHttpClients(this IServiceCollection services)
{
    services.AddHttpClient<IMyInterface, MyImplementation>(httpClient =>
    {
        using HttpClientHandler httpClientHandler = new HttpClientHandler()
        {
            ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
        };
        httpClient = new HttpClient(httpClientHandler);
    });

    // ...

    return services;
}

but this didn't work and my IDE shows me this information for the variable httpClient

the value passed to the method is never used because it is overwritten
in the method body before being read

So where do I have to configure the client to disable the validation?

A: Use ConfigurePrimaryHttpMessageHandler to configure the handler used by the typed client
//...

services
    .AddHttpClient<IMyInterface, MyImplementation>()
    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() {
        ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
    });

//...

Reference Configure the HttpMessageHandler


text:
Q: Replacing hard drives in a LaCie 2big Network I have a LaCie 2big Network that currently has 2 500GB drives in it (mirror).
I'd like to upgrade the drives to 1TB each using something like this
I know that Lacie sells a 1TB drive designed for the 2big Network but it would seem to me that these drives are standard drives with the Lacie holder included.
Do I need to use their drives or can I get my own?  (Their customer support pushes me towards their drives)  I'm assuming the device can format the drives for me when I add them in.

A: I did the same yesterday, after breaking my head about the fact that replacing both disks at the same time does not work. There seems to bee some kind of linux software on the drives that make them "network". replacing both drives at the same time means the device is NOT accessible anymore.
The trick that did it: replace one drive by the bigger one, go to the admin page to the RAID section and add this new drive. the drive is being added but no change in total disk size.
after the raid is rebuild (takes some time), exchange the second drive and do the same procedure.
After both drives are rebuild, format the raid and the total disk size is correct

A: They are hot swappable; you can replace them with any drives which meet the specs defined by the hardware. They do not need to be LaCie drives; however I would get the same make/model with varying manufacturer dates for each drive existing in the array.

A: Just make sure to backup your data elsewhere!!
All data is lost when you rebuild the raid..
You DON'T need to use Lacie spare drives - You just have to swap ONE disk at a time, just like "SalF" wrote.
Replacing BOTH drives at the same time will leave you with a NAS without an OS..

A: If you use ghost and do a sector by sector copy you dont need to do the mirror process and you can do data as well but it took me 5 hours for 1.5 tb x 2 drives I replaced mine with 2x3tb drives

A: For those users who use Lacie 2Big devices, they do not run a software OS on the disks, they run what is called hardware RAID. This runs right from the mainboard or motherboard of the device if you will.
To upgrade simple:
1) Insert two Seagate-brand NAS disks of the same model and disk size, in my instance I downgrade from a 2x5TB disks Enterprise to 2x4TB disks NAS by Seagate.
2) Hold down the Lacie reset-pen or if you don't have it, a normal real pen will do to hold down the 'Select' button on Power-on for about 10 seconds. The Fast / Safe lights will start flashing.
3) Click the pen a few times on the Select hole to choose 'Safe or Fast'. This will install the setup of choice on this device and format the drives.
Tip! I have noticed that changing it to the opposite setting of what you previously had might be required to force a re-format on the newly inserted disks.
Download Lacie Desktop Manager (google it) to check the RAID-status on your device once the drives get formated.
The normal format time is about 10 seconds. We are talking fast, quick-format here by Lacie, writing 0's over both of the disks nearly instantly.
Enjoy.