text:
Q: Why can't I migrate my postgres database in windows? I switched my database from sqlite to postgres for deployment on heroku. When I did that and attempted to run heroku run rake db:migrate -a  I saw this error:
ActiveRecord::StatementInvalid: PG::DatatypeMismatch: ERROR: column "pay_date" cannot be cast automatically to type date HINT: You might need to specify "USING pay_date::date". : ALTER TABLE "recurring_payments" ALTER COLUMN "pay_date" TYPE date
 So i created a migration to fix this, but when I run rake db:migrate to run the migration, I see this error:
PG::ConnectionBad: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

However, when I check my services, I see that it is running, and it is configured to listen on port 5432. What else could be causing this issue?
Also, if I add this line to database.yml:
  host: localhost

The error changes to this:
PG::ConnectionBad: could not translate host name "localhost" to address: Name or service not known

Perhaps this is more promising?

A: You seem to have multiple problems:
By default Rails uses Unix sockets to connect to PostgreSQL. Hence the original error message.
Adding the host key switches Rails to a TCP/IP connection instead, which is what you want in Windows.
Now you seem to have another problem: localhost cannot be resolved to an IP address, which suggests that you have general configuration problems on your Windows machines which are unrelated to Rails or PostgreSQL.
Check if your hosts file is messed up or if your (personal) firewall is blocking Rails or PostgreSQL. Try running ping localhost.
If all else fails try using host: 127.0.0.1 instead.


text:
Q: Hover on position fixed image I have an image that I set up with the position: fixed CSS attribute. I want to change the image source when I hover it with the mouse. The problem is the hover function is called not only when the mouse is on the image but when the mouse enters the invisible square going from x=0, y=0 to the image itself.
I am afraid not to be very clear, here is a JSFiddle of the issue: http://jsfiddle.net/fz0e8nz9/1/
How can I manage to change the source only when the mouse hovers the image itself ? Do you have any idea ? Thank you.
HTML code :

CSS code :
html
{
  background: #dddddd;
}

#chicken
{
    position: fixed;
    padding-left: 70%;
    padding-top: 25%;
    width: 15%;
}

#chick
{
    position: fixed;
    padding-left: 65%;
    padding-top: 29%;
    width: 10%;
    visibility: hidden;
}

A: You could use margininstead of paddinglike this:
#chicken
{
    position: fixed;
    margin-left: 70%;
    margin-top: 25%;
    width: 15%;
}

Check this Demo Fiddle

A: CSS positioning accepts top -left -bottom -right attributes to move your item, try:
position:fixed
left:70%;
top:25%;
width:auto

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proof of Equivalence of Sets If A is a subset of the set of all functions $f : \mathbb{R}\rightarrow \mathbb{R}$ and let $g:\mathbb{R}\rightarrow\mathbb{R}$ be a bijective function. We use the notation $gAg^{−1} = \{g\circ f\circ g^{−1} : f \in A\}$. Prove that $A ≈ gAg^{−1}$.
I know to show equivalence I need to show a bijection from $A$ to $gAg^{−1}$, I'm not sure how to use the given information to start going about this.

A: A bijection from $A$ to $gAg^{-1}$ is, first of all, a function. Given an element $f$ of $A$, what would the obvious way to define an element of $gAg^{-1}$ be? This defines a function which is obviously surjective; then you need to check that it's injective, which shouldn't be too hard.


text:
Q: SQLite3 Insert statement error, but error message blank? I'm working on a basic program to learn how to use SQLite3; a user gives input on a song they'd like to add to a SQLite database, and it is inserted. As far as I can seen, the insert statement I'm generating- while not pretty- is a valid statement, but once it reaches my queryDatabase() function it enters the error clause. It prints "Error in execution: ", but when it moves on to errmsg, it seems to enter into a state where nothing happens/no actual error message is printed until I enter .quit. I've tried altering the print line like cout << "ERROR EXECUTING SQL: " << errmsg << "End";, and "End" never prints.
Here is the section of code that calls the queryDatabase() function/passes the command string. args refers to a vector that contains the user input:
string sqlq;

sqlq = "INSERT INTO songs (sid, title, composer) VALUES(";

sqlq.append(args[2]); sqlq.append(", "); sqlq.append("\'"); sqlq.append(args[3]); sqlq.append("\'"); sqlq.append(", "); sqlq.append("\'"); sqlq.append(args[4]); sqlq.append("\'"); sqlq.append(");");

data.queryDatabase(sqlq);

and here is the queryDatabase() function:
sqlite3 *db;
char * errmsg = 0;
int rc;

void Data::queryDatabase(string queryString){

      if(queryString.empty()) return;

      const char * sqlQuery = queryString.c_str();

      rc = sqlite3_exec(db, sqlQuery, callback, (void *) data, &errmsg);

      if( rc != SQLITE_OK) {
          cout << "Error in execution: " << errmsg;
      } else {
         cout << "\nSQL QUERY SUCCEEDED\n";
      }
   }

Both queryString and sqlQuery print INSERT INTO songs (sid, title, composer) VALUES(1905, 'Anti-rage', 'Emperor X'); which as far as I know is a valid command, as copy and pasting this when working direct in the database from terminal results in the song being added. Why might this not be inserting correctly, and why am I not being given an error message?
MODIFIED FOR MORE INFO:
Here's the callback
static int callback(
  void * data, //pass through data provided to sqlite3_exec() [4th argument]
  int argc, //# of cols in table row
  char ** argv, //array of strings representing table row values
  char ** azColName //array of strings representing column names
  ){
    for (int i=0; i<argc; i++){
      cout << argv[i] << ", ";
    }
    cout << "\n";
    return 0;
  }


text:
Q: Windows Firewall fails to launch, error 5 - like KB943996, but fix not working Environment
Windows 7 Professional SP1 PL, domain-joined.
Problem
Since 2014-06-12, several of our computers (but definitely not all, not yet at least) embraced a problem with printer sharing, which was quickly explained as Windows Firewall service being offline.
Attempts to start Windows Firewall service ends with failure and error no. 5 ("Access denied") returned by the service.
Windows EventLog shows that the issue began at the above date and is recurring every morning at startup - or at any manual service launch attempt.
Diagnostics
By courtesy of Google, we quickly identified the problem has something to do with accessing subkeys of following registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SharedAccess
There are several websites that suggest the problem is caused by insufficient access to some significant subkeys of this key for NT Service\MpsSvc. Most authoritative source seems to be the Microsoft Knowledge Base article KB943996. While this article is about Windows Vista, it provides link to a more general website with Firewall FixIt Tool.
We have tried to apply the suggestions found in the knowledge base and came up with following results:

*

*We were able to verify that only \Epoch subkey was missing the advised ACL set.

*We were unable to add NT Service\MpsSvc manually, as Windows was not able to find such user. We did check proper search scope (local computer) and did enable all object types. We have estabilished, that this account can be properly found and used on healthy machines.

*The FixIt tool did properly assign the rights to \Epoch subkey for NT Service\MpsSvc (!), but it did not solve the problem, which was admitted even by Fixit tool itself in the post-run test.

We have verified that the above registry key is the key to our issue. We did it by assigning inheritable Full Access rights to Everyone - with these rights, Windows Firewall service did start properly. This however doesn't solve our problem due to obvious security issues. What we need is to fix it correctly.
During our further investigation, we've attempted to monitor the above key using Sysinternals Process Monitor. We have established, that the Windows Firewall service fails after ACCESS DENIED upon \Epoch2 subkey, which we did not know of.
While running regedit.exe with account that has Local Administrator privileges, we were unable to see that subkey. Yet that key was clearly visible:

*

*on healthy machines, using same privileges,

*on affected machines, running regedit.exe as SYSTEM user (psExec -s -i regedit.exe)

The accounts enlisted in ACL on Epoch2 subkey are also missing NT Service\MpsSvc entry. On affected machine, these are:

*

*CREATOR OWNER

*SYSTEM

*Administrators

*Users

*LOCAL SERVICE
On healthy/unaffected machine the entries properly run as follows:

*

*CREATOR OWNER

*SYSTEM

*Administrators

*Users

*MpsSvc
Since we're unable to manually assign these permissions, we're kind of lost at what we can do next.
Range and significance
The issue has been reported in few areas only, but affects circa 50% of computers in the first area we were able to verify in detail.
The issue may likely affect other areas too. Since it requires user to interact with affected Windows features (printing on printer shared by affected computer), user reports will likely be rare when compared to the possible extent of the issue.
While shared printers are not common by now, that feature is not a real issue. But the downed firewall is definitely a problem that needs to be solved.
Result
One: we have no idea on what could have possibly caused such issue.
All computers (both affected and healthy) are run within controlled software installation environment. Users have no administrative privileges, software is automatically deployed via Wpkg. All above computers have identical software profile - which means that same software products have been installed. These computers are even identical in hardware terms, all have been acquired in a single batch and have consecutive serial numbers.
Our primary suspicion, related to common time of issue occurence, is some selective issue with one of the recent 2014-06-10 Windows Updates. We were unfortunately totally unable to reproduce this issue in our time-snapshotted virtual test machines, so that suspicion is kind of thin.
Finding source is important though, both for fixing it and avoiding it in future.
Two: we have no satisfactory idea how to fix the problem. We're thinking about:

*

*adding rights for MpsSvc user through some commandline ACL tool, though this would take a lot of time and manforce, were the problem begin to spread;

*perhaps to deploy these rights via GPO (GPO would accept any user here), but we would first have to correctly establish that the \Epoch2 rights are the only ones missing.

Before attempting anything drastic domain-wide, we'd be grateful to hear some comments. Most of all, previous experiences, ideas for solution and ideas on the possible source of the issue.
Perhaps someone else had that issue recently?

A: I have been battling the same problem for a couple days, and I too was unable to see the NT Service\MpsSvc account when checking registry key permissions. Apparently this is by design(?) and the NT Service\MpsSvc account is available, but hidden; you just have to enter it manually in the [Add...] dialog. After doing this, and giving the account Full Control on the Shared Access key, Windows Firewall now starts as it should.
I can only note that Linux with iptables is a marvel of simplicity in comparison.

A: This just happened to me this week, only obvious changes were the two security patches for Nov 2017 (KB4047206, KB4048960).
I can confirm that deleting and re-adding the specified registry keys as instructed in KB943996 fixed this for me. One additional thing I did was grant my domain user account full permissions to the Epoch, Epoch2 and FirewallPolicy keys and subkeys as well as NT Service\MpsSvc.


text:
Q: Does the weak law of large numbers imply that the ratio $\frac{\frac{1}{n}\sum_{i=1}^nX_i}{\mu}\rightarrow 1$ in probability? Suppose there is a sequence of $n$ bounded i.i.d. random variables $X_1,\ldots,X_n$, i.e. for all $i$, $a<X_i<b$ with $a$ and $b$ real constants.  Denote the mean of these random variables by $\mu$.  Weak law of large numbers (WLLN) states that $\frac{1}{n}\sum_{i=1}^nX_i\rightarrow\mu$ in probability, i.e. $\lim P(|\mu-\frac{1}{n}\sum_{i=1}^nX_i|\geq\epsilon)=0$ for any $\epsilon>0$.
The statement of the WLLN uses the absolute difference.  I am wondering whether showing that $\lim P(|\mu-\frac{1}{n}\sum_{i=1}^nX_i|\geq\epsilon)=0$ for any $\epsilon>0$ also implies the following:
$$\frac{\frac{1}{n}\sum_{i=1}^nX_i}{\mu}\rightarrow 1$$
in probability (in my particular case with bounded r.v.'s or in general).

A: For $\mu>0$,
$$\lim P(|\mu-\frac{1}{n}\sum_{i=1}^nX_i|\geq\epsilon)=0 \Rightarrow \lim P\left(\mu\left|1-\frac{\frac{1}{n}\sum_{i=1}^nX_i}{\mu}\right|\geq\epsilon\right) = \lim P\left(\left|1-\frac{\frac{1}{n}\sum_{i=1}^nX_i}{\mu}\right|\geq\epsilon\mu^{-1}\right) =  \lim P\left(\left|1-\frac{\frac{1}{n}\sum_{i=1}^nX_i}{\mu}\right|\geq\epsilon^*\right) = 0$$
For $\mu<0$,
$$\lim P(|\mu-\frac{1}{n}\sum_{i=1}^nX_i|\geq\epsilon)=0 \Rightarrow \lim P\left(\left|-\left((-\mu)+\frac {1}{n}\sum_{i=1}^nX_i\right)\right|\geq\epsilon\right) = \lim P\left((-\mu)\left|1+\frac{\frac{1}{n}\sum_{i=1}^nX_i}{-\mu}\right|\geq\epsilon\right)=\lim P\left(\left|1-\frac{\frac{1}{n}\sum_{i=1}^nX_i}{\mu}\right|\geq\epsilon(-\mu)^{-1}\right) =  \lim P\left(\left|1-\frac{\frac{1}{n}\sum_{i=1}^nX_i}{\mu}\right|\geq\epsilon^{**}\right) = 0$$

A: If $\mu\neq 0$, just use the definition of convergence in probability of $\frac1n\sum_{i=1}^nX_i$ with $\mu\varepsilon$ instead of $\varepsilon$.


text:
Q: How to use Groovy jenkins directory path as an Array I am checking out files from git to jenkins in this format:
local/joules/.../dev/n-1a/pf-as.manifest
local/joules/.../dev/n-2a/pf-as.manifest
local/joules/.../sit/n-3b/pf-as.manifest
local/joules/.../sit/n-4a/pf-as.manifest
local/joules/.../perf/n-3b/pf-as.manifest
local/joules/.../perf/n-4a/pf-as.manifest

i want to change this in groovy script something like:
pf-as-dev-n-1a.manifest
pf-as-dev-n-2a.manifest
pf-as-sit-n-3b.manifest
pf-as-sit-n-4a.manifest

can i do it using some looping mechanism in groovy. I am able to achieve this on by one...but i need to implement it using loop.
I stuggled a lot, but not get yet. Any1 have idea please help.

A: Here you go
list.map { it.split("/") }.flatMap {
  val lastPart = it.last().split(".")
  val extension = lastPart.last()
  val begin = lastPart.first()
  val middle = it[it.size - 3]
  val end = it[it.size - 2]
  listOf("$begin-$middle-$end.$extension")
}

A: You could do this easily as below:
//list of file paths
def files = ['local/joules/.../dev/n-1a/pf-as.manifest',
'local/joules/.../dev/n-2a/pf-as.manifest',
'local/joules/.../sit/n-3b/pf-as.manifest',
'local/joules/.../sit/n-4a/pf-as.manifest',
'local/joules/.../perf/n-3b/pf-as.manifest',
'local/joules/.../perf/n-4a/pf-as.manifest']

println files.collect{it.substring(it.lastIndexOf('/')+1, it.length())}

Quickly try this online demo


text:
Q: Distributing x amount of gold coins to n number of thieves Suppose if there are 10 thieves and 100 gold coins to be distributed and the distribution pattern goes like this:
Thief 1 gets 1 coin.
Thief 2 gets 2 coins.
Thief 3 gets 3 coins.... and so on upto 10.

When all the thief have received the coins then the sum of total coins will be (1+2+3+... = 55 coins). Now the coins left are 45. Now, how can I start redistribution from thief one but with the last incremented value instead of starting from 1 coin again? Like 1st thief in 2nd round should get 11 coins instead of 1 and this should continue until all the coins are distributed and coin left is 0. If the last thief has to get 7 coins but the coin available is 3 then he should get 3 coins and the distribution should be over.
I tried this...
$thieves = 10;
$goldCoins = 100;

$thiefArr = range(1, $thieves);
$assgnCoins = 0;

foreach($thiefArr as $key => $value){

  for($i=1; $i<=$goldCoins; $i++){

    $assgnCoins = $value; // This assigns first round of coins but how to redistribute it again I have no idea.

  }
  echo "Thief ".$value." will have ".$assgnCoins." gold coins.

";
}

A: I'm not really sure if I understood your problem correctly but here's my take, hope this helps:
<?php
$numt = 10; //Total number of thieves
$totalCoins = 100; //Total coins to redistribute
$data = []; //Data array (will contains the index, which is the "thief" number, and the value of a specific index is the total amount of coins for that specific thief

//Loop init: $coins is the amount of coins given to a thief in a specific distribution round
//Loop condition: We loop until there are still coins to redistribute
//Loop statement: We add 1 coin to each redistribution round
// (I start from 0 and use $coins + 1 because I do modulus on $numt ($coins % $numt) which will give me a number from 0 to $numt - 1 (Hint/fact: array indexes start from 0 and not 1)
for ($coins = 0; $totalCoins > 0; $coins++)
{
    //This will always give me a number between 0 and $numt - 1 (so that we know which thief's turn is)
    //(If this is not clear, you can print out $coins and $thiefIndex then you'll see/understand why I do this)
    $thiefIndex = ($coins % $numt);

    //Because we did not initialize $data values, we check if this specific thief's coins amount has been initialized
    if (!isset($data[$thiefIndex]))
    {
        $data[$thiefIndex] = 0; //Every thief starts with 0 coins
    }

    //Because we started from 0, we need to add 1 (this is the amount of coins that this thief ($thiefIndex) will get in this redistribution round
    $coinsToGive = ($coins + 1);

    //If there's not enough coins left, we just give the total coins remaining
    if ($totalCoins < $coinsToGive)
    {
        $coinsToGive = $totalCoins;
    }

    //Here we sum up all coins that a thief receives in a specific redistribution round
    $data[$thiefIndex] += $coinsToGive;

    //We need to subtract the given coins to the total conins that we redistribute (this makes the loop break when it reaches 0 (see the loop condition part)
    $totalCoins -= $coinsToGive;
}

//Use data/print in your case
foreach ($data as $idx => $tot)
{
    echo "Thief ".($idx + 1)." will have ".$tot." gold coins.
";
}

EDIT: I think you edited the question while I was writing my answer. Anyways, if you want to see how much coins every thief is getting on every redistribution round, you can add an echo in the first loop (at the end).
If you're new to programming, you may not know what += or -= means:
$foo += $bar;

Is the same as:
$foo = $foo + $bar;

This can be applied to every arithmetical operator like +, -, *, / (and even other signs like &= and |=, etc... but those will be bit-wise operations)
Information about operators can be found online on the PHP website.

A: <?php

$thieves = range(1, 10);
$availableCoins = 100;
$assignCoins = 0;

while($availableCoins > 0) {
    foreach($thieves as $thief) {
        // increase the coins to assign
        $assignCoins++;

        // check if assign coins are greater than the availableCoins
        if ($assignCoins > $availableCoins) {
            $assignCoins = $availableCoins;
        }

        echo "Thief ".$thief." will have ".$assignCoins." gold coins.

";

        // substract assignedCoins from availableCoins
        $availableCoins -= $assignCoins;
        // break the loop if no coins left
        if ($availableCoins <= 0) {
            break;
        }
    }
}

A: I have now edited the answer of @julian S to give the result that the homework should give:
I also have added some more HTMl input to demonstrate the structure of the array  the running operations and the resulting array in readable form.
In short:
The range was wrong here.
Because it will fill an array with 1,2,3,4,5,6,7,8,9,     that already is a numerical array   so member 1 has a value 1 ??  Useless.  NO!
So we crate an array of the 10thives weach with teh initial value =  - because teh thieves have = money  initially.
We print this array and add pre so that it looks a little better :-)
Then we have two loops  - the outer while loop that has the function to look if there is still money left.  if there is still moey left then make another round.
That was the logic missing to the original poster as he did understand that he needed a loop for the 10 thieves.
Then there is the INNER LOOP
just count from 1 to the number of thieves. So each thief will get its share.
$a += $b  is the short form of  $a=$a+$b
Add the currentcoins to the current arrray member
Add a break to leave the for loop if the monex is gone before you are at the end of the 10 thieves.
At the end just print the array with the wealth of the thieves.
0-9 as arrays start with 0.
<?php

$thieves = 10;
$availableCoins = 100;
$assignCoins = 0;
$array_thieves= array_fill(0,10,0);
echo "
Initial array with wealth of each thief
 ";
echo "
";
print_r($array_thieves)."
";
echo"
";

while($availableCoins > 0) {   //inerate as long as there are coins - outer loop
    for($i=0; $i<$thieves; $i++) {     //execute loop once per thieve so 10 x per round -inner loop
        // increase the coins to assign
        $assignCoins++;   //we have started with 0 and each time we add 1

        // check if assign coins are greater than the availableCoins
        //if the number of available coins is smaller then just assign all available coins
        if ($assignCoins > $availableCoins) {
            $assignCoins = $availableCoins;
        }
        $array_thieves[$i] += $assignCoins;   //add the coins to the thied (= array member) with the current number $i  [0-9]

        echo "Thief ". $i ." gets now additional ".$assignCoins." gold coins. He has now a total of: ". $array_thieves[$i] ."
";

        // substract assignedCoins from availableCoins
        $availableCoins -= $assignCoins;
        // break the FOR loop if no coins left - otherwise the inner loop will continue
        if ($availableCoins <= 0) {
            break;
        }
    }
}

echo"
Resulting array with all thieves and their wealth
";
echo"
";
print_r($array_thieves);
echo"
";


text:
Q: Can Xcode's 'Architecture' and 'Valid Architectures' exclude armv6 devices from downloading the app? We recently set the minimum iOS support to 4.0 and started using the LLVM compiler for a new update of a current available app.
Will setting 'Architecture' and 'Valid Architectures' to only armv7 exclude armv6 devices such as iPhone 3G from downloading the update?
I have tried with UIRequiredDeviceCapabilities but Apple does not let you set this for app updates, only for new apps, which is unfortunate.
We also don't have access to an armv6 device to test the app as I have read reports that the new compiler might cause some issues with this older architecture, thus we want to exclude armv6 from updating the app as we still have a small number of users running on armv6.

A: Just set the minimum required OS to iOS 4.3. That will exclude all armv6 devices as Apple dropped armv6 in iOS 4.3.


text:
Q: Is it possible to use common AuthorizedKeysFile for a group of users without disabling StrictMode in sshd_config? # rpm --query centos-release
centos-release-7-2.1511.el7.centos.2.10.x86_64

I want to use a common AuthorizedKeysFile in sshd for multiple users on my server. For that, I added:
Match Group my-secret-group
        AuthorizedKeysFile /etc/ssh/my-secret-group/common_authorized_keys

to /etc/ssh/sshd_config, and then added all those users to group my-secret-group.
sshd restarted fine, but that didn't allow me to log into accounts of the users in my-secret-group with a public key. However, when I set StrictModes no in /etc/ssh/sshd_config, it finally worked. I'm concerned that I shouldn't use StrictModes no, but I'm not sure what files should have what permissions for this setup to work. Currently, I have:
root:/etc/ssh/# ls -al my-secret-group/{.,common_authorized_keys}
-rw-r----- 1 root my-secret-group 2776 Nov  3 07:41 my-secret-group/common_authorized_keys

my-secret-group/.:
total 16
drwxrwx---  2 root my-secret-group   74 Nov  4 10:02 .
drwxr-xr-x. 3 root root            4096 Nov  4 10:33 ..
-rw-r-----  1 root my-secret-group 2776 Nov  3 07:41 common_authorized_keys
-rwxr-xr-x  1 root root            419 Nov  4 09:23 install_ssh_keys
-rw-r--r--  1 root root            274 Nov  3 07:47 README.md

Can I adjust permissions somehow so I don't have to set StrictModes no? I tried various combinations, but they didn't work.

A: You can use AuthorizedKeysCommand instead to get the authorized keys. This command does not need to confirm to these requirements (but you need to make sure the command is sane). For example
AuthorizedKeysCommand /usr/bin/cat /etc/ssh/my-secret-group/common_authorized_keys
AuthorizedKeysCommandUser root
# or whatever reasonable user with access to this file

should do the job.


text:
Q: Azure AD reply url failing on html handler Via ASP.NET I have created a startup file that will use Azure AD to log in a user
e.g.
 public void Configuration(IAppBuilder app)
 {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
        {
            ClientId = "42067b8d-b972-44e9-af86-ef60bc6d6fdb",
            Authority = "https://login.windows.net/...com",
            RedirectUri = "http://localhost:50560/content/story_html5.html",
            PostLogoutRedirectUri = "http://localhost:50560/content/story_html5.html",
            Scope = OpenIdConnectScope.OpenIdProfile,
            ResponseType = OpenIdConnectResponseType.IdToken
        });
  }

And as you can see my RedirectUri in hitting a static file html file.
On my app registration in Azure portal my manifest for the replyUrls states
"replyUrls": [
"http://localhost:50560/content/story_html5.html"
],

So everything is working and connecting correctly.
(if I use a aspx for example the redirection would work)
However using the .html file I'm getting the error

HTTP Error 405.0 - Method Not Allowed
The page you are looking for cannot be displayed because an invalid
  method (HTTP verb) is being used.

All I believe I need to do is add the html handler to Azure AD, does anyone know how to do this?
Thanks

A: This has nothing to do with Azure AD, but your configuration. Your end. Your Project. Your IIS config. Because sign-in response is a HTTP POST for security reasons. And static files handler in IIS does not accept anything beside GET for obvious reasons.
More information you will find here and there.
First, why would you want to redirect to a static page?! With the redirection after OIDC login, the IdP (Identity Provider, understand Azure AD in that case) sends valuable information which is needed by the OIDC middleware (understand the .UseOpenIdConnectAuthentication method) to be able to verify the token and initialize user session. By sending the sign-in response back to a static page you accomplish couple of things:

*

*You cut out the OIDC middleware from the authentication - it is no longer able to process the response. Because it will not listen on static file requests. Static files are processed outside your OWIN authentication middleware.

*Thus not able to verify authenticity of the user.

*Thus not able to create secure cookie.

*Thus not able to sign-in the user into your application.

Conclusion
Do not change the reply URL for your ASP.NET middleware, unless you explicitly and knowingly want to override the complete handling of sign-in responses.


text:
Q: Pyramid traversal is doing my head in I am trying to get my head around Pyramid traversal with this very simple example.  What I haven't quite grasped yet is where to "inject" an Article object from the db.
As it is, /Article correctly finds and renders the article_view but that's fairly useless.  How/when/where do I use the next part of the URL to query for a particular Article from the db?  eg. /Article/5048230b2485d614ecec341d.
Any clues would be great!
init.py
from pyramid.config import Configurator
from pyramid.events import subscriber
from pyramid.events import NewRequest
import pymongo

from otk.resources import Root

def main(global_config, **settings):
    """ This function returns a WSGI application.
    """
    config = Configurator(settings=settings, root_factory=Root)
    config.add_static_view('static', 'otk:static')
    # MongoDB
    def add_mongo_db(event):
        settings = event.request.registry.settings
        url = settings['mongodb.url']
        db_name = settings['mongodb.db_name']
        db = settings['mongodb_conn'][db_name]
        event.request.db = db
    db_uri = settings['mongodb.url']
    MongoDB = pymongo.Connection
    if 'pyramid_debugtoolbar' in set(settings.values()):
        class MongoDB(pymongo.Connection):
            def __html__(self):
                return 'MongoDB: <b>{}></b>'.format(self)
    conn = MongoDB(db_uri)
    config.registry.settings['mongodb_conn'] = conn
    config.add_subscriber(add_mongo_db, NewRequest)
    config.include('pyramid_jinja2')
    config.include('pyramid_debugtoolbar')
    config.scan('otk')
    return config.make_wsgi_app()

resources.py
class Root(object):
    __name__ = None
    __parent__ = None

    def __init__(self, request):
        self.request = request

    def __getitem__(self, key):
        if key == 'Article':
            return Article(self.request)
        else:
            raise KeyError

class Article:
    __name__ = ''
    __parent__ = Root

    def __init__(self, request):
        self.reqeust = request

    # so I guess in here I need to update the Article with
    # with the document I get from the db.  How?

    def __getitem__(self, key):
        raise KeyError

views.py
from pyramid.view import view_config
from otk.resources import *
from pyramid.response import Response

@view_config(context=Root, renderer='templates/index.jinja2')
def index(request):
    return {'project':'OTK'}

@view_config(context=Article, renderer='templates/view/article.jinja2')
def article_view(context, request):
    # I end up with an instance of Article here as the context.. but
    # at the moment, the Article is empty
    return {}

A: You'd generally return a Article object from the id part of the URL traversal.
What happens with traversal is that for each element in the URL path, an object is looked up and made the new current object for the next path element lookup.
So for Article, the root object is asked for something matching that name, and the result of that lookup is made the new "current" object, and 5048230b2485d614ecec341d is then looked up on that new object.
So, what you are looking for is a dispatcher object, something that looks up articles based on the longer id you are passed, and that returns your Article instances:
class Root(object):
    __name__ = None
    __parent__ = None

    def __init__(self, request):
        self.request = request

    def __getitem__(self, key):
        if key == 'articles':
            dispatch =  ArticleDispatcher(self.request)
            dispatch.__name__ = key
            dispatch.__parent__ = self
            return dispatch
        raise KeyError(key)

class ArticleDispatcher(object):
    __name__ = None
    __parent__ = None

    def __init__(self, request):
        self.request = request

    def __getitem__(self, key):
        # Get a hold of the database here:
        db = findDatabase(self.request)
        if db.exists(key):
            data = db.load(key)
            art = Article(data)
            art.__name__ = key
            art.__parent__ = self
            return art
        raise KeyError(key)

class Article:
    __name__ = None
    __parent__ = None

    def __init__(self, data):
        self.data = data

Note how I returned a ArticleDispatcher when you use the /articles URL path, and also how I set the __name__ and __parent__ variables; you'll need those to be able to generate URLs for those instances.
The Article object returned now contains the actual article data, and the view can access that information when rendering.
You really want to go and study the Pyramid Traversal tutorial which explains this all in more detail.


text:
Q: lapply when both list elements their names are arguments of the function My toy dataframe:
d <- data.frame(
  value = sample(1:10),
  class = sample(c("a","b"), 20, replace = TRUE)
)

I split my data frame up by values of 'class' and put them in a list where each list element is named after its class:
l <- dlply(d, .(class), function(x)return(x))

Then I want to lapply over each class and make a histogram. Note that I do NOT want a facet. I want as many individual files saved as classes. So I define a function doPlots that makes histograms, then ggsaves them (as a_hist.png and b_hist.png, in this example):
doPlots <- function(d, name){
  g <- ggplot(data = d, aes(x=value)) +
    geom_histogram(binwidth=1)
  ggsave(filename=paste(name,"hist.png",sep="_"))
}

However, when I lapply:
lapply(l, FUN=doPlots, name=names(l))

I get Error: device must be NULL, a string or a function.
Thanks in advance.

A: Two problems with your code, one is that you are passing the entire vector of names to the function. Second, you have not added a plot to save to the ggsave function. You can use mapply to iterate over two or more lists.
doPlots <- function(d, name){
  g <- ggplot(data = d, aes(x=value)) +
    geom_histogram(binwidth=1)
  ggsave(filename=paste(name, "hist.png", sep="_"), g)
}

mapply(doPlots, l, names(l))

A: Consider base R's by which slices a dataframe by factor levels into a list of elements. You can even pass your user-defined function into it all in one call:
dlist <- by(d, d$class, FUN=function(i) {
             name <- max(as.character(i$class))
             doPlots(i, name)
         })


text:
Q: Strong parameter: issue with array on "permit" method The problem

/app/controllers/users_controller.rb:29: syntax error, unexpected ',', expecting => name, roles: [], (something here)

The scenario
In users_controller.rb:
params.require(:user).permit(:name, roles: [])

Diagnostics

*

*The problem happens when I access any page related to users_controller.rb;

*If I use :roles => [] instead of roles: [], the error is the same;

*If I change roles: [] for :roles, everything goes okay.

Environment
I'm running on CentOS 6.5 with Rails 4.

A: The comma is unexpected because it interprets :name as a hash key.  This is happening because Rails is seeing the hash roles: [].    Explicitly mark it as such
params.require(:user).permit(:name, {roles: []})


text:
Q: Taking slowlogs that are having TOOK field greater than 15ms using logstash? LOGS:
[2017-01-14 10:48:06,848][WARN ][index.search.slowlog.query] [yaswanth] [bank][0] took[27.8ms], took_millis[27], types[], stats[], search_type[QUERY_THEN_FETCH], total_shards[5], source[], extra_source[],
[2017-01-14 10:48:06,851][WARN ][index.search.slowlog.query] [yaswanth] [bank][3] took[12.7ms], took_millis[33], types[], stats[], search_type[QUERY_THEN_FETCH], total_shards[5], source[], extra_source[],

I am trying to get the logs whose TOOK field is >15ms . I used the below config
input {
  file {
    path => "F:\logstash-2.4.0\logstash-2.4.0\pica.txt"
    start_position => "beginning"
  }
}

filter {
           grok {
                match => [ "message", "\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:QUERY}\]%{SPACE}\[%{DATA:QUERY1}\]%{SPACE}\[%{DATA:INDEX-NAME}\]\[%{DATA:SHARD}\]%{SPACE}took\[%{DATA:TOOK}\],%{SPACE}took_millis\[%{DATA:TOOKM}\], types\[%{DATA:types}\], stats\[%{DATA:stats}\], search_type\[%{DATA:search_type}\], total_shards\[%{NUMBER:total_shards}\], source\[%{DATA:source_query}\], extra_source\[%{DATA:extra_source}\],"]
           }
if [TOOK] > 15ms {
    mutate {
      add_tag => "slowresponse"
    }
  } else {
    drop { }
  }
}
output {
stdout { codec => rubydebug }

}

The error is like this:
[31mException in pipelineworker, the pipeline stopped processing new events, please check your filter configuration and restart Logstash. {"exception"=>#<NoMethodError: undefined method `>' for nil:NilClass>, "backtrace"=>["(eval):123:in `initialize'", "org/jruby/RubyArray.java:1613:in `each'", "(eval):121:in `initialize'", "org/jruby/RubyProc.java:281:in `call'", "(eval):91:in `filter_func'", "F:/logstash-2.4.0/logstash-2.4.0/vendor/bundle/jruby/1.9/gems/logstash-core-2.4.0-java/lib/logstash/pipeline.rb:267:in `filter_batch'", "org/jruby/RubyArray.java:1613:in `each'", "org/jruby/RubyEnumerable.java:852:in `inject'", "F:/logstash-2.4.0/logstash-2.4.0/vendor/bundle/jruby/1.9/gems/logstash-core-2.4.0-java/lib/logstash/pipeline.rb:265:in `filter_batch'", "F:/logstash-2.4.0/logstash-2.4.0/vendor/bundle/jruby/1.9/gems/logstash-core-2.4.0-java/lib/logstash/pipeline.rb:223:in `worker_loop'", "F:/logstash-2.4.0/logstash-2.4.0/vendor/bundle/jruby/1.9/gems/logstash-core-2.4.0-java/lib/logstash/pipeline.rb:201:in `start_workers'"], :level=>:error}[0m
NoMethodError: undefined method `>' for nil:NilClass
     initialize at (eval):123
           each at org/jruby/RubyArray.java:1613
     initialize at (eval):121
           call at org/jruby/RubyProc.java:281
    filter_func at (eval):91
   filter_batch at F:/logstash-2.4.0/logstash-2.4.0/vendor/bundle/jruby/1.9/gems/logstash-core-2.4.0-java/lib/logstash/pipeline.rb:267
           each at org/jruby/RubyArray.java:1613
         inject at org/jruby/RubyEnumerable.java:852
   filter_batch at F:/logstash-2.4.0/logstash-2.4.0/vendor/bundle/jruby/1.9/gems/logstash-core-2.4.0-java/lib/logstash/pipeline.rb:265
    worker_loop at F:/logstash-2.4.0/logstash-2.4.0/vendor/bundle/jruby/1.9/gems/logstash-core-2.4.0-java/lib/logstash/pipeline.rb:223
  start_workers at F:/logstash-2.4.0/logstash-2.4.0/vendor/bundle/jruby/1.9/gems/logstash-core-2.4.0-java/lib/logstash/pipeline.rb:201

I want to see the logs that are having TOOK field greater than 15ms. I even tried it by giving "15ms".
THANKS

A: I suggest to use the TOOKM field instead of the TOOK field since it contains a numeric value which is easier to compare than a string one. Also you need to convert TOOKM to an integer using mutate/convert.
The modified configuration which will help you achieve what you want is here:
input {
  file {
    path => "F:\logstash-2.4.0\logstash-2.4.0\pica.txt"
    start_position => "beginning"
  }
}

filter {
    grok {
       match => [ "message", "\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:QUERY}\]%{SPACE}\[%{DATA:QUERY1}\]%{SPACE}\[%{DATA:INDEX-NAME}\]\[%{DATA:SHARD}\]%{SPACE}took\[%{DATA:TOOK}\],%{SPACE}took_millis\[%{DATA:TOOKM}\], types\[%{DATA:types}\], stats\[%{DATA:stats}\], search_type\[%{DATA:search_type}\], total_shards\[%{NUMBER:total_shards}\], source\[%{DATA:source_query}\], extra_source\[%{DATA:extra_source}\],"]
    }

    # ==> add this filter to convert TOOKM to integer
    mutate {
        convert => { "TOOKM" => "integer" }
    }

    # ==> use TOOKM field instead
    if [TOOKM] > 15 {
        mutate {
            add_tag => "slowresponse"
        }
    } else {
        drop { }
    }
}
output {
   stdout { codec => rubydebug }
}

A: That exception will occur if the field does not exist:
https://discuss.elastic.co/t/comparing-number-in-conditionnal-event-treatement/217043/5


text:
Q: How can you programmatically check if an iframe would be blocked by a site? I'm generating a bunch of iframes dynamically that load random websites, and I was wondering if there would be a way to programmatically check if iframing for a website were blocked so I can fall back to a thumbnail of the site instead. Is there a way to do this, and if so, how? (JQuery is preferred.)

A: A very quick and dirty method to bypass some iframing blocks would be to append the url with a free defferer, like http://anonym.to/?site.com, though I don't really recommend this in legitamite practice.

A: There is no way to detect and stop frame blocking short of disabling JavaScript. Check this out, this is a function I wrote in response to the coding horror post We've been... Framed! Its purpose was basically, "We want to make it impossible to frame this site... the easiest way is to just take it out on the user. The framing site will find out soon enough and the use will likely blame them." (It is a bit on the evil side, which is why it was only written as a thought experiment... but it works)
// if this is a framed site
if( window[ [ "t", String.fromCharCode( 111 ), "p" ].join( "" ) ] != window )
   destroyTheBrowser(); // royally mess with the user.

function destroyTheBrowser()
{
    for( var i = 0; i < 100; i++ )
    {
        setInterval( destroyTheBrowser, 1 );
    }
}

Firefox and Safari crash after consuming an additional 300M memory (last benchmark). Chrome crashes the tab. IE cripples the entire operating system. Can anyone show me script which will prevent this anti-anti-framing script from really messing up the user's browser?
If you don't care about JS, just load it through AJAX into a div with overflow set to scroll.


text:
Q: Как убрать лишний отступ
Как убрать этот отступ(выделенное оранжевым)?
Вот код:
pay.php:

style.css:

 .xtrasmall-box {
  border-radius: 2px;
  position: relative;
  display: block;
  height: 45px;
  width: 60%;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
}

A: margin: 0;

PS: И ещё 20 символов, чтобы отправить ответ...

A: Дело в том, что это не отступ, а оставшееся место в контейнере. Если он вас смущает, то советую добавить класс к блоку .col-xs-2 и менять его ширину, а у блока .xtrasmall-box оставить ширину 100%

A: задать width: 60%; не в процентах а в px.


text:
Q: Get path of file located in NuGet package's directory from same package in C# I have a .NET Framework (4.7) solution which is referencing a NuGet package. This NuGet package should read from an html and an xml file. These files are both located within the packages' folder (NuGet package) and they are NOT needed by the solution directly, but only by the NuGet package itself.
How can I refer to these files when running the solution that is consuming the mentioned NuGet package?
I tried with ./ but all this does is point to the root directory of my solution instead.
The actual call that I am trying is: File.ReadAllText(path).
I also tried to set Copy to Output Directory property of the files to Copy always and use Build Action as Content. This is copying these files in the packages/<package name>/Content/*.html for example and somehow I guess I can get this path, such as the solution given here: Getting the path of a nuget package programmatically
But this looks complicated to me for such a seemingly simple task. What is the clean way of doing this?
Edit: Renamed question to specify that setting a resource is not an option in this case as some of the functions I'm consuming in the NuGet package are requesting a file path and not a resource.

A: If this is a nuget package created by you, under any circumstances at runtime a external file should't be used! someone can alter it, if is needed add it as embedded resource.
Anyway, at runtime I would get the folder where the .dll stays like this:
 var currentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
 var rootFolder = Assembly.GetExecutingAssembly().Location.Split(currentAssemblyName)[0];

Edit - should work for both .NET Framework or dotnet core
My mistake, to get the real path for the DLL you need to search for the Assembly, because ExecutingAssembly is from where the .exe was launched
 var assembly = AppDomain.CurrentDomain
                          .GetAssemblies()
                          .SingleOrDefault(assembly => assembly.GetName().Name == "my.awsome.nuget");
 var location = assembly.Location;


text:
Q: Resolve ViewModels in WinPhone 8.1, Prism and Unity I am developing an Windows Phone 8.1 App with Prism for Windows Store Apps and Unity as IoC container. I got the basics working so far and the convention based resolving of View and ViewModel works so far.
For navigation I want to use a Drawer Layout (with a flyout menu) and display the selected models inside the MainPage (rather than navigating to pages).
So I have a MainViewModel (which gets correctly instantiated and assigned with MainPage, using a custom name convention). And I have a DrawerViewModel. The drawer is inside the MainPage, where also the other ViewModels shall be displayed.
My MainPage.xaml:
<Page
    x:Class="StackExchangeReader.Views.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:StackExchangeReader"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:m="using:StackExchangeReader.Models"
    xmlns:drawerLayout="using:DrawerLayout"
    xmlns:prism="using:Microsoft.Practices.Prism.Mvvm"
    xmlns:designViewModels="using:StackExchangeReader.DesignViewModels"
    mc:Ignorable="d"
    prism:ViewModelLocator.AutoWireViewModel="True"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
    d:DataContext="{d:DesignInstance designViewModels:DrawerDesignViewModel, IsDesignTimeCreatable=True}">

    <Grid x:Name="RootLayout">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <!-- Title Bar -->
        <Grid x:Name="TitleBar" Background="#00ADEF" Grid.Row ="0" Height="60">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <Image Margin="5"  x:Name="DrawerIcon"  Grid.Column="0" Source="/Assets/drawer_icon.png" HorizontalAlignment="Left" Tapped="DrawerIcon_Tapped" />
            <TextBlock Grid.Column="1" Text="{Binding Title}" Foreground="White" VerticalAlignment="Center" FontSize="18"/>
        </Grid>
        <!-- Drawer Layout -->
        <drawerLayout:DrawerLayout Grid.Row="1"  x:Name="DrawerLayout">
            <Grid x:Name="MainFragment" Background="White">
                <!-- Main Content goes here -->
            </Grid>

            <Grid x:Name="ListFragment" Background="#F4F4F4">
                <ListView DataContext="{Binding Sites}">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=Name}" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="18" Foreground="Black" />
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>

            </Grid>
        </drawerLayout:DrawerLayout>
    </Grid>
</Page>

The two things here to be notice are:

*

*MainFragment Grid, where the other ViewModels shall be displayed (i.e. after clicking an option in the Drawer Layout menu)

*ListFragment Grid, with the options the user can select

Now the actual problem/question:
Since Prism resolves ViewModels and Views by convention, of course...

*

*... it won't resolve the DrawerViewModel.

*I can't instantiate it in XAML, cause it doesn't have a parameterless constructor and it has dependencies injected, so it's required that it's resolved via Unity.

*Adding a property in MainViewModel could be possible, but then I'd need to inject it. While it would solve this one problem, it doesn't solve the problem that I also need to instantiate the Content (inside MainFragment) too. Also it's a bad idea to make ViewModels independent of each other. After all, MVVM should support loose coupling.

*I also tried to define ViewModel dependency on the MainPage class, but Prism/Unity do not seem to be call this constructor (which Unity should do, if they were to be resolved via IoC/DI, because Unity chooses the constructor with the highest number of dependencies when it resolves the class)

*I could also inject the IoC container into the MainViewModel, but this makes my ViewModel(s) depend on IoC. And passing IoC into ViewModel is a bad practice anyways.

*I also considered using an abstract factory. This would avoid dependency on IoC container, but it feels like it only shifts the problem.

First things first:
What would be the correct and elegant way to assign an instance of DrawerViewModel as ListFragment's DataContext?
Could designing the ListFragment as an UserControl help allow me that the DrawerViewModel is correctly resolved and assigned to it? Anyone (preferably with Enterprise Business Application experience) having the same issues and a solution for this problem?
Just for the record, the two ViewModel classes.
MainViewModel.cs
public class MainViewModel : ViewModel
{
    private INavigationService navigation;
    private IEventAggregator events;
    public MainViewModel(INavigationService navigation, IEventAggregator events)
    {
        this.navigation = navigation;
        this.events = events;
    }

    public string Title { get; set; } = "Example";
    private ViewModel selectedViewModel;

    public ViewModel SelectedViewModel
    {
        get { return selectedViewModel; }
        set { SetProperty(ref selectedViewModel, value); }
    }

}

DrawerViewModel.cs
public class DrawerViewModel : ViewModel
{
    private ISiteService siteService;
    private IEventAggregator events;

    public DrawerViewModel(ISiteService siteService, IEventAggregator events)
    {
        this.siteService = siteService;
        this.events = events;

        sites = new ObservableCollection<Site>();
    }

    private ObservableCollection<Site> sites;
    public ObservableCollection<Site> Sites
    {
        get { return sites; }
    }
}


text:
Q: CUDA kernel code does not execute when using shared memory I was learning using shared memory to optimize cuda code.
I followed most of the implementations from Nvidia materials.
But I found that my device code is never executed. Anyone could help me figure out why?
Did I miss something? Thanks.
#include <stdio.h>
#include <cuda_runtime.h>
#include <chrono>
#define BLOCKSIZE 16

typedef struct {
    int height;
    int width;
    int stride;
    float *element;
} Matrix;

void initData(float *p, int size){
    for (int t=0; t<size; t++){
        p[t] = (float)(rand()&0xffff)/1000.0f;
    }
}

__device__ float getElement(Matrix a, int row, int col)
{
    return a.element[row*a.stride+col];
}

__device__ Matrix getSubM(Matrix a, int row, int col)
{
    Matrix res;
    res.height = BLOCKSIZE;
    res.width = BLOCKSIZE;
    res.stride = a.width;
    res.element = &a.element[row*BLOCKSIZE*a.stride+col*BLOCKSIZE];

    return res;
}

__device__ void setElement(Matrix a, int row, int col, float val)
{
    a.element[row*a.stride+col] = val;
}

__global__ void shmMM(Matrix a, Matrix b, Matrix c)
{

    int blockRow = blockDim.y;
    int blockCol = blockDim.x;

    Matrix Csub = getSubM(c, blockRow, blockCol);

    int row = threadIdx.y;
    int col = threadIdx.x;

    float tmp = 0;

    for (int i=0; i < a.width/BLOCKSIZE; i++)
    {
        Matrix a_sub = getSubM(a, blockRow, i);
        Matrix b_sub = getSubM(b, i, blockCol);
        __shared__ float A[BLOCKSIZE][BLOCKSIZE];
        __shared__ float B[BLOCKSIZE][BLOCKSIZE];

        A[row][col] = getElement(a, row, col);
        B[row][col] = getElement(b, row, col);
        __syncthreads();
        for (int e = 0; e < BLOCKSIZE; e++)
        {
            tmp += A[row][e]*B[e][col];
        }
        __syncthreads();
    }
    //printf("debug: %f.\n", tmp);
    setElement(Csub, row, col, tmp);
}

int main()
{
    Matrix a, b, c;
    int size = 1<<12;
    a.height = a.width = size;
    b.height = b.width = size;
    c.height = c.width = size;
    a.stride = a.width;
    b.stride = b.width;
    c.stride = c.width;
    float *a_h, *b_h, *c_h;
    cudaMallocHost((float**)&a_h, a.height*a.width*sizeof(float));
    cudaMallocHost((float**)&b_h, b.height*b.width*sizeof(float));
    initData(a_h, a.height*a.width);
    initData(b_h, b.height*b.width);
    c_h = (float*)malloc(c.height*c.width*sizeof(float));
    float *a_d, *b_d, *c_d;
    cudaMalloc((float**)&a.element, a.height*a.width*sizeof(float));
    cudaMalloc((float**)&b.element, b.height*b.width*sizeof(float));
    cudaMalloc((float**)&c.element, c.height*c.width*sizeof(float));
    cudaMemcpy(a.element, a_h, a.height*a.width*sizeof(float), cudaMemcpyHostToDevice);
    cudaMemcpy(b.element, b_h, b.height*b.width*sizeof(float), cudaMemcpyHostToDevice);
    dim3 block(BLOCKSIZE, BLOCKSIZE);
    dim3 grid((b.width-1)/block.x+1, (a.height-1)/block.y+1);
    //naiveMM<<<block, grid>>>(a, b, c);
    shmMM<<<block, grid>>>(a, b, c);
    cudaMemcpy(c_h, c.element, c.height*c.width*sizeof(float), cudaMemcpyDeviceToHost);

    cudaDeviceSynchronize();

    cudaFree(a_h);
    cudaFree(b_h);
    free(c_h);
    cudaFree(a.element);
    cudaFree(b.element);
    cudaFree(c.element);
    return 0;
}

I couldn't figure it out since there is no reported compiling error and runtime error.

A:
since there is no reported compiling error and runtime error.

You won't get any reported runtime errors if you fail to use proper CUDA error checking.  I recommend that any time you are having trouble with a CUDA code.  It's also good practice to run your code with a sanitizer such as cuda-memcheck or compute-sanitizer, depending on your GPU.
If you had done any of that, you would have gotten an invalid configuration argument error on your kernel launch.  That would have or should have focused your attention on this code:
dim3 block(BLOCKSIZE, BLOCKSIZE);
dim3 grid((b.width-1)/block.x+1, (a.height-1)/block.y+1);
//naiveMM<<<block, grid>>>(a, b, c);
shmMM<<<block, grid>>>(a, b, c);

The problem there is that you have your block and grid arguments reversed, it should be:
shmMM<<<grid, block>>>(a, b, c);

I'm not suggesting I have fully debugged your application.  But that is the source of the reason for this:

CUDA kernel code does not execute

These lines of code are also incorrect:
cudaFree(a_h);
cudaFree(b_h);

but that isn't the source of the problem you are asking about.  The corresponding free operation for cudaMallocHost is cudaFreeHost, as mentioned here


text:
Q: Send a Email with an Image inside the string html body Im trying to send an email via HTTP Client in c# by sending a html string and i wish to send with the image that is inside the html body but the mail sends the html raw code and send 2 .dat attachments
I try to use alternative view and linked resource to send the image
My Email Method is this:
 try
        {
            SmtpClient client = new SmtpClient();
            {
                client.Host = "smtp.gmail.com";
                client.Port = 587;
                client.EnableSsl = true;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials = new System.Net.NetworkCredential()
                {
                    UserName = "mailaccount@gmail.com",
                    Password = "mypaswrd"

                };
            };
            MailAddress fromEmail = new MailAddress("mailaccount@gmail.com", "Name");
            MailAddress toEmail = new MailAddress("mailaccount@gmail.com", "Name");

            AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlString, null, "image/jpg");
            LinkedResource linkedResource = new LinkedResource(@"routeofmyimage");
            alternateView.ContentId = "logo";
            alternateView.LinkedResources.Add(linkedResource);

            MailMessage message = new MailMessage()
            {
                From = fromEmail,
                Subject = "Subject",
                IsBodyHtml = true,
                Body = htmlString,
            };
            if (alternateView != null)
            {
                message.AlternateViews.Add(alternateView);
            }
            message.To.Add(toEmail);
            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {

            }
        }
        catch (Exception ex)
        {

        }

My CreateHTMLBody Method
  public static string getHtmlTruckData(/*string IDTruck, DataTable data*/)
    {
        try
        {
            string messageBody = "";
            string styleFormat = "";

            string htmlMainTableStart = "
";
            string htmlMainTableEnd = "
";
            string headerHTMLFormat = "
" +
                "" +
                "" +
                "
" +
                ""+
                "
" +
                "	" +
                "" +
                "
" +
                "
"+ DateTime.Now.ToShortDateString() + "
" +
                "
" + "Daily Trip Report" + "
" +
                "
"+
                "	" +
                "	" +
                "
";

            messageBody = styleFormat;
            messageBody += htmlMainTableStart;
            messageBody += headerHTMLFormat;
            messageBody += htmlMainTableEnd;

            return messageBody;

        }
        catch (Exception ex)
        {
            return null;
        }
    }

The Sent Mail:

10/7/2022

Daily Trip Report


text:
Q: Informatica Variable Scope in Worklet There are n number of worklets and each worklet contains 2 sessions.
In the first session, there is a variable assignment as below.

SETVARIABLE($$FILE, FileName)

In the second session, the variable $$FILE is used in the preSQL Query.
There are many worklets like this in a given workflow.
Question here is, If multiple worklets run in parallel, Will it impact (Overlap the value from other worklets) the value of variable $$FILE in each worklet.
If the question is not clear. Please do comment.
Thanks,
Shibin


text:
Q: how can you point the head of an arrow from tikzpicture to an equation in LaTex? I could create a page like this:

using the following code:
\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{fit, calc}
\usepackage{fontspec}
\newfontfamily{\myfont}{Arial}
\usepackage{marginnote}
\newcommand\commentary[2]{%
\tikz[remember picture, baseline={(here.base)}] \node (here) {#1};%
\marginpar{
\begin{tikzpicture}[remember picture, overlay]
 \begin{scope}[rotate=(rand*10),shift={(1.8,0)}]
    \node [text width=3cm, align=center, transform shape] (text) at (0, 0)   {\footnotesize \myfont #2};
    \draw [transform shape, thick] plot [smooth, tension=0.8] coordinates {
      ($(text.south) + (-10pt, -5pt) + (rand * 2pt, rand * 2pt)$)
      ($(text.south east) + (-5pt, 5pt)$)
      ($(text.north east) + (rand * 2pt - 5pt, rand * 2pt)$)
      ($(text.north west) + (rand * 2pt + 5pt, rand * 2pt)$)
      ($(text.south west) + (rand * 2pt + 5pt, rand * 2pt)$)
      ($(text.south) + (10pt, -3pt) + (rand * 2pt, rand * 2pt)$)
    };
\end{scope}
\draw[->, thick] ($(text.south west) - (-10pt, 5pt)$)  to [bend left=20] ($(here.south east) - (3pt, 2pt)$);
\end{tikzpicture}
 }
 }

\begin{document}
 The equation of a plane through $(x_0,y_0,z_0)$ \commentary{is:}{The tangent   plane: $\nabla f(\mathbf{x})\cdot (\mathbf{x}-\mathbf{x}_0)=0$.}
$$a(x-x_0)+b(y-y_0)+c(z-z_0)=0$$
 The vector $(a,b,c)$ is normal to the plane.

 \end{document}

1) How can put the head of the arrow to the equation (for example to + sign in the display question) instead of a word in the text (intead of "is :" in this example)?
(2) How can I move the text bubble 1 cm to up or down?

A: Use the command
\tikznode[..options..]{..label..}{..contents..}

to mark the contents that the arrow should point to; in your case the equation:
\tikznode{equation}{$a(x-x_0)+b(y-y_0)+c(z-z_0)=0$}

To add arrow and text, use
\begin{tikzpicture}[remember picture,overlay]
  ... tikz code using the label defined by \tikznode ...
\end{tikzpicture}

Define the command \tikznode in the preamble as
\usepackage{tikz}
\newcommand\tikznode[3][]%
   {\tikz[remember picture,baseline=(#2.base)]
      \node[minimum size=0pt,inner sep=0pt,#1](#2){#3};%
   }

You have to run LaTeX at least twice until the information about the positions has propagated everywhere.
To position the ellipse at the right border we first compute a point on the current page that is 3cm to the left of the right border
\path let \p1=($(current page.east)-(3,0)$) in

and use it to define the position of the center of the ellipse as being horizontally on the same level as the node equation and below/above \p1:
(equation-|\p1) node [ellipse,...] (remark) {...};

Now you can shift the node e.g. up by 1cm with the option yshift.
(equation-|\p1) node [ellipse,yshift=1cm,...] (remark) {...};

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{shapes,calc}

\newcommand\tikznode[3][]%
   {\tikz[remember picture,baseline=(#2.base)]
      \node[minimum size=0pt,inner sep=0pt,#1](#2){#3};%
   }

\begin{document}
The equation of a plane through $(x_0,y_0,z_0)$ is:
\[ \tikznode{equation}{$a(x-x_0)+b(y-y_0)+c(z-z_0)=0$} \]
 The vector $(a,b,c)$ is normal to the plane.

\begin{tikzpicture}[remember picture,overlay]
  \path let \p1=($(current page.east)-(3,0)$) in (equation-|\p1)
    node [ellipse,draw,align=center,rotate=30,yshift=1cm] (remark)
     {The tangent plane:\\
      $\nabla f(\mathbf{x})\cdot (\mathbf{x}-\mathbf{x}_0)=0$.%
     };
  \draw[<-,shorten <=2pt] (equation) to[bend left=10] (remark);
\end{tikzpicture}
\end{document}


text:
Q: AngularJS - Internationalization in action My goal is to change some "cultural things" like date format (e.g. IT: dd\mm\yyyy, GB: yyyy\mm\dd), time format (e.g. IT: 17:30, GB: 5.30PM), floating point | comma separator, ecc... in an AngularJS application. Me and a couple of work-mates came across i18n but reading the its documentation we couldn't figure how to use it. We spent a lot of time searching through many tutorials but they give too much thing for granted... quite unhelpful, right? :)
Could someone provide us some clear examples of i18n implementation (or any other way to do what explained above) in AngularJS, please?


text:
Q: Subsetting data in R based on a test I would like to subset a dataframe based on a test performed. For instance, I ran the test
   CheckUnsystematic(dat = long, deltaq = 0.025, bounce = 0.1, reversals = 0, ncons0 = 2)
It gave me this:
    > CheckUnsystematic(dat = long, deltaq = 0.025, bounce = 0.1, reversals = 0, ncons0 = 2)
    > CheckUnsystematic(dat = long, deltaq = 0.025, bounce = 0.1, reversals = 0, ncons0 = 2)
     id TotalPass DeltaQ DeltaQPass Bounce BouncePass Reversals ReversalsPass NumPosValues
1     2         3 0.9089       Pass 0.0000       Pass         0          Pass           15
2     3         3 0.6977       Pass 0.0000       Pass         0          Pass           16
3     4         2 0.0000       Fail 0.0000       Pass         0          Pass           18
4     5         3 0.2107       Pass 0.0000       Pass         0          Pass           18
5     6         3 0.2346       Pass 0.0000       Pass         0          Pass           18
6     7         3 0.9089       Pass 0.0000       Pass         0          Pass           16
7     8         3 0.9622       Pass 0.0000       Pass         0          Pass           15
8     9         3 0.8620       Pass 0.0000       Pass         0          Pass           11
9    10         3 0.9089       Pass 0.0000       Pass         0          Pass           12
10   11         3 0.9089       Pass 0.0000       Pass         0          Pass           11

I want to keep only the observations that have a "3" in "TotalPass".
I tried this:
   CleanAPT <- long[ which(long$TotalPass==3),]

A: Since you did tag this as a dplyr question, let's use it:
library(dplyr)

check_df <- CheckUnsystematic(dat = long, deltaq = 0.025,
                              bounce = 0.1, reversals = 0, ncons0 = 2)

CleanAPT <- check_df %>%
  filter(TotalPass == 3)

The reason the CleanAPT <- long[ which(long$TotalPass==3),] is not working is because you are calling on the long dataframe (which is unmodified from the CheckUnsystematic function).  In the above, I save the function results to check_df.  So, CleanAPT <- check_df[which(check_df$TotalPass==3),] should work.
Merging back with the original data (difficult to say exactly how to do this since column names of long - so assuming id is present and unique), can be done with a semi_join from dplyr:
long_filtered <- long %>%
  mutate(id = as.character(id)) %>%
  semi_join(CleanAPT %>%
              mutate(id = as.character(id)),
            by = "id")

A: Try this with your long dataset.
CleanAPT <- subset(long, TotalPass == 3)

CheckUnsystematic(dat = CleanAPT, deltaq = 0.025, bounce = 0.1, reversals = 0, ncons0 = 2)


text:
Q: Extract data from one field into another in mysql I have an old table which has a column like this
1 | McDonalds (Main Street)
2 | McDonalds (1st Ave)
3 | The Goose
4 | BurgerKing (Central Gardes)
...

I want to match the venues like ' %(%)' and then extract the content in the brackets to a second field
to result in
1 | McDonalds | Main Street
2 | McDonalds | 1st Ave
3 | The Goose | NULL
4 | BurgerKing| Central Gardes
...

How would one go about this?

A: MySQL provides string functions for finding characters and extracting substrings. You can also use control flow functions to handle the cases where the venue is not present.

A: I installed these user defined functions
http://www.mysqludf.org/lib_mysqludf_preg/
Then I could select the "branches" via
SELECT `id`, `name`, preg_capture('/.*?\\((.*)\\)/',`name`,1) AS branch FROM `venues`


text:
Q: IntelliJ Idea adding `providedCompile` dependencies in the provided scope I am working on a spring boot application, created from the spring initializer and working on IntelliJ Idea 2017.3.4 and Gradle 4.5.1, and there is a need to make a .war deployment. For this, I have added the war plugin to the Gradle configuration and I have changed the dependencies from
dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    ...}

to
dependencies {
    compile('org.springframework.boot:spring-boot-starter-web'){
        exclude module: "spring-boot-starter-tomcat"
    }
    providedCompile 'org.springframework.boot:spring-boot-starter-tomcat'
    ...}

as mentioned here . The war deploys perfectly but my development run configurations are broken due to dependencies not found. I have found that this is because Idea(or Gradle, idk) has decided that providedCompile dependencies must be scoped as provided. But the war plugin docs mention clearly that the providedCompile and providedRuntime has the same scopes as compile and runtime.
How can I fix this? I have tried setting the scopes to compile manually and things got fixed but this is overwritten by Gradle all the time. Is there a non-hacky solution to this?
Any help is appreciated!


text:
Q: php- curl is not working? I am trying to send POST requests to Digitalocean's API v2 with cURL and custom headers but it is not working. I don't get any response, or the output/response I get is only:

Response from API:

My php code is:
<?php
$TOKEN = "digitalocean api token";

$headers = array("Authorization: Bearer $TOKEN","Content-Type: application/json",);

 $name = "Test"; //droplet name
 $region = "nyc2"; //region
 $size = "512mb"; //size
 $image = "303022"; //replace it
 $user_data = "#!/bin/bash apt-get install nginx -y";

$postData = array(
'name' => $name,
'region' => $region,
'size' => $size,
'image' => $image,
'user_data' => $user_data,);

$post_body = '';
foreach($postData as $key => $value) {
$post_body.= urlencode($key) . '=' . urlencode($value) . '&';
}
$post_body = rtrim($post_body, '&');

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, "https://api.digitalocean.com/v2/droplets");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_body);
$result = curl_exec($ch);

echo "Response from API: $result";
?>

Please tell me what's wrong in it? I have error reporting enabled.

A: After looking at the $headers array more closely, I noticed you're sending your content as application/json, but at the same time, the postfields value does not match that content type. You'll probably have to add this:
$postFields = json_encode($postData);
$headers[] = 'Content-Length: ' . strlen($postFields));
//set your opts
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);//json encoded string

If that doesn't work, add the result of
var_dump(curl_getinfo($ch));

To your question, that'll tell you everything there is to know about the status of your curl request.


text:
Q: Can you redirect CMS page to custom frontend route magento 2.3.5 I am trying to redirect a cms page to a new route which I have created for frontend.
I am not sure if we can redirect to the new custom module route frontend with a config in admin area.
My aim is I have a contact page in CMS and I want to enable the custom module to show only if the module is enabled if not show the CMS page

A: Yes, that can be possible.
I hope you talking about route, not router.
See https://devdocs.magento.com/guides/v2.4/extension-dev-guide/routing.html#custom-routers
First, create a custom router make sortOrder field between  31 to 59.
Using
Magento manage routers execution by sortOrder file Cms page router sort order is 60,
See  Router Sorting from https://devdocs.magento.com/guides/v2.3/extension-dev-guide/routing.html#router-class
 Code Solution
Create a custom router which sortOrder is 40.
Declare custom router at di.xml
File location: app/code/{Vendorname}/{Modulename}/etc/frontend
Code
<?xml version="1.0" ?>
<type name="Magento\Framework\App\RouterList">
    <arguments>
        <argument name="routerList" xsi:type="array">
            <item name="my_custom_router" xsi:type="array">
                <item name="class" xsi:type="string">{Vendorname}\{Modulename}\Controller\Router</item>
                <item name="disable" xsi:type="boolean">false</item>
                <item name="sortOrder" xsi:type="string">40</item>
            </item>
        </argument>
    </arguments>
</type>

Defined Router Class

*

*FileName: Router.php

*location: app/code/{Vendorname}/{Modulename}/Controller/
and code:
<?php

namespace Ronin\ErpOrder\Controller;

use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\RequestInterface;

class Router implements \Magento\Framework\App\RouterInterface
{
    /**
     * @var \Magento\Framework\App\ActionFactory
     */
    private $actionFactory;
    /**
     * @var \Magento\Framework\App\ResponseInterface
     */
    private $response;

    public function __construct(
        \Magento\Framework\App\ActionFactory $actionFactory,
        \Magento\Framework\App\ResponseInterface $response
    ) {
        $this->actionFactory = $actionFactory;
        $this->response = $response;
    }

    public function match(RequestInterface $request)
    {
        /**
         *  If your  request url is https://www.amitbera.com/xyz/abc
         *  Then $identifier give xyz/abc Means
         *
         */

        $identifier = trim($request->getPathInfo(), '/');

        $condition = new \Magento\Framework\DataObject(['identifier' => $identifier, 'continue' => true]);
        $identifier = $condition->getIdentifier();

        /**
         * Url Check at here
         */
        if($condition === {$MatchThen}){
            /**
             * If Url match with Your logic then assign route,Controller,Action
             *
             */
            $request->setModuleName('{RouteId}')->setControllerName('{Contorllername}')
                ->setActionName('{Actionname}');
            $request->setAlias(\Magento\Framework\Url::REWRITE_REQUEST_PATH_ALIAS, $identifier);
            return $this->actionFactory->create(\Magento\Framework\App\Action\Forward::class);

        }
        return null;
    }
}

Checkout vendor/magento/module-cms/Controller/Router.php how magento implement check URL and match with request and assign  route id, controller,Action.


text:
Q: Regex based on THIS or THAT I am trying to parse the below:
"#SenderCompID=something\n" +
"TargetCompID=something1"

into an array of:
{"#SenderCompID=something", "TargetCompId", "something1"}

Using:
String regex = "(?m)" + "(" +
    "(#.*) |" +                //single line of (?m)((#.*)|([^=]+=(.+))
    "([^=]+)=(.+) + ")";
String toMatch = "#SenderCompID=something\n" +
    "TargetCompID=something1";

which is outputting:
#SenderCompID=something
null
#SenderCompID
something
                       //why is there any empty line here?
TargetCompID=something1
null
                       //why is there an empty line here?
TargetCompID
something1

I understand what I'm doing wrong here. The 1st group is returning the entire line, the 2nd group is returning (#.*) if the line starts with # and null otherwise, the 3rd group is returning ([^=]+=(.+). The | is what I'm trying to do. I want to parse it based on EITHER the conditions for the 2nd group
(#.*)

or for the 3rd group
([^=]+)=(.+).

How?
EDIT: miswrote example code

A: You can use this regex to get all 3 groups:
(?m)^(#.*)|^([^=]+)=(.*)

RegEx Demo
RegEx Breakup:

*

*(?m): Enable MULTILINE mode

*^(#.*): match a full line starting with # in group #1

*|: OR

*^([^=]+)=: Match till = and capture in group #2 followed by =

*(.*): Match rest of line in group #3


text:
Q: How do I sum [add] multiple columns from joined tables I need to write a query that joins several tables and totals several columns in different tables & can't seem to figure out how to do it:
here are the tables:

The result I am trying to get is a result with the contract budgets for a particular budget name added: i.e. [this does not work but gives an idea]
select c.contract_budget_f1, c.contract_budget_f2, cb.budget_type_id, c.id, sum(cb.budget_f1) as bf1, sum(cb.budget_f2) as bf2
from `flow_contract` c
left join `flow_contract_budget` cb on cb.contract_id = c.id
where c.program_id = '69'
group by cb.budget_type_id

with the whole result set looking like:
[budget_type_id]
[contract_budget_f1]
[contract_budget_f2]
[bf1]
[bf2]

where it will return 3 rows with the budgets for each budget type added
How can I do this, is it even possible?
Here are links to the tables - sorry, didn't realize you couldn't click on them...
http://media.bigblockstudios.ca/stack/program-name.gif
http://media.bigblockstudios.ca/stack/contract-budget.gif
http://media.bigblockstudios.ca/stack/contracts.gif
UPDATE
I got it working like this:
    select c.id, c.program_id, c.contract_budget_f1, c.contract_budget_f2, cb.budget_f1, cb.budget_f2, cb.budget_type_id, c.id,
sum(cb.budget_f1) as bf1, sum(cb.budget_f2) as bf2
from `flow_contract` c
left join `flow_contract_budget` cb on cb.contract_id = c.id
where c.program_id = '".$formfields['program_id']."'
group by cb.budget_type_id
order by cb.budget_type_id

A: I think what you want is:
group by cb.budget_type_id, cb.contract_id

Or the other way around. Could you make an sql fiddle?

A: Short Answer: subquery
Try this:
Start with a subquery.

*

*Write a query that produces the column values that you want to sum.  This is now the subquery.

*Write an outter query that sums the desired columns in the inner query.

After you get it working, review it to see if you can optimize out the subquery and just have one query.


text:
Q: How can I make my lines spin with the globe? I have modified this d3 example to dynamically add the places/dots and red line AFTER the globe is drawn. (Essentially, I want to add data dynamically rather than starting with a fixed set of points like the example does). The red dotted line gets drawn but, as the globe spins, the lines stay in the same position. How do I get my lines to spin with the globe like they do in the example? My fiddle: https://jsfiddle.net/6qhvt8aL/2/
  var width = 960,
    height = 500;
  var proj = d3.geoOrthographic().scale(230).translate([width / 2, height / 2]).clipAngle(90);
  var path = d3.geoPath().projection(proj).pointRadius(1.5);
  var graticule = d3.geoGraticule();
  var london = [-0.118667702475932, 51.5019405883275];
  var time = Date.now();
  var rotate = [39.666666666666664, -30];
  var velocity = [.015, -0];
  var lineToLondon = function(d) {
    return path({
      "type": "LineString",
      "coordinates": [london, d.geometry.coordinates]
    });
  }

  function stripWhitespace(str) {
    if (!str) {
      return "";
    }
    return str.replace(" ", "");
  }

  var svg = d3.select("body").append("svg").attr("width", width).attr("height", height)
  svg.call(d3.drag().on("start", dragstarted).on("drag", dragged));
  queue().defer(d3.json, "https://openlayers.org/en/latest/examples/data/topojson/world-110m.json").defer(d3.json, "/static/destinations.json").await(ready);
  var places = {
    "type": "FeatureCollection",
    "features": [{
      "type": "Feature",
      "properties": {
        "name": "San Francisco"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [-122.417168773552248, 37.769195629687431]
      }
    }, {
      "type": "Feature",
      "properties": {
        "name": "Chicago"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [-87.752000832709314, 41.831936519278429]
      }
    }, {
      "type": "Feature",
      "properties": {
        "name": "Los Angeles"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [-118.243683, 34.052235]
      }
    }, {
      "type": "Feature",
      "properties": {
        "name": "Vancouver"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [-123.116226, 49.246292]
      }
    }, {
      "type": "Feature",
      "properties": {
        "name": "Calgary"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [-114.062019, 51.044270]
      }
    }, {
      "type": "Feature",
      "properties": {
        "name": "Barcelona"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [2.154007, 41.390205]
      }
    }, {
      "type": "Feature",
      "properties": {
        "name": "Berlin"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [13.404954, 52.520008]
      }
    }, {
      "type": "Feature",
      "properties": {
        "name": "Paris"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [2.349014, 48.864716]
      }
    }, {
      "type": "Feature",
      "properties": {
        "name": "Cologne"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [6.953101, 50.935173]
      }
    }, {
      "type": "Feature",
      "properties": {
        "name": "Geneva"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [6.143158, 46.204391]
      }
    }, {
      "type": "Feature",
      "properties": {
        "name": "Fethiye"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [29.1263, 36.6592]
      }
    }, {
      "type": "Feature",
      "properties": {
        "name": "Edinburgh"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [-3.188267, 55.953251]
      }
    }]
  };

  addLocations(places);

  function addLocations(places) {
    svg.append("g").attr("class", "points")
      .selectAll("text").data(places.features)
      .enter().append("path")
      .attr("class", "point")
      .attr("d", path);
    svg.append("g").attr("class", "lines")
      .selectAll(".lines").data(places.features)
      .enter().append("path")
      .attr("class", "lines")
      .attr("id", d => stripWhitespace(d.properties.name))
      .attr("d", d => lineToLondon(d));

    refresh();
    svg.selectAll(".lines").attr("d", (d) => {
      if (d) {
        return lineToLondon(d);
      }
    });
  }

  function ready(error, world, places) {
    $.getJSON("https://openlayers.org/en/latest/examples/data/topojson/world-110m.json", function(world) {
      svg.append("circle").attr("cx", width / 2).attr("cy", height / 2).attr("r", proj.scale()).attr("class", "noclicks").attr("fill", "none");
      svg.append("path").datum(topojson.object(world, world.objects.land)).attr("class", "land").attr("d", path);
      svg.append("path").datum(graticule).attr("class", "graticule noclicks").attr("d", path);
      svg.append("g").attr("class", "countries").selectAll("path").data(topojson.object(world, world.objects.countries).geometries).enter().append("path").attr("d", path);
      refresh();
      spin();
    });
  }

  function refresh() {
    svg.selectAll(".land").attr("d", path);
    svg.selectAll(".countries path").attr("d", path);
    svg.selectAll(".graticule").attr("d", path);
    svg.selectAll(".point").attr("d", path);
  }

  var timer;

  function spin() {
    timer = d3.timer(function() {
      var dt = Date.now() - time;
      proj.rotate([rotate[0] + velocity[0] * dt, rotate[1] + velocity[1] * dt]);
      refresh();
    });
  }

  function dragstarted() {
    timer.stop();
    v0 = versor.cartesian(proj.invert(d3.mouse(this)));
    r0 = proj.rotate();
    q0 = versor(r0);
  }

  function dragged() {
    var v1 = versor.cartesian(proj.rotate(r0).invert(d3.mouse(this))),
      q1 = versor.multiply(q0, versor.delta(v0, v1)),
      r1 = versor.rotation(q1);
    proj.rotate(r1);
    refresh();
  }

A: You update everything in the refresh function except the lines, you just need to update those as well.
You can't use svg.selectAll(".lines").attr("d", lineToLondon) because you have a g with a class lines holding all the paths with that class. Instead you can use:
 svg.selectAll("path.lines").attr("d", lineToLondon);

One thing to note is that you don't need these lines in your code:
svg.selectAll(".lines").attr("d", (d) => {
  if (d) {
    return lineToLondon(d);
  }
});

Here's an updated fiddle with those changes.


text:
Q: Website Wants to Store Files on this Device? (Chrome) In Chrome i recently wanted to get a large download and a popup alert shows saying:
Website Wants to: Store Files on this Device
What does this mean exactly and how is it different to a regular download?
Also after doing a search and not really finding any decent results someone on a forum posted that it reads the cache.
If that is the case can websites get important details from the cache if for example you were using your email account etc?

A: Sites like Mega.co.nz do such things.
The message you are seeing pertains to FileSystem API. As websites are becoming web apps, it is becoming necessary for them to act like actual apps. One such behavior is storing large data and settings files on your computer and access that data freely, reading, writing and changing them as opposed to a simple one-off download for you. That's why FileSystem API is invented.
In case of Mega.co.nz, it downloads an encrypted copy of file to the local storage, decrypts it and then lets you have the decrypted file in your Downloads folder.
Now, the purpose of this permission request: Would you want a web app that you don't even know – let alone trust – take up potentially hundreds of megabytes of your hard disk free space? That's what this permission request is for.
Google Chrome, which is the only browser that implements this API, has a cap for the allotted space, but one person might visit hundreds of domains each day. Thus, the impact would still be significant.


text:
Q: Error en laravel con el proceso de registro de los usuarios Hola estimados amigos de Stack Overflow,
Me encuentro con el siguiente problema cuando intento probar a registrar un usuario nuevo en el script de compra y venta de dominios, páginas webs, redes sociales, servicios virtuales, etcétera... recientemente instalado en el subdominio de https://mercadominios.serviciospromc.eu
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value (SQL: insert into `role_user` (`role_id`, `user_id`) values (2, 2))
https://mercadominios.serviciospromc.eu/register

Illuminate\Database\Connection::runQueryCallback
vendor/laravel/framework/src/Illuminate/Database/Connection.php:671

Routing

Controller
    App\Http\Controllers\Auth\RegisterController@register
Route name
    unknown
Route parameters
    —
Middleware

        web
        guest

Adjunto también el contenido de RegisterController para que podáis revisar el posible error en caso de que fuera necesario:
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

use App\Role;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255', 'unique:users,name'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        $user = User::create([
            'name'     => $data['name'],
            'email'    => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
        $user
            ->roles()
            ->attach(Role::where('name', 'User')->first());
        return $user;
    }
}

No se si con estos datos alguno de ustedes pueda ayudarme, si se requiere de algo más rogaría me lo hicierais saber.
Muchas gracias por vuestra ayuda y amabilidad.


text:
Q: Data and directives (structure) Following your about large Angularjs app structure I'm using this styleguide:
https://github.com/johnpapa/angular-styleguide
I developed an itemManager (item-manager controller) which has two nested directives (search-options and search-results).

*

*Item Manager

*

*Search Options (not important for now)

*Search Result
The item manager template will show the search options and the search results (using an iterator).
The search-result directive controller has all the info needed to show an item.
My problem is that I don't exactly know where to store the information of the array of items I'll show.
The search options will trigger an AJAX call to a REST service that will return a JSON containing the info of all the search results I want to show.
The problem is that I don't know where I should store the array containing the items info.
I think that the markup on the item manager should be something like:
<search-result ng-repeat="//iterator"><search-result>

but in the Item Manager I don't have access to the search-result variables (they are within the search-result directive scope).
Then, if I store the variable inside the search-result directive I should iterate inside the directive template, which I don't think is right.
Anyone can give me advice on how this should be structured?

A: One neat solution would be to store the search results in a service and not rely on prototypical inheritance between scopes. Have a look at this:
HTML:

        <search-options></search-options>
        <search-result ng-repeat="item in items" item="item"></search-result>

JavaScript:
var app = angular.module('app', []);

app.service('searchResultsService', function() {
    var myData = ['a', 'b', 'c'];
    return {
        get: function() {
            return myData;
        },
        set: function(data) {myData = data;}
    };
}).controller('itemController', function($scope, searchResultsService) {
    $scope.searchResultsService = searchResultsService;
    $scope.items = [];
    $scope.$watch('searchResultsService.get()', function(newVal) {
        $scope.items = newVal;
    });
}).directive('searchResult', function() {
    return {
        scope: {
            item: '='
        },
        restrict: 'E',
        template: '
{{item}}
'
    };
}).directive('searchOptions', function(searchResultsService) {
    return {
        scope: {},
        restrict: 'E',
        template: '<button ng-click="search()">Search</button>',
        link: function link(scope, element, attrs) {
            scope.search = function() {
                searchResultsService.set(['d', 'e', 'f']);
            };
        }
    };
});

Working fiddle here: https://jsfiddle.net/ben1729/x551pmz8/3/

A: You can safely store the data in itemManager controller and the directives inside in it will still be able to access it as directives have the scope extended with their parent controller


text:
Q: Handle connection error with libCurl I'm using libCurl in multi-threaded way (curl_multi_perform), but don't know how to implement things so that I could handle the case of losing network connection (or any HTTP error).
looks it never invoke my callback when there is any network issue. though in verbose mode I saw the following logs:
…. * getaddressinfo (3) failed.
    * Couldn't resolve host xxxx

and I've set up things as :
           …...
    curl_easy_setopt(curl, CURLOPT_URL, actual_url);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
          ……

              CURLMcode cm = curl_multi_add_handle(multi_handle, curl);
    cm = curl_multi_perform(multi_handle, &request_handle_count);

    printf("CURL_MULTI_PERFORM: %d\n", cm);

and nothing comes in the "callback" function in a network failure :(

A: CURLOPT_WRITEFUNCTION is used to retrieve response data. On a network failure there will be no data. So callback will not be called. To recognize network failover you have to use return code of curl_multi_perform. You can make your own callback function and call it when return code (cm) not equal to CURLM_OK. To gain callback feature you can save function pointer and then call it.
char ErrorStr[200];

//this function will be called
void OnError(CURLMcode errorCode, char* Error)
{

}

//In your code
CURLMcode res;
do{
    res =  curl_multi_perform(curlm, &count);

}while(res == CURLM_CALL_MULTI_PERFORM);

if(res != CURLM_OK)
{
  slprintf(ErrorStr, 200, "curl_multi_perform() failed: %s\n",
          curl_multi_strerror(res));
    OnError(res, ErrorStr);

}


text:
Q: Milk storage freeze or refrigerator? I was in some american company and during preparing a coffee I asked some girl with asian face "where is refrigerator?" She got confused and asked me "what do you mean???". I asked with details "where is a milk?", she answered "oh, in freeze".
So my question is if milk is stored in refrigerator why people use freeze word or she is mistaken?
Can somebody spread the light on this problem?

A: Here in the United States, people call the place where you store milk the refrigerator or just the fridge. Ice cream is stored in the freezer, which is much colder than the fridge. (You would not want to store milk in the freezer, because it would freeze solid!) This seems to be quite standard terminology. Perhaps the girl was not a native English speaker and was not familiar with the proper words for "refrigerator" and "freezer"; or (more likely) she said "fridge" but you heard "freeze."


text:
Q: How to Add a Tooltip for a Button inside Datatabels Created by Yajra Addons on Laravel How Can I Add a Tooltip for a Button inside the Datatables Created automatically by Yajra Addons inside Laravel?
the following code is for html function inside the Datatable file
public function html()
{
    return $this->builder()
                ->columns($this->getColumns())
                ->minifiedAjax()
                ->addAction(['width' => '80px'])
                ->parameters([
                    'dom'=>'Blfrtip',
                    'lengthMenu'=>[[10,25,50,100,-1],[10,25,50,'All Records']],
                     'buttons'=>[
                         ['extend'=>'print','className'=>'btn btn-primary','text'=>''],
                         ['extend'=>'csv','className'=>'btn btn-primary','text'=>''],
                     ],
        ]);
}


text:
Q: Custom push notification sound( .wav ) file is not playing in ios7
aps ={ alert = "push message"; badge = 1; id = 557; sound =
  "seller.wav"; type = 107; };

Though i have added "seller.wav" file in my bundle I could not able to play custom sound,when push comes.
Help me to get this solve.
Thanks in advance.

A: Check 'Preparing custom alert sounds' in the documentation:
https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/IPhoneOSClientImp.html
You file might not be the right format. Apple recommends the CAF file format. You can convert a wav file to CAF using afconvert like this:
afconvert /System/Library/Sounds/Submarine.aiff ~/Desktop/sub.caf -d ima4 -f caff -v
(Also from Apple doc)


text:
Q: How can I run multiple instances of bitlbee on OS X? I've been using bitlbee on OS X for a while now, but I've hit a roadblock when trying to use it the way I'd like to.
I have a .plist file created which launches bitlbee at boot, and thats working fine. I then use irssi to connect, and use my work jabber, as well as GTalk and Facebook chat.
Ideally, I'd like to use 2 instances of bitlbee, with 2 instances of irssi – thus keeping my personal comms seperate from business related ones.
I can't quite figure out (via launchctl and .plist files) how to get two instances of bitlbee running at boot, listening on different ports (6667 and 6668 for simplicity). Once that is working, it's a simple matter of having irssi connect to localhost:port and all is well.
Thoughts or ideas? Configs can be provided if needed.

A: You could do it with a single instance of Bitlbee.  Just use a different login from the second irssi.
If you actually want a second instance of Bitlbee, make a second config file and have it listen on a different port.  Then run the second Bitlbee using the second config file (use the "-c /path/to/second.conf" in the startup script).  Then use the second instance of irssi to connect to the second Bitlbee.
http://linux.die.net/man/8/bitlbee and http://en.linuxreviews.org/Bitlbee should help with the needed syntax.


text:
Q: How do I capture a matrix from a user input and print it out as the user input it? I'm messing around with numpy trying to create a 3x3 matrix. I want to capture the matrix input via user input and then print the matrix out as the user entered it.
Here's what I have now, it throws a
ValueError: invalid literal for int() with base 10:

when I run it and I have no idea why. I'm not entering the letter "a" anywhere, only numbers.
def matrix():
    row = int(3)
    column = int(3)
    matrix_input = []
    print("Enter the entries in a single line (separated by space): ")
    for i in range(row):  # A for loop for row entries
        entries = []
        for j in range(column):  # A for loop for column entries
            entries.append(int(input()))
        matrix_input.append(entries)

    # matrix_input = np.array(entries).reshape(row, column)
    print(matrix_input)

The goal is to get the user to input 3 numbers on three separate lines.
Example:
130
304
603

The program would then type this back out exactly as the user entered it and in the same format.
130
304
603

Any guidance would be much appreciated. Thanks

A: Right now, your code asks for each element seperately. If you enter numbers until it ends itself like
111
222
333
444
555
666
777
888
999

the program will return
[[111, 222, 333], [444, 555, 666], [777, 888, 999]]

This happens because the input() is inside the inner most loop, and is consequently called 9 times.
So if you want to enter the values separated by space as indicated, you could use list comprehension to convert this to a list of numbers:
row = int(3)
matrix_input = []
print("Enter the entries in a single line (separated by space): ")
for i in range(row):  # A for loop for row entries
    matrix_input.append([int(k) for k in input().split(' ')])

for out in matrix_input:
    print('{0} {1} {2}'.format(*out))

This will ask for three entries, which are split along the spaces and converted to integer. If you want floats, you could use float(k) instead of int(k).
The print command uses unpacking and the fact that the for ... in returns the rows.
Alternatively, you could use ' '.join(), which is more flexible:
for out in matrix_input:
    print(' '.join([str(el) for el in out]))

This is in fact the inverse operation of the construction of the matrix.

A: def matrix():
    row = int(3)
    column = int(3)
    matrix_input = []
    print("Enter the entries in a single line (separated by space): ")

    for i in range(row):  # A for loop for row entries
        ints =input()

        entries = []

        for a in ints:
          entries.append(int(a))
        matrix_input.append(entries)

    for ele in matrix_input:
      for d in ele:
        print(d,end='')
      print('')

matrix()

Input:
Enter the entries in a single line (separated by space):
130
304
603

Output:
130
304
603

A: The problem is that you're trying to convert an entire string (the input with spaces between each int) to an integer.
Instead you need to split out the input. See below:
def matrix():
    row = int(3)
    column = int(3)
    matrix_input = []
    print("Enter the entries in a single line (separated by space): ")

    input_str = input()

    entries = []
    entries.extend([int(x) for x in input_str.split(' ')])

    for item in entries:
        print(item)

A: This does the trick.
def matrix():
    row = int(3)
    column = int(3)
    matrix_input = []
    print("Enter the entries in a single line (separated by space): ")
    for i in range(row):  # A for loop for row entries
        # ints = input().split()
        while True:
            ints = input().split()
            if len(ints) == 3:
                break
            print("Invalid Input Received")
            print("Enter the entries in a single line (separated by space): ")
        entries = []
        for a in ints:
            entries.append(int(a))
        matrix_input.append(entries)
    print("Output")
    for ele in matrix_input:
        for d in ele:
            print(d, end=' ')
        print('')