问:
How to abstract from data type parameters in class instances?
As a toy project, I would like to understand how to model mathematical groups in Haskell in general.

To start us off, we begin by observing that a to be defined Group is just a Monoid with inversion.

```<code>class (Monoid m) => Group m where
    minvert :: m -> m
</code>```

Next, we first restrict ourselves to cyclic groups and start by defining the cyclic group of order 12.

```<code>data Cyclic12 = Cyclic12 Int deriving (Show, Eq)
</code>```

Finally, we instantiate both classes for Cyclic12.

```<code>instance Monoid Cyclic12 where
    mempty = Cyclic12 0
    mappend (Cyclic12 x) (Cyclic12 y) = Cyclic12 ((x + y) `mod` 12)

instance Group Cyclic12 where
    minvert (Cyclic12 x) = Cyclic12 ((0 - x) `mod` 12)
</code>```

How do I abstract the previous definition from the specific value of 12 to allow a more generic definition of different cyclic groups?

Ideally, I would like to write definitions like

```<code>instance Monoid (Cyclic k) where
    mempty = Cyclic k 0
    mappend (Cyclic k x) (Cyclic k y) = Cyclic k ((x + y) `mod` k)

instance Group (Cyclic k) where
    minvert (Cyclic k x) = Cyclic k ((0 - x) `mod` k)
</code>```

But with a data definition like

```<code>data Cyclic = Cyclic Int Int deriving (Show, Eq)
</code>```

we still don't get very far, because k is "not in scope". Regarding its apparent triviality I have a feeling to be missing out on some fundamental concept here. Thanks in advance for your help.

答:
You must make the order of the cyclic group part of the type. One way of doing this is to use the builtin type level natural numbers GHC gives us.

```<code>{-# LANGUAGE DataKinds, KindSignatures, ScopedTypeVariables #-}

import GHC.TypeLits
import Data.Proxy (Proxy(..))

data Cyclic (n :: Nat) = Cyclic Integer deriving (Show, Eq)
</code>```

Which lets us make the two instances pretty easily:

```<code>instance KnownNat n => Monoid (Cyclic n) where
    mempty = Cyclic 0
    Cyclic x `mappend` Cyclic y = Cyclic $ (x + y) `mod` natVal (Proxy :: Proxy n)

instance KnownNat n => Group (Cyclic n) where
    minvert (Cyclic x) = Cyclic $ negate x `mod` natVal (Proxy :: Proxy n)
</code>```

The KnownNat part of the signature basically says that whatever n :: Nat ends up being, it is something whose value we should be able to extract using natVal.

Then, once loaded in GHCi:

```<code>ghci> :set -XDataKinds
ghci> type Z12 = Cyclic 12
ghci> mappend (Cyclic 8 :: Z12) (Cyclic 7 :: Z12)
Cyclic 3
ghci> minvert (Cyclic 4 :: Z12)
Cyclic 8
</code>```

Aside on extensions

DataKinds lets us have a type parameter n which isn't a type. We say that its kind is not type (*). In this case, n has kind Nat (n :: Nat).

KindSignatures just lets us write n :: Nat where :: means "has kind" (instead of "has type") when it makes sense.

ScopedTypeVariables makes it so that the n type variable in Proxy :: Proxy n is the same one as in the instance head instance KnownNat m => Monoid (Cyclic n) where.

Body:
As a toy project, I would like to understand how to model mathematical groups in Haskell in general.

To start us off, we begin by observing that a to be defined Group is just a Monoid with inversion.

class (Monoid m) => Group m where
    minvert :: m -> m

Next, we first restrict ourselves to cyclic groups and start by defining the cyclic group of order 12.

data Cyclic12 = Cyclic12 Int deriving (Show, Eq)

Finally, we instantiate both classes for Cyclic12.

instance Monoid Cyclic12 where
    mempty = Cyclic12 0
    mappend (Cyclic12 x) (Cyclic12 y) = Cyclic12 ((x + y) `mod` 12)

instance Group Cyclic12 where
    minvert (Cyclic12 x) = Cyclic12 ((0 - x) `mod` 12)

How do I abstract the previous definition from the specific value of 12 to allow a more generic definition of different cyclic groups?

Ideally, I would like to write definitions like

instance Monoid (Cyclic k) where
    mempty = Cyclic k 0
    mappend (Cyclic k x) (Cyclic k y) = Cyclic k ((x + y) `mod` k)

instance Group (Cyclic k) where
    minvert (Cyclic k x) = Cyclic k ((0 - x) `mod` k)

But with a data definition like

data Cyclic = Cyclic Int Int deriving (Show, Eq)

we still don't get very far, because k is "not in scope". Regarding its apparent triviality I have a feeling to be missing out on some fundamental concept here. Thanks in advance for your help.

Body:
You must make the order of the cyclic group part of the type. One way of doing this is to use the builtin type level natural numbers GHC gives us.

{-# LANGUAGE DataKinds, KindSignatures, ScopedTypeVariables #-}

import GHC.TypeLits
import Data.Proxy (Proxy(..))

data Cyclic (n :: Nat) = Cyclic Integer deriving (Show, Eq)

Which lets us make the two instances pretty easily:

instance KnownNat n => Monoid (Cyclic n) where
    mempty = Cyclic 0
    Cyclic x `mappend` Cyclic y = Cyclic $ (x + y) `mod` natVal (Proxy :: Proxy n)

instance KnownNat n => Group (Cyclic n) where
    minvert (Cyclic x) = Cyclic $ negate x `mod` natVal (Proxy :: Proxy n)

The KnownNat part of the signature basically says that whatever n :: Nat ends up being, it is something whose value we should be able to extract using natVal.

Then, once loaded in GHCi:

ghci> :set -XDataKinds
ghci> type Z12 = Cyclic 12
ghci> mappend (Cyclic 8 :: Z12) (Cyclic 7 :: Z12)
Cyclic 3
ghci> minvert (Cyclic 4 :: Z12)
Cyclic 8

Aside on extensions

DataKinds lets us have a type parameter n which isn't a type. We say that its kind is not type (*). In this case, n has kind Nat (n :: Nat).

KindSignatures just lets us write n :: Nat where :: means "has kind" (instead of "has type") when it makes sense.

ScopedTypeVariables makes it so that the n type variable in Proxy :: Proxy n is the same one as in the instance head instance KnownNat m => Monoid (Cyclic n) where.


来源: stackexchange

问:
Dygraphs - add vertical line
I am using dygraph to chart temperature readings over a period of time.
I am looking to add 2 lines to the y-axis that represent high/low thresholds.

This is currently being achieved through the use of 2 additional constant data series but I suspect there is a better way.

An underlayCallback appears to be the better option, but I am not clear on how to use the canvas.fillRect and g.toComCoords properties to draw the lines.

Currently working through the sample below (http://dygraphs.com/tests/highlighted-region.html) which is rendering a vertical line.
Any assistance is appreciated.

```<code>var g = new Dygraph(
          document.getElementById("div_g"),
          data,
          {
            labels: ['X', 'Est.', 'Actual'],
            animatedZooms: true,
            underlayCallback: function(canvas, area, g) {
              var bottom_left = g.toDomCoords(300, -20);
              var top_right = g.toDomCoords(301, +20);

          var left = bottom_left[1];
          var right = top_right[0];

          canvas.fillStyle = "rgba(255, 0, 0, 1)";
          canvas.fillRect(right, area.y, 1, area.h);
        }

      }
  );
</code>```

For anyone that is interested, used the following to achieve the desired result:

```<code>underlayCallback: function(canvas, area, g) {
          var LowCoords = g.toDomCoords(0, 2.25);
          var HighCoords = g.toDomCoords(0, 4);

          var high = HighCoords[1];
          var low = LowCoords[1];

          canvas.fillStyle = 'red';
          canvas.fillRect(area.x, low, area.w, 2);
          canvas.fillStyle = 'blue';
          canvas.fillRect(area.x, high, area.w, 2);
          }
</code>```

答:
Alt. solution: I wanted dashed lines; so did this:

underlayCallback: function(ctx, area, g) {

    var LowCoords = g.toDomCoords(0, 2.25);
    var HighCoords = g.toDomCoords(0, 4);

    var high = HighCoords[1];
    var low = LowCoords[1];
    ctx.beginPath();

    ctx.setLineDash([5,15]);
    ctx.moveTo(0, low);
    ctx.lineTo(10000, low);
    ctx.strokeStyle = 'red';
    ctx.stroke();
    ctx.moveTo(0, high);
    ctx.lineTo(10000, high);
    ctx.strokeStyle = 'red';
    ctx.stroke();
    ctx.setLineDash([]);

}
```

ContentLicense: CC BY-SA 4.0

Title: Dygraphs - add vertical line

Body:
I am using dygraph to chart temperature readings over a period of time.
I am looking to add 2 lines to the y-axis that represent high/low thresholds.

This is currently being achieved through the use of 2 additional constant data series but I suspect there is a better way.

An underlayCallback appears to be the better option, but I am not clear on how to use the canvas.fillRect and g.toComCoords properties to draw the lines.

Currently working through the sample below (http://dygraphs.com/tests/highlighted-region.html) which is rendering a vertical line.
Any assistance is appreciated.

var g = new Dygraph(
          document.getElementById("div_g"),
          data,
          {
            labels: ['X', 'Est.', 'Actual'],
            animatedZooms: true,
            underlayCallback: function(canvas, area, g) {
              var bottom_left = g.toDomCoords(300, -20);
              var top_right = g.toDomCoords(301, +20);

          var left = bottom_left[1];
          var right = top_right[0];

          canvas.fillStyle = "rgba(255, 0, 0, 1)";
          canvas.fillRect(right, area.y, 1, area.h);
        }

      }
  );

For anyone that is interested, used the following to achieve the desired result:

underlayCallback: function(canvas, area, g) {
          var LowCoords = g.toDomCoords(0, 2.25);
          var HighCoords = g.toDomCoords(0, 4);

          var high = HighCoords[1];
          var low = LowCoords[1];

          canvas.fillStyle = 'red';
          canvas.fillRect(area.x, low, area.w, 2);
          canvas.fillStyle = 'blue';
          canvas.fillRect(area.x, high, area.w, 2);
          }


问:
How to reuse Ammonite REPL's sc files in a sbt project?
I have some reusable Ammonite REPL's sc files that were used in some Jupyter Scala notebooks.

Now I am creating a standalone application built from sbt. I hope I can reuse these existing sc files in the sbt project.

Is it possible to share these sc files for both Jupyter Scala/Ammonite REPL and sbt projects? How to make scala sources and sc files compile together?

答:
I created Import.scala, a Scala compiler plugin that enables magic imports.

With the help of Import.scala, code snippets in a .sc file can be loaded into Scala source file in a sbt project with the same syntax as Ammonite or Jupyter Scala:

Given a MyScript.sc file.

```<code>// MyScript.sc
val elite = 31337
</code>```

Magic import it in another file.

```<code>import $file.MyScript
</code>```

It works.

```<code>assert(MyScript.elite == 31337)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I created Import.scala, a Scala compiler plugin that enables magic imports.

With the help of Import.scala, code snippets in a .sc file can be loaded into Scala source file in a sbt project with the same syntax as Ammonite or Jupyter Scala:

Given a MyScript.sc file.

// MyScript.sc
val elite = 31337

Magic import it in another file.

import $file.MyScript

It works.

assert(MyScript.elite == 31337)


问:
PHP Ajax GET method does not fire
I have problem passing 2 parameters using php/ajax/mysql.

Not able to trace out the problem

Here is Ajax code

```<code><script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#myonoffswitch').click(function(){
var myonoffswitch=$('#myonoffswitch').val();
if ($("#myonoffswitch:checked").length == 0)
{
var a=myonoffswitch;
}
else
{
var a="off";
}

$.ajax({
type: "POST",
url: "process.php",
data: "ps="+a ,
success: function(html){
$("#display").html(html).show();
}
});

});
});
</script>

<script type="text/javascript">
$(document).ready( function(){
$(".cb-enable").click(function(){
var parent = $(this).parents('.switch');
$('.cb-disable',parent).removeClass('selected');
$(this).addClass('selected');
$('.checkbox',parent).attr('checked', true);
});
$(".cb-disable").click(function(){
var parent = $(this).parents('.switch');
$('.cb-enable',parent).removeClass('selected');
$(this).addClass('selected');
$('.checkbox',parent).attr('checked', false);
});
});
</script>
</code>```

PHP :

```<code>$k=1;
while($row = mysqli_fetch_array($result)) {
$id = $row['ID'];
$ps = $row['Status'];

    echo "<div class=\"onoffswitch\">\n";
        echo "<input type=\"checkbox\" name=\"$k\" class=\"onoffswitch-checkbox\" id=\"$k\"\n";
        if($ps=="1") {
            echo "checked ";
        }
        echo ">";
        echo "<label class=\"onoffswitch-label\" for=\"$k\">\n";
        echo "  <div class=\"onoffswitch-inner\"></div>\n";
        echo "  <div class=\"onoffswitch-switch\"></div>\n";
        echo "</label>\n";
    echo "</div>\n";
    $k++;
}
</code>```

process .php is similar to below :

$ps=$_POS['ps'];
$id=$_POS['id'];

//mysql_query("UPDATE Tbl set Status='$ps' where ID=$id"); // does not work

mysql_query("UPDATE Tbl set Status='$ps' where ID=1");

code updated and working when passing only 1 argument/parameter.

POST or GET method will be ok. Any help please ?

答: Do not, I repeat, DO NOT, use the mysql_* interface. Switch to mysqli or PDO.  It is deprecated and gone in the latest PHP release.  And especially do not mix them!  It won't work!

Title: PHP Ajax GET method does not fire

Body:
I have problem passing 2 parameters using php/ajax/mysql.

Not able to trace out the problem

Here is Ajax code

PHP :

$k=1;
while($row = mysqli_fetch_array($result)) {
$id = $row['ID'];
$ps = $row['Status'];

    echo "
\n";
        echo "<input type=\"checkbox\" name=\"$k\" class=\"onoffswitch-checkbox\" id=\"$k\"\n";
        if($ps=="1") {
            echo "checked ";
        }
        echo ">";
        echo "\n";
        echo "

\n";
        echo "

\n";
        echo "\n";
    echo "
\n";
    $k++;
}

process .php is similar to below :

$ps=$_POS['ps'];
$id=$_POS['id'];

//mysql_query("UPDATE Tbl set Status='$ps' where ID=$id"); // does not work

mysql_query("UPDATE Tbl set Status='$ps' where ID=1");

code updated and working when passing only 1 argument/parameter.

POST or GET method will be ok. Any help please ?


问:
Is this javascript hack sufficient to mask a mailto link from bots?

// contact link -- no peeking!
  $('.footer a.peek').click(function(){
    $(this).attr('href', atob('bWFpbHRvOmRvbnRzdGVhbEBtZS5jb20='));
  });
  $('.footer a.peek').focusout(function(){
    $(this).attr('href', '#');
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="footer">
  Contact Me
</div></code>```

答:
That will probably mask the link from most bots, yes.

It will also mask the link from touchscreen devices (like smartphones) -- with no mouse cursor, they will never fire mouseenter events. This is probably undesirable. Consider other methods.

Body:
// contact link -- no peeking!
  $('.footer a.peek').click(function(){
    $(this).attr('href', atob('bWFpbHRvOmRvbnRzdGVhbEBtZS5jb20='));
  });
  $('.footer a.peek').focusout(function(){
    $(this).attr('href', '#');
  });

  Contact Me


问:
Laravel 5.2 - Send welcome email after user registered
I would like to send some emails after users registered.
But, it doest work. I didn't receive an email in my SMTP mail. I'm using mailtrap.io.

I have set up a Registered event with a listener to NewUserRegistered.

Within my NewUserRegistered Controller\Auth\AuthController as follows:

```<code>    <?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Log;
use Validator;
use Mail;

class AuthController extends Controller {
    /*
            |--------------------------------------------------------------------------
            | Registration & Login Controller
            |--------------------------------------------------------------------------
            |
            | This controller handles the registration of new users, as well as the
            | authentication of existing users. By default, this controller uses
            | a simple trait to add these behaviors. Why don't you explore it?
            |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

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

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct() {
        $this->middleware($this->guestMiddleware(), [
            'except' => 'logout'
        ]);

        }

    /**
     * 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|max:255',
            'matric' => 'required|max:5',
            'faculty' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'address' => 'required',
            'phone' => 'required',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data) {

        return User::create([
            'name' => $data['name'],
            'matric' => $data['matric'],
            'faculty' => $data['faculty'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'address' => $data['address'],
            'phone' => $data['phone'],
        ]);

        event(new Registered($user));

    //sreturn User;
    }
}
</code>```

Within my Registered Events as follows:

```<code>    <?php

namespace App\Events;

use App\Events\Registered;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class Registered extends Event
{
    use SerializesModels;
    /**
     * @var
     */
    public $user;

    /**
     * Create a new event instance.
     *
     * @param $user
     */
    public function __construct($user)
    {
        //
        $this->user = $user;
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return [];
    }
}
</code>```

Within my NewUserRegistered Listeners as follows:

```<code>    <?php

    namespace App\Listeners;

    use App\Events\Registered;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Mailer;
    use Mail;

    class NewUserRegistered
    {
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    /**
     * Handle the event.
     *
     * @param  Registered  $event
     * @return void
     */
    public function welcome(Registered $event)
  {
     $data = [
       'user' => $event->user,
          'from' => 'hello@test.dev',
          'subject' => 'Welcome to test'
    ];

        $this->mailer->send('emails.auth.verify', $data, function($message) {
            $message->to($data['user']->email, $data['user']->matric)
                    ->subject($data['subject']);
        });
    }
}
</code>```

答:
A couple potential issues with your solution could be:

In Controller\Auth\AuthController, you haven't imported the Registered event into the namespace. Try adding use App\Events\Registered; to the top.

In NewUserRegistered, you've defined a #welcome method, but Laravel event listeners expect a #handle method. See the Laravel docs on Events for more information.

Beyond that, you could be experiencing issues with your Mailtrap credentials.

Body:
I would like to send some emails after users registered.
But, it doest work. I didn't receive an email in my SMTP mail. I'm using mailtrap.io.

I have set up a Registered event with a listener to NewUserRegistered.

Within my NewUserRegistered Controller\Auth\AuthController as follows:

    <?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Log;
use Validator;
use Mail;

class AuthController extends Controller {
    /*
            |--------------------------------------------------------------------------
            | Registration & Login Controller
            |--------------------------------------------------------------------------
            |
            | This controller handles the registration of new users, as well as the
            | authentication of existing users. By default, this controller uses
            | a simple trait to add these behaviors. Why don't you explore it?
            |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

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

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct() {
        $this->middleware($this->guestMiddleware(), [
            'except' => 'logout'
        ]);

        }

    /**
     * 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|max:255',
            'matric' => 'required|max:5',
            'faculty' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'address' => 'required',
            'phone' => 'required',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data) {

        return User::create([
            'name' => $data['name'],
            'matric' => $data['matric'],
            'faculty' => $data['faculty'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'address' => $data['address'],
            'phone' => $data['phone'],
        ]);

        event(new Registered($user));

    //sreturn User;
    }
}

Within my Registered Events as follows:

    <?php

namespace App\Events;

use App\Events\Registered;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class Registered extends Event
{
    use SerializesModels;
    /**
     * @var
     */
    public $user;

    /**
     * Create a new event instance.
     *
     * @param $user
     */
    public function __construct($user)
    {
        //
        $this->user = $user;
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return [];
    }
}

Within my NewUserRegistered Listeners as follows:

    <?php

    namespace App\Listeners;

    use App\Events\Registered;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Mailer;
    use Mail;

    class NewUserRegistered
    {
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    /**
     * Handle the event.
     *
     * @param  Registered  $event
     * @return void
     */
    public function welcome(Registered $event)
  {
     $data = [
       'user' => $event->user,
          'from' => 'hello@test.dev',
          'subject' => 'Welcome to test'
    ];

        $this->mailer->send('emails.auth.verify', $data, function($message) {
            $message->to($data['user']->email, $data['user']->matric)
                    ->subject($data['subject']);
        });
    }
}


问:
Reduce PythonRDD of lists into one list
Going to keep this short post, but happy to add more context / details if they are necessary. I have a PythonRDD that looks as follows:

```<code>print(myRDD)
PythonRDD[4] at RDD at PythonRDD.scala:43

print(myRDD.take(1))
[[0.305, 0.302, -0.005, 0.302]]

print(myRDD.collect())
[[0.305, 0.302, -0.005, 0.302],
 [0.294, 0.183, 0.084, 0.277],
 [0.184, 0.997, -1.123, 0.654]]
</code>```

Each of the 3 lists contains the 4 values for a 2x2 matrix. I would like to add these 3 matrices together, hence I would like to use some reduce function on myRDD such that the output is:

[[.783, 1.482, -1.044, 1.233]]
```

<p>Where .783 = .305 + .294 + .184, etc. I tried to do:</p>

```myRDD.reduce(lambda a, b: a + b)
```

However this did not give me what I desired. Any help appreciated! Thanks!

Title: Reduce PythonRDD of lists into one list

Body:
Going to keep this short post, but happy to add more context / details if they are necessary. I have a PythonRDD that looks as follows:

print(myRDD)
PythonRDD[4] at RDD at PythonRDD.scala:43

print(myRDD.take(1))
[[0.305, 0.302, -0.005, 0.302]]

print(myRDD.collect())
[[0.305, 0.302, -0.005, 0.302],
 [0.294, 0.183, 0.084, 0.277],
 [0.184, 0.997, -1.123, 0.654]]

Each of the 3 lists contains the 4 values for a 2x2 matrix. I would like to add these 3 matrices together, hence I would like to use some reduce function on myRDD such that the output is:

[[.783, 1.482, -1.044, 1.233]]

Where .783 = .305 + .294 + .184, etc. I tried to do:

myRDD.reduce(lambda a, b: a + b)

However this did not give me what I desired. Any help appreciated! Thanks!

Body:
sc = SparkContext(appName='MyApp')
data = \
    [[0.305, 0.302, -0.005, 0.302],
     [0.294, 0.183, 0.084, 0.277],
     [0.184, 0.997, -1.123, 0.654]]

res = sc.parallelize(data).reduce(lambda x, y: map(sum, zip(x, y)))


问:
Why doesn't dialyzer detect this bad type?
Dialyzer behaves rather strangely to me in this case, and I haven't found anything to better understand it.

This is not an error:

```<code>defmodule Blog.UserResolver do
  @type one_user :: ( {:error, String.t} )

  @spec find(%{id: String.t}, any()) :: one_user

  def find(%{id: id}, _info) do
    age = :rand.uniform(99)
    if (age < 100) do
      # This doesn't trigger a type error, even though it's wrong
      {:ok, %{email: "dw@1g.io", name: "Deedub"}}
    else
    {:error, "Age isn't in the right range"}
    end
  end
end
</code>```

Note that one of the possible return branches definitely does not match with the type signature.

This however does have an error:

```<code>defmodule Blog.UserResolver do
  @type one_user :: ( {:error, String.t} )

  @spec find(%{id: String.t}, any()) :: one_user

  # Throws an error since no return path matches the type spec
  def find(%{id: id}, _info) do
    age = :rand.uniform(99)
    if (age < 100) do
      {:ok, %{email: "dw@1g.io", name: "Deedub"}}
    else
     10
    end
  end
end
</code>```

In this case, none of the possible branches match the typespec, and dialyzer says has this error message:

web/blog/user_resolver.ex:4: Invalid type specification for function 'Elixir.Blog.UserResolver':find/2. The success typing is (#{'id':=_, _=>_},_) -> 10 | {'ok',#{'email':=<<_:64>>, 'name':=<<_:48>>}}

The part I don't understand is that dialyzer clearly recognizes the two different types the branches may return ((#{'id':=_, _=>_},_) -> 10 | {'ok',#{'email':=<<_:64>>, 'name':=<<_:48>>}), so it's not a problem of inference. So why then does it not recognize that one of the branches does not conform to the type spec (it seems to be happy if just one of the branches conforms, which is not what I want at all)

答:
From the LearnYou link that Dogbert provided, dialyzer will:

only complain on type errors that would guarantee a crash.

In your first example, if age is always greater than or equal to 100, your function will return the declared type. In the second example, there is no way for your function to return the declared type.

dialyzer creates a set of constraint equations. If there is any solution to those equations, then dialyzer won't complain. Erlang was created as a dynamically typed language. dialyzer is just a program someone wrote after the fact.  For reasons I'm sure they pondered over and discussed and theorized about, the designers of dialyzer chose that functionality.

I'm looking for a more rigorous type checker if possible.

Not possible so far:

The Erlang Type System

The reason for not having a more elaborate type system is that none of
  the Erlang inventors knew how to write one, so it never got done. The
  advantage of a static type system is that errors can be predicted at
  compile time rather than at runtime, therefore allowing faults to be
  detected earlier and fixed at a lower cost. A number of people have
  tried to build a static type system for Erlang. Unfortunately, due to
  design decisions taken when Erlang was invented, no project has been
  able to write a comprehensive type system, since with hot code
  loading, this is intrinsically difficult. To quote Joe Armstrong in
  one of the many type system flame wars, "It seems like it should be
  'easy'—and indeed, a few weeks programming can make a type system that
  handles 95% of the language. Several man-years of work [by some of the
  brightest minds in computer science] have gone into trying to fix up
  the other 5%—but this is really difficult."

From "Erlang Programming (Francesco Cesarini & Simon Thompson)".

A test suite is required to keep dynamically typed programs under control.   Elixir is just a Rubified version of Erlang.  Ruby is also a dynamically typed language--but it has no dialyzer.  The only thing Ruby has is testing.  You use test suites to keep the Wild West of computer programming languages under control--not a compiler.  If you require a statically typed language, then a Rubified version of Erlang wasn't a great choice--see Haskell.

Body:
Dialyzer behaves rather strangely to me in this case, and I haven't found anything to better understand it.

This is not an error:

defmodule Blog.UserResolver do
  @type one_user :: ( {:error, String.t} )

  @spec find(%{id: String.t}, any()) :: one_user

  def find(%{id: id}, _info) do
    age = :rand.uniform(99)
    if (age < 100) do
      # This doesn't trigger a type error, even though it's wrong
      {:ok, %{email: "dw@1g.io", name: "Deedub"}}
    else
    {:error, "Age isn't in the right range"}
    end
  end
end

Note that one of the possible return branches definitely does not match with the type signature.

This however does have an error:

defmodule Blog.UserResolver do
  @type one_user :: ( {:error, String.t} )

  @spec find(%{id: String.t}, any()) :: one_user

  # Throws an error since no return path matches the type spec
  def find(%{id: id}, _info) do
    age = :rand.uniform(99)
    if (age < 100) do
      {:ok, %{email: "dw@1g.io", name: "Deedub"}}
    else
     10
    end
  end
end

In this case, none of the possible branches match the typespec, and dialyzer says has this error message:

web/blog/user_resolver.ex:4: Invalid type specification for function 'Elixir.Blog.UserResolver':find/2. The success typing is (#{'id':=_, _=>_},_) -> 10 | {'ok',#{'email':=<<_:64>>, 'name':=<<_:48>>}}

The part I don't understand is that dialyzer clearly recognizes the two different types the branches may return ((#{'id':=_, _=>_},_) -> 10 | {'ok',#{'email':=<<_:64>>, 'name':=<<_:48>>}), so it's not a problem of inference. So why then does it not recognize that one of the branches does not conform to the type spec (it seems to be happy if just one of the branches conforms, which is not what I want at all)


问:
InvocationTargetException and NoSuchMethodError in android
I get an java.lang.NoSuchMethodError when I use the putFile method of a StorageReference object in Android.

I have the required dependencies in the app level gradle file ('com.google.firebase:firebase-storage:10.0.1' and 'com.google.firebase:firebase-database:10.0.1').

Here is the Error message:

```<code>06-05 02:28:29.530 15493-15493/packagename A/FirebaseApp: Firebase API initialization failure.
                                                                        java.lang.reflect.InvocationTargetException
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.google.firebase.FirebaseApp.zza(Unknown Source)
                                                                            at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                            at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                            at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                            at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                                                                            at android.content.ContentProvider.attachInfo(ContentProvider.java:1737)
                                                                            at android.content.ContentProvider.attachInfo(ContentProvider.java:1712)
                                                                            at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                                                                            at android.app.ActivityThread.installProvider(ActivityThread.java:6475)
                                                                            at android.app.ActivityThread.installContentProviders(ActivityThread.java:6070)
                                                                            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6010)
                                                                            at android.app.ActivityThread.access$1700(ActivityThread.java:218)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:145)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6934)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
                                                                         Caused by: java.lang.NoSuchMethodError: No static method getNoBackupFilesDir(Landroid/content/Context;)Ljava/io/File; in class Lcom/google/android/gms/common/util/zzw; or its super classes (declaration of 'com.google.android.gms.common.util.zzw' appears in /data/app/packagename-2/split_lib_dependencies_apk.apk:classes19.dex)
                                                                            at com.google.firebase.iid.zzh.zzeK(Unknown Source)
                                                                            at com.google.firebase.iid.zzh.<init>(Unknown Source)
                                                                            at com.google.firebase.iid.zzh.<init>(Unknown Source)
                                                                            at com.google.firebase.iid.zzd.zzb(Unknown Source)
                                                                            at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.google.firebase.FirebaseApp.zza(Unknown Source)
                                                                            at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                            at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                            at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                            at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                                                                            at android.content.ContentProvider.attachInfo(ContentProvider.java:1737)
                                                                            at android.content.ContentProvider.attachInfo(ContentProvider.java:1712)
                                                                            at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                                                                            at android.app.ActivityThread.installProvider(ActivityThread.java:6475)
                                                                            at android.app.ActivityThread.installContentProviders(ActivityThread.java:6070)
                                                                            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6010)
                                                                            at android.app.ActivityThread.access$1700(ActivityThread.java:218)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:145)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6934)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
</code>```

And sometimes I get this Error message:

```<code>06-05 02:42:13.403 15493-15493/packagename E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: packagename, PID: 15493
                                                                           java.lang.NoSuchMethodError: No static method zzyv()Lcom/google/android/gms/common/util/zze; in class Lcom/google/android/gms/common/util/zzh; or its super classes (declaration of 'com.google.android.gms.common.util.zzh' appears in /data/app/packagename-2/split_lib_dependencies_apk.apk:classes19.dex)
                                                                               at com.google.android.gms.internal.zzbqw.<clinit>(Unknown Source)
                                                                               at com.google.firebase.storage.UploadTask.<init>(Unknown Source)
                                                                               at com.google.firebase.storage.StorageReference.putFile(Unknown Source)
                                                                               at packagename.PostActivity$2.onClick(PostActivity.java:80)
                                                                               at android.view.View.performClick(View.java:5246)
                                                                               at android.widget.TextView.performClick(TextView.java:10620)
                                                                               at android.view.View$PerformClick.run(View.java:21256)
                                                                               at android.os.Handler.handleCallback(Handler.java:739)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:145)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6934)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
</code>```

The error happens here in the code (when I try to use putFile):

```<code>StorageReference filepath = mStorage.child("Pictures").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri);
</code>```

答:
After a lot of searching and testing, I found out that not all Firebase UI libraries are compatible with any Firebase libraries.

Here is the list and the solution to the problem:
https://github.com/firebase/FirebaseUI-Android#compatibility-with-firebase--google-play-services-libraries

Scroll down on the linked page and the answer is there.

Body:
I get an java.lang.NoSuchMethodError when I use the putFile method of a StorageReference object in Android.

I have the required dependencies in the app level gradle file ('com.google.firebase:firebase-storage:10.0.1' and 'com.google.firebase:firebase-database:10.0.1').

Here is the Error message:

06-05 02:28:29.530 15493-15493/packagename A/FirebaseApp: Firebase API initialization failure.
                                                                        java.lang.reflect.InvocationTargetException
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.google.firebase.FirebaseApp.zza(Unknown Source)
                                                                            at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                            at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                            at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                            at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                                                                            at android.content.ContentProvider.attachInfo(ContentProvider.java:1737)
                                                                            at android.content.ContentProvider.attachInfo(ContentProvider.java:1712)
                                                                            at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                                                                            at android.app.ActivityThread.installProvider(ActivityThread.java:6475)
                                                                            at android.app.ActivityThread.installContentProviders(ActivityThread.java:6070)
                                                                            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6010)
                                                                            at android.app.ActivityThread.access$1700(ActivityThread.java:218)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:145)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6934)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
                                                                         Caused by: java.lang.NoSuchMethodError: No static method getNoBackupFilesDir(Landroid/content/Context;)Ljava/io/File; in class Lcom/google/android/gms/common/util/zzw; or its super classes (declaration of 'com.google.android.gms.common.util.zzw' appears in /data/app/packagename-2/split_lib_dependencies_apk.apk:classes19.dex)
                                                                            at com.google.firebase.iid.zzh.zzeK(Unknown Source)
                                                                            at com.google.firebase.iid.zzh.<init>(Unknown Source)
                                                                            at com.google.firebase.iid.zzh.<init>(Unknown Source)
                                                                            at com.google.firebase.iid.zzd.zzb(Unknown Source)
                                                                            at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.google.firebase.FirebaseApp.zza(Unknown Source)
                                                                            at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                            at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                            at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                            at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                                                                            at android.content.ContentProvider.attachInfo(ContentProvider.java:1737)
                                                                            at android.content.ContentProvider.attachInfo(ContentProvider.java:1712)
                                                                            at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                                                                            at android.app.ActivityThread.installProvider(ActivityThread.java:6475)
                                                                            at android.app.ActivityThread.installContentProviders(ActivityThread.java:6070)
                                                                            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6010)
                                                                            at android.app.ActivityThread.access$1700(ActivityThread.java:218)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:145)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6934)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

And sometimes I get this Error message:

06-05 02:42:13.403 15493-15493/packagename E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: packagename, PID: 15493
                                                                           java.lang.NoSuchMethodError: No static method zzyv()Lcom/google/android/gms/common/util/zze; in class Lcom/google/android/gms/common/util/zzh; or its super classes (declaration of 'com.google.android.gms.common.util.zzh' appears in /data/app/packagename-2/split_lib_dependencies_apk.apk:classes19.dex)
                                                                               at com.google.android.gms.internal.zzbqw.<clinit>(Unknown Source)
                                                                               at com.google.firebase.storage.UploadTask.<init>(Unknown Source)
                                                                               at com.google.firebase.storage.StorageReference.putFile(Unknown Source)
                                                                               at packagename.PostActivity$2.onClick(PostActivity.java:80)
                                                                               at android.view.View.performClick(View.java:5246)
                                                                               at android.widget.TextView.performClick(TextView.java:10620)
                                                                               at android.view.View$PerformClick.run(View.java:21256)
                                                                               at android.os.Handler.handleCallback(Handler.java:739)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:145)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6934)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

The error happens here in the code (when I try to use putFile):

StorageReference filepath = mStorage.child("Pictures").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri);


问:
Python IPv6 Bytes To Address
I am running python on the iOS App Pythonista 3.
When I try to get an IPv6 address it ends up
returning bytes rather than a formatted address.
Right now I am trying to find a way to either get the address properly without bytes, or to find a way to make the bytes become the address.
Here is the code I ran to get the address:

```<code>def getIPv6Addr(input):
    return socket.getaddrinfo(input, None, socket.AF_INET6)
</code>```

and here was the output:

```<code>[(30, 2, 17, '', (30, '\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14')), (30, 1, 6, '', (30, '\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14'))]
</code>```

Edit: The alternative solution is to find what type of encoding is being used to turn this data into bytes.

```<code>What Makes:
2607:f8b0:4000:814::200e
become
\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14
</code>```

答:
there is a quick way if you use this package:</p>

```<code>from django.utils.encoding import smart_str

a = '\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14'

print(smart_str(a))
</code>```

Title: Python IPv6 Bytes To Address

Body:
I am running python on the iOS App Pythonista 3.
When I try to get an IPv6 address it ends up
returning bytes rather than a formatted address.
Right now I am trying to find a way to either get the address properly without bytes, or to find a way to make the bytes become the address.
Here is the code I ran to get the address:

def getIPv6Addr(input):
    return socket.getaddrinfo(input, None, socket.AF_INET6)

and here was the output:

[(30, 2, 17, '', (30, '\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14')), (30, 1, 6, '', (30, '\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14'))]

Edit: The alternative solution is to find what type of encoding is being used to turn this data into bytes.

What Makes:
2607:f8b0:4000:814::200e
become
\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14

Body:
there is a quick way if you use this package:

from django.utils.encoding import smart_str

a = '\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14'

print(smart_str(a))


问:
Google Cloud Launcher Wordpress Site Times Out After VM Resize
I have a wordpress site which I created using Google Cloud Launcher. From what I can tell, this process created a VM and installed debian 8 with apache, php, and wordpress.

My site was running fine and I set up a custom domain. Then, Google suggested my instance was not large enough and I needed to resize the VM. They have a one click resize which I pressed. This moved my site to a new VM.

Now that I have moved to the new VM, when I type my site's URL into the address bar I just get a timeout error.

How can I begin to figure out what is wrong?

I tried restarting apache.  I also tried fetching my site using curl localhost after sshing to my VM and that works. I imagine this has something to do w/ a firewall or ip but I'm not sure where to start checking.

答:
I tried to resize the machine type for my Windows server based on Google's recommendation, resizing was done successfully without changing the external IP address since my VM was using a static IP. Instance IP address changes if using an Ephemeral IP.

At this point, I would verify if DNS A record is pointing to my current instance IP address.

Important: When resizing the VM as per Google's suggestion; It doesn't move to a new VM instead stops the instance, modifies the machine type, and restarts the instance. Find more information here.


问:
HTTP Status 500 - Handler processing failed; nested exception is java.lang.StackOverflowError
I get the below exception after running my webportal for a while. I need to re login to eliminate this error. Because of this I am not able to run my development environment smoothly on eclipse.

This is my AuthenticationFilter.java

```<code>public class AuthenticationFilter implements Filter {
    private static final Logger log = Logger.getLogger(AuthenticationFilter.class) ;
    static Map<String, String> permissionsMapping = new HashMap<String, String>();
    private static int domainOrGroupParentId = 0;
    static {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest servletRequest = (HttpServletRequest) request;

        if (servletRequest.getRequestURI().contains("onLoadOfLoginPage")
                || servletRequest.getRequestURI().contains("Corporate")
                || servletRequest.getRequestURI().contains("mainDashboard")
                // ||
                // servletRequest.getRequestURI().contains("mainDashboardWithoutDomainOrGroupParent")
                || servletRequest.getRequestURI().contains("loginButtonPressedForSuperAdminView")
                // ||
                // servletRequest.getRequestURI().contains("loginButtonPressedForNonSuperAdmin")
                || servletRequest.getRequestURI().contains("resources")
                || servletRequest.getRequestURI().contains("session")
                || servletRequest.getRequestURI().contains("forgot_password")
                || servletRequest.getRequestURI().contains("resetPassword")) {
>>Line52>>      chain.doFilter(request, response);

        } else {
            HttpSession session = servletRequest.getSession(false);
            try {
                if (null == session || SessionDataManager.getInstance().getLoggedInWebAdminUser().getWebAdminUserPojo()
                        .getUsername() == null) {
                    RequestDispatcher dispatcher = request.getRequestDispatcher("onLoadOfLoginPage");
                    dispatcher.forward(request, response);
                    return;

                } else if (!servletRequest.getRequestURI().contains("get")) {

                    String username = (String) SessionDataManager.getInstance().getLoggedInWebAdminUser()
                            .getWebAdminUserPojo().getUsername();
                    String sessionID = session.getId();
                    domainOrGroupParentId = SessionDataManager.getInstance().getDomainIdFromRequest(servletRequest);
                    log.info("Attempting to maintain Session, with domainParent "+domainOrGroupParentId);
                    if (!WebAdminHelper.maintainSession(username, sessionID, domainOrGroupParentId)) {
                        RequestDispatcher dispatcher = request.getRequestDispatcher("onLoadOfLoginPage");
                        dispatcher.forward(request, response);
                        return;
                    }
                }
            } catch (Exception e) {

            }
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}
</code>```

Exception I get

```<code>type Exception report

message Handler processing failed; nested exception is java.lang.StackOverflowError

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.StackOverflowError
    org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1276)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:958)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    net.codejava.spring.AuthenticationFilter.doFilter(AuthenticationFilter.java:52)
root cause

java.lang.StackOverflowError
    com.google.gson.stream.JsonWriter.beforeName(JsonWriter.java:586)
    com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:401)
    com.google.gson.stream.JsonWriter.value(JsonWriter.java:417)
    com.google.gson.internal.bind.TypeAdapters$13.write(TypeAdapters.java:362)
    com.google.gson.internal.bind.TypeAdapters$13.write(TypeAdapters.java:346)
    com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
    com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
    com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
</code>```

EDIT
I have identified the root causing line.

response = new Gson().toJson(invException);

Type of

InvalidObjectStateException invException

```<code>public class InvalidObjectStateException extends Exception {
    private static final long serialVersionUID = -9086960433236073019L;
    private static final Logger log = Logger.getLogger(InvalidObjectStateException.class);
    private String customErrorMessage = null;
    private Object exceptionCausingObject = null;

    public InvalidObjectStateException(String errorMessage, Object exceptionCausingObject) {
        super(errorMessage);
        this.customErrorMessage = errorMessage;
        log.info("InvalidObjectStateException : exceptionCausingObject"
                + ((exceptionCausingObject != null) ? exceptionCausingObject.getClass().toString() : ""));
        this.exceptionCausingObject = exceptionCausingObject;
    }

    public String getCustomErrorMessage() {
        return customErrorMessage;
    }

    public void setCustomErrorMessage(String customErrorMessage) {
        this.customErrorMessage = customErrorMessage;
    }

    public Object getExceptionCausingObject() {
        return exceptionCausingObject;
    }

    public void setExceptionCausingObject(Object exceptionCausingObject) {
        this.exceptionCausingObject = exceptionCausingObject;
    }
}
</code>```

What am I doing wrong here ? Why cant Gson parse the Exception ?

答:
I think this is not the right source of exception.  net.codejava.spring.AuthenticationFilter.doFilter(AuthenticationFilter.java:52). It just failed at this location due to low memory.

There should be another process/request which is converting a response(maybe)/object to json string. Look in the response object it should have a nested infinite object reference.

Body:
I get the below exception after running my webportal for a while. I need to re login to eliminate this error. Because of this I am not able to run my development environment smoothly on eclipse.

This is my AuthenticationFilter.java

public class AuthenticationFilter implements Filter {
    private static final Logger log = Logger.getLogger(AuthenticationFilter.class) ;
    static Map<String, String> permissionsMapping = new HashMap<String, String>();
    private static int domainOrGroupParentId = 0;
    static {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest servletRequest = (HttpServletRequest) request;

        if (servletRequest.getRequestURI().contains("onLoadOfLoginPage")
                || servletRequest.getRequestURI().contains("Corporate")
                || servletRequest.getRequestURI().contains("mainDashboard")
                // ||
                // servletRequest.getRequestURI().contains("mainDashboardWithoutDomainOrGroupParent")
                || servletRequest.getRequestURI().contains("loginButtonPressedForSuperAdminView")
                // ||
                // servletRequest.getRequestURI().contains("loginButtonPressedForNonSuperAdmin")
                || servletRequest.getRequestURI().contains("resources")
                || servletRequest.getRequestURI().contains("session")
                || servletRequest.getRequestURI().contains("forgot_password")
                || servletRequest.getRequestURI().contains("resetPassword")) {
>>Line52>>      chain.doFilter(request, response);

        } else {
            HttpSession session = servletRequest.getSession(false);
            try {
                if (null == session || SessionDataManager.getInstance().getLoggedInWebAdminUser().getWebAdminUserPojo()
                        .getUsername() == null) {
                    RequestDispatcher dispatcher = request.getRequestDispatcher("onLoadOfLoginPage");
                    dispatcher.forward(request, response);
                    return;

                } else if (!servletRequest.getRequestURI().contains("get")) {

                    String username = (String) SessionDataManager.getInstance().getLoggedInWebAdminUser()
                            .getWebAdminUserPojo().getUsername();
                    String sessionID = session.getId();
                    domainOrGroupParentId = SessionDataManager.getInstance().getDomainIdFromRequest(servletRequest);
                    log.info("Attempting to maintain Session, with domainParent "+domainOrGroupParentId);
                    if (!WebAdminHelper.maintainSession(username, sessionID, domainOrGroupParentId)) {
                        RequestDispatcher dispatcher = request.getRequestDispatcher("onLoadOfLoginPage");
                        dispatcher.forward(request, response);
                        return;
                    }
                }
            } catch (Exception e) {

            }
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

Exception I get

type Exception report

message Handler processing failed; nested exception is java.lang.StackOverflowError

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.StackOverflowError
    org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1276)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:958)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    net.codejava.spring.AuthenticationFilter.doFilter(AuthenticationFilter.java:52)
root cause

java.lang.StackOverflowError
    com.google.gson.stream.JsonWriter.beforeName(JsonWriter.java:586)
    com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:401)
    com.google.gson.stream.JsonWriter.value(JsonWriter.java:417)
    com.google.gson.internal.bind.TypeAdapters$13.write(TypeAdapters.java:362)
    com.google.gson.internal.bind.TypeAdapters$13.write(TypeAdapters.java:346)
    com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
    com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
    com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)

EDIT
I have identified the root causing line.

response = new Gson().toJson(invException);

Type of

InvalidObjectStateException invException

public class InvalidObjectStateException extends Exception {
    private static final long serialVersionUID = -9086960433236073019L;
    private static final Logger log = Logger.getLogger(InvalidObjectStateException.class);
    private String customErrorMessage = null;
    private Object exceptionCausingObject = null;

    public InvalidObjectStateException(String errorMessage, Object exceptionCausingObject) {
        super(errorMessage);
        this.customErrorMessage = errorMessage;
        log.info("InvalidObjectStateException : exceptionCausingObject"
                + ((exceptionCausingObject != null) ? exceptionCausingObject.getClass().toString() : ""));
        this.exceptionCausingObject = exceptionCausingObject;
    }

    public String getCustomErrorMessage() {
        return customErrorMessage;
    }

    public void setCustomErrorMessage(String customErrorMessage) {
        this.customErrorMessage = customErrorMessage;
    }

    public Object getExceptionCausingObject() {
        return exceptionCausingObject;
    }

    public void setExceptionCausingObject(Object exceptionCausingObject) {
        this.exceptionCausingObject = exceptionCausingObject;
    }
}

What am I doing wrong here ? Why cant Gson parse the Exception ?


问:
500 Internal Server Error when performing large MySQL Insert with PHP / IIS7
System Spec:
VPS running Windows Server 2008 R2 SP1
64-bit dual core 2.39GHz VCPU
2GB RAM
Parallels Plesk for Windows 10.4.4
IIS 7.5
PHP 5.2.17
MySQL 5.1.56

I have a PHP script to loop through a static file and import each line as a row in MySQL. This works fine if the file is split into several thousand lines at a time, but this creates a lot of manual effort.

The whole file contains around 160,000 lines to be imported. The script currently connects to the database via mysql_connect / mysql_select_db, processes the loop with mysql_query, and disconnects at the end of the loop. However, at any point between around 55 seconds - 1 min 35 seconds, the client browser returns a 500 Internal Server Error page, which contains no useful diagnostic info.

I have tried increasing the max connection times of MySQL, PHP, IIS and even the max user sockets for winsock, to no avail.

I tried performing a connect / disconnect to MySQL for each insert query, but this caused thousands of connections to the server which were then stuck in a "TIME_WAIT" state, and returned a "could not connect to server" error, presumably due to insufficient sockets remaining. I have also tried both the mysql and mysqli extensions.

I have looked through all the logs I can find for IIS and MySQL, but cannot see anything that would help with finding the cause.

The last two attempts inserted 33,979 and 78,173 rows respectively.

Can anyone offer any assistance?

Thanks.

** UPDATE **

This must be an IIS issue. I have converted the script to run via command-line PHP and it processes the whole file with no issues.

答:
Use LOAD DATA INFILE instead of trying to do the INSERTs via PHP.  It will run a lot faster, thereby avoiding the 500 error.

Do not even consider using the mysql_* interface. Switch to mysqli or PDO.  It is deprecated and gone in the latest PHP release.


问:
How do I align something in a  in the top-left corner - without aligning everything?
Say I have something that looks like this: http://jsfiddle.net/Dtsjh/

How do I align the numbers in each cell to be in the top-left corner of each cell - without aligning the words?

Preferably in just HTML/CSS - but if you can't do it any of those, then jQuery is fine.

答:
Wrap the number in a , float it to the left, and give it a negative top margin to push it up into the corner: http://jsfiddle.net/ambiguous/chp8y/

You'll have to fiddle with the pixel values on the .sit-in-the-corner margins to get something that works for you.

ContentLicense: CC BY-SA 2.5

Title: How do I align something in a <td> in the top-left corner - without aligning everything?

Body:
Wrap the number in a <span>, float it to the left, and give it a negative top margin to push it up into the corner: http://jsfiddle.net/ambiguous/chp8y/

You'll have to fiddle with the pixel values on the .sit-in-the-corner margins to get something that works for you.


问:
Scatter in matplotlib shows a vertical line of dots in the center of the chart instead of above the corresponding X axis values
The app I am writing parses data in a CSV of datetimes and temperature observation pairs to the same time in another city then writes a report and a scatter chart.  Everything works, except, the scatter chart is showing a vertical line of dots beginning at the center of the x axis, instead of a dot above each listed date on the x axis.

This is the code around my application of matplotlib.

```<code>import matplotlib.pyplot as pp
.
.
.
# Code that imports the CSV, changes the times to the other city ....
.
.
.

paris_stamps = [] # This list is a list of datetimes that compose the X axis

i = 0
while i < len(parsedObservations):
  paris_stamps.append(parsedObservations[i][1])
  i += 1

observed_values = [] # these are the temperatures that go on the X axis
i = 0
while i < len(parsedObservations):
  observed_values.append(parsedObservations[i][0])
  i += 1

# the code below is the interaction with matplotlib

paris_stamps = [pandas.to_datetime(d) for d in paris_stamps] # sanitize the string datetimes to a format matplotlib will accept

pp.scatter(x = paris_stamps,y = observed_values, s = 500, c='blue')
pp.show()
</code>```

When I run this, I get this for a chart:Chart with a vertical line of dots instead of a horizontal series of dots above each of the x axis values

How do I get matplotlib scatter plot to format with a real X,Y pairing chart in this context?

答:
It's hard to give you what you want exactly without your data. Essentially, you are trying to plot categorical data on a scatter plot, which is designed for numerical data. You could use numerical data, range(0, len(observed_values)), to finish the plot first. Then you can change tick labels to corresponding categories as you want. Hopefully, the following is close to what you want:

```<code>from matplotlib import pyplot as plt

observed_values = [6, 3, 1, 5, 2, 4]
paris_stamps = ['2017-04', '2017-05', '2017-06', '2017-07', '2017-08', '2017-09']
plt.scatter(range(0, len(observed_values)), observed_values)
plt.xticks(range(0, len(observed_values)), paris_stamps)
plt.show()
</code>```

You can get this:

Body:
The app I am writing parses data in a CSV of datetimes and temperature observation pairs to the same time in another city then writes a report and a scatter chart.  Everything works, except, the scatter chart is showing a vertical line of dots beginning at the center of the x axis, instead of a dot above each listed date on the x axis.

This is the code around my application of matplotlib.

import matplotlib.pyplot as pp
.
.
.
# Code that imports the CSV, changes the times to the other city ....
.
.
.

paris_stamps = [] # This list is a list of datetimes that compose the X axis

i = 0
while i < len(parsedObservations):
  paris_stamps.append(parsedObservations[i][1])
  i += 1

observed_values = [] # these are the temperatures that go on the X axis
i = 0
while i < len(parsedObservations):
  observed_values.append(parsedObservations[i][0])
  i += 1

# the code below is the interaction with matplotlib

paris_stamps = [pandas.to_datetime(d) for d in paris_stamps] # sanitize the string datetimes to a format matplotlib will accept

pp.scatter(x = paris_stamps,y = observed_values, s = 500, c='blue')
pp.show()

When I run this, I get this for a chart:Chart with a vertical line of dots instead of a horizontal series of dots above each of the x axis values

How do I get matplotlib scatter plot to format with a real X,Y pairing chart in this context?

Body:
It's hard to give you what you want exactly without your data. Essentially, you are trying to plot categorical data on a scatter plot, which is designed for numerical data. You could use numerical data, range(0, len(observed_values)), to finish the plot first. Then you can change tick labels to corresponding categories as you want. Hopefully, the following is close to what you want:

from matplotlib import pyplot as plt

observed_values = [6, 3, 1, 5, 2, 4]
paris_stamps = ['2017-04', '2017-05', '2017-06', '2017-07', '2017-08', '2017-09']
plt.scatter(range(0, len(observed_values)), observed_values)
plt.xticks(range(0, len(observed_values)), paris_stamps)
plt.show()

You can get this:


问:
Not able to launch Gallery from Android Instant app
I created an app which picks up images from images folder in emulator and displays selected image in my layout of application. When I converted my app to instant app, the same code that picks up images from image folder throws exception. I used runtime permissions READ_EXTERNAL_STORAGE.

My code:

```<code>private static final int PICK_IMAGE_REQUEST = 234;
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
</code>```

Exception thrown:

```<code>java.lang.SecurityException: Not allowed to start activity Intent {
          act=android.intent.action.GET_CONTENT typ=*/* }
</code>```

Code for runtime permissions:

```<code>private static final int REQUEST_WRITE_STORAGE = 112;
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public boolean checkPermission()
    {
        int currentAPIVersion = Build.VERSION.SDK_INT;
        if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
        {
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {

                   Toast.makeText(MainActivity.this,"Permission Denied...",Toast.LENGTH_LONG).show();
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_WRITE_STORAGE);
                    return  true;
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }
</code>```

Can anyone help me in solving this issue?

答:
Instant Apps are blocked from accessing some features that regular Android apps can access. The exception:

java.lang.SecurityException: Not allowed to start activity Intent...

Means you have found one such feature. In this case it is Intent.ACTION_GET_CONTENT which is not currently allowed. Support for additional features such as this may be introduced over time.

In addition, Instant Apps do not have access to read or write from external storage so requesting access to READ_EXTERNAL_STORAGE will also not work or throw an exception. See here for a list of permissions that are supported by Instant Apps.

Body:
I created an app which picks up images from images folder in emulator and displays selected image in my layout of application. When I converted my app to instant app, the same code that picks up images from image folder throws exception. I used runtime permissions READ_EXTERNAL_STORAGE.

My code:

private static final int PICK_IMAGE_REQUEST = 234;
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);

Exception thrown:

java.lang.SecurityException: Not allowed to start activity Intent {
          act=android.intent.action.GET_CONTENT typ=*/* }

Code for runtime permissions:

private static final int REQUEST_WRITE_STORAGE = 112;
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public boolean checkPermission()
    {
        int currentAPIVersion = Build.VERSION.SDK_INT;
        if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
        {
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {

                   Toast.makeText(MainActivity.this,"Permission Denied...",Toast.LENGTH_LONG).show();
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_WRITE_STORAGE);
                    return  true;
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

Can anyone help me in solving this issue?


问:
Executing a sqlalchemy exists query
I'm having trouble understanding how to execute a query to check and see if a matching record already exists in sqlalchemy.  Most of the examples I can find online seem to reference "session" and "query" objects that I don't have.

Here's a short complete program that illustrates my problem:

1. sets up in-memory sqlite db with "person" table.

2. inserts two records into the person table.

3. check if a particular record exists in the table.  This is where it barfs.

```<code>from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.sql.expression import exists

engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()

person = Table('person', metadata,
                        Column('id', Integer, primary_key=True),
                        Column('name', String(255), nullable=False))

metadata.create_all(engine)
conn = engine.connect()

s = person.insert()
conn.execute(s, name="Alice")
conn.execute(s, name="Bob")

print("I can see the names in the table:")
s = person.select()
result = conn.execute(s)
print(result.fetchall())

print('This query looks like it should check to see if a matching record exists:')
s = person.select().where(person.c.name == "Bob")
s = exists(s)
print(s)

print("But it doesn't run...")
result = conn.execute(s)
</code>```

The output of this program is:

```<code>I can see the names in the table:
[(1, 'Alice'), (2, 'Bob')]
This query looks like it should check to see if a matching record exists:
EXISTS (SELECT person.id, person.name
FROM person
WHERE person.name = :name_1)
But it doesn't run...
Traceback (most recent call last):
  File "/project_path/db_test/db_test_env/exists_example.py", line 30, in <module>
    result = conn.execute(s)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 945, in execute
    return meth(self, multiparams, params)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 265, in _execute_on_connection
    raise exc.ObjectNotExecutableError(self)
sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: <sqlalchemy.sql.selectable.Exists object at 0x105797438>
</code>```

答:
exists is used in SQL subqueries.  If you had a table posts containing blog post with an author_id, mapping back to people, you might use a query like the following to find people who had made a blog post:

```<code>select * from people where exists (select author_id from posts where author_id = people.id);
</code>```

You can't have a exists as the outermost statement in an SQL query; it's an operator to use in SQL boolean clauses.
So, SQLAlchemy is not letting you execute that query because it's not well-formed.
If you want to see if a row exists, just construct a select statement with a where clause and see how many rows the query returns.

Title: Executing a sqlalchemy exists query

Body:
I'm having trouble understanding how to execute a query to check and see if a matching record already exists in sqlalchemy.  Most of the examples I can find online seem to reference "session" and "query" objects that I don't have.

Here's a short complete program that illustrates my problem:

1. sets up in-memory sqlite db with "person" table.

2. inserts two records into the person table.

3. check if a particular record exists in the table.  This is where it barfs.

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.sql.expression import exists

engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()

person = Table('person', metadata,
                        Column('id', Integer, primary_key=True),
                        Column('name', String(255), nullable=False))

metadata.create_all(engine)
conn = engine.connect()

s = person.insert()
conn.execute(s, name="Alice")
conn.execute(s, name="Bob")

print("I can see the names in the table:")
s = person.select()
result = conn.execute(s)
print(result.fetchall())

print('This query looks like it should check to see if a matching record exists:')
s = person.select().where(person.c.name == "Bob")
s = exists(s)
print(s)

print("But it doesn't run...")
result = conn.execute(s)

The output of this program is:

I can see the names in the table:
[(1, 'Alice'), (2, 'Bob')]
This query looks like it should check to see if a matching record exists:
EXISTS (SELECT person.id, person.name
FROM person
WHERE person.name = :name_1)
But it doesn't run...
Traceback (most recent call last):
  File "/project_path/db_test/db_test_env/exists_example.py", line 30, in <module>
    result = conn.execute(s)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 945, in execute
    return meth(self, multiparams, params)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 265, in _execute_on_connection
    raise exc.ObjectNotExecutableError(self)
sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: <sqlalchemy.sql.selectable.Exists object at 0x105797438>

Body:
exists is used in SQL subqueries.  If you had a table posts containing blog post with an author_id, mapping back to people, you might use a query like the following to find people who had made a blog post:

select * from people where exists (select author_id from posts where author_id = people.id);

You can't have a exists as the outermost statement in an SQL query; it's an operator to use in SQL boolean clauses.
So, SQLAlchemy is not letting you execute that query because it's not well-formed.
If you want to see if a row exists, just construct a select statement with a where clause and see how many rows the query returns.


问:
javascript date difference
I've looked at: Get difference between 2 dates in javascript?

And I still can't get this to work.

```<code>var difference = data.List[0].EndDate - Math.round(new Date().getTime()/1000.0) * 1000;
var daysRemaining = Math.floor(difference / 1000 / 60 / 60 / 24);
var hoursRemaining = Math.floor(difference / 1000 / 60 / 60 - (24 * daysRemaining));
var minutesRemaining = Math.floor(difference / 1000 / 60 - (24 * 60 * daysRemaining) - (60 * hoursRemaining));
var secondsRemaining = Math.floor(difference / 1000 - (24 * 60 * 60 * daysRemaining) - (60 * 60 * hoursRemaining) - (60 * minutesRemaining));
</code>```

data.List[0].EndDate is a UTC number (like: 1291427809310 (http://www.epochconverter.com/)) that will always be later than the current date.

答:
If EndDate is in milliseconds, and getTime() returns milliseconds, why do you divide it by 1000 only to multiply it by 1000 in the same line? And if you only need second precision for all the rest of the code, why work in milliseconds? Start out with a number of seconds to simplify all your calculations:</p>

```<code>var difference = Math.round((data.List[0].EndDate - new Date().getTime()) / 1000);
</code>```

Title: javascript date difference

Body:
I've looked at: Get difference between 2 dates in javascript?

And I still can't get this to work.

var difference = data.List[0].EndDate - Math.round(new Date().getTime()/1000.0) * 1000;
var daysRemaining = Math.floor(difference / 1000 / 60 / 60 / 24);
var hoursRemaining = Math.floor(difference / 1000 / 60 / 60 - (24 * daysRemaining));
var minutesRemaining = Math.floor(difference / 1000 / 60 - (24 * 60 * daysRemaining) - (60 * hoursRemaining));
var secondsRemaining = Math.floor(difference / 1000 - (24 * 60 * 60 * daysRemaining) - (60 * 60 * hoursRemaining) - (60 * minutesRemaining));

data.List[0].EndDate is a UTC number (like: 1291427809310 (http://www.epochconverter.com/)) that will always be later than the current date.

Body:
If EndDate is in milliseconds, and getTime() returns milliseconds, why do you divide it by 1000 only to multiply it by 1000 in the same line? And if you only need second precision for all the rest of the code, why work in milliseconds? Start out with a number of seconds to simplify all your calculations:

var difference = Math.round((data.List[0].EndDate - new Date().getTime()) / 1000);


问:
MIPS: "lw" instruction path
From lecture notes:

from what I understand, doesn't the black dots indicate the binary bits is being copied to both paths moving forward?

For example, instruction bits I[20-16] should be going into the Read register 2 and Write register. It's just that in the end, the Read data 2 is not being used due to the MUX selecting 1.

Did my prof choose not to draw the red lines going to the Read register 2 path just to emphasize on the most significant path? Or does the black dot before Read register 2 have the ability to close off irrelevant data path?

答: Your professor is only highlighting the paths that affect the result. This is normal -- if every path that contained data were highlighted, everything would be red.

Title: MIPS: "lw" instruction path


问:
Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property
Obviously the beta for Angular2 is newer than new, so there's not much information out there, but I am trying to do what I think is some fairly basic routing.

Hacking about with the quick-start code and other snippets from the https://angular.io website has resulted in the following file structure:

```<code>angular-testapp/
    app/
        app.component.ts
        boot.ts
        routing-test.component.ts
    index.html
</code>```

With the files being populated as follows:

index.html

    <base href="/">
    <title>Angular 2 QuickStart</title>
    <link href="../css/bootstrap.css" rel="stylesheet">

    <my-app>Loading...</my-app>

```

<p><strong>boot.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>import {bootstrap}    from 'angular2/platform/browser'
import {ROUTER_PROVIDERS} from 'angular2/router';

import {AppComponent} from './app.component'

bootstrap(AppComponent, [
    ROUTER_PROVIDERS
]);
</code>```

app.component.ts

import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';

import {RoutingTestComponent} from './routing-test.component';

@Component({
    selector: 'my-app',
    template: `

Component Router

        Routing Test
        <router-outlet></router-outlet>
        `
})

@RouteConfig([
    {path:'/routing-test', name: 'RoutingTest', component: RoutingTestComponent, useAsDefault: true},
])

export class AppComponent { }
```

<p><strong>routing-test.component.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>import {Component} from 'angular2/core';
import {Router} from 'angular2/router';

@Component({
    template: `
        <h2>Routing Test</h2>
        <p>Interesting stuff goes here!</p>
        `
})
export class RoutingTestComponent { }
</code>```

Attempting to run this code produces the error:

```<code>EXCEPTION: Template parse errors:
Can't bind to 'routerLink' since it isn't a known native property ("
        <h1>Component Router</h1>
        <a [ERROR ->][routerLink]="['RoutingTest']">Routing Test</a>
        <router-outlet></router-outlet>
        "): AppComponent@2:11
</code>```

I found a vaguely related issue here; router-link directives broken after upgrading to angular2.0.0-beta.0. However, the "working example" in one of the answers is based on pre-beta code - which may well still work, but I would like to know why the code I have created is not working.

Any pointers would be gratefully received!

答:
In my case I have imported the RouterModule in App module but not imported in my feature module. After import the router module in my EventModule the error goes away.

    import {NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import {EventListComponent} from './EventList.Component';
    import {EventThumbnailComponent} from './EventThumbnail.Component';
    import { EventService } from './shared/Event.Service'
    import {ToastrService} from '../shared/toastr.service';
    import {EventDetailsComponent} from './event-details/event.details.component';
    import { RouterModule } from "@angular/router";
    @NgModule({
      imports:[BrowserModule,RouterModule],
      declarations:[EventThumbnailComponent,EventListComponent,EventDetailsComponent],
      exports: [EventThumbnailComponent,EventListComponent,EventDetailsComponent],
       providers: [EventService,ToastrService]
    })
    export class EventModule {

     }
```

Body:
Obviously the beta for Angular2 is newer than new, so there's not much information out there, but I am trying to do what I think is some fairly basic routing.

Hacking about with the quick-start code and other snippets from the https://angular.io website has resulted in the following file structure:

angular-testapp/
    app/
        app.component.ts
        boot.ts
        routing-test.component.ts
    index.html

With the files being populated as follows:

index.html

    <base href="/">
    <title>Angular 2 QuickStart</title>
    <link href="../css/bootstrap.css" rel="stylesheet">

    <my-app>Loading...</my-app>

boot.ts

import {bootstrap}    from 'angular2/platform/browser'
import {ROUTER_PROVIDERS} from 'angular2/router';

import {AppComponent} from './app.component'

bootstrap(AppComponent, [
    ROUTER_PROVIDERS
]);

app.component.ts

import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';

import {RoutingTestComponent} from './routing-test.component';

@Component({
    selector: 'my-app',
    template: `

Component Router

        Routing Test
        <router-outlet></router-outlet>
        `
})

@RouteConfig([
    {path:'/routing-test', name: 'RoutingTest', component: RoutingTestComponent, useAsDefault: true},
])

export class AppComponent { }

routing-test.component.ts

import {Component} from 'angular2/core';
import {Router} from 'angular2/router';

@Component({
    template: `

Routing Test

Interesting stuff goes here!

        `
})
export class RoutingTestComponent { }

Attempting to run this code produces the error:

EXCEPTION: Template parse errors:
Can't bind to 'routerLink' since it isn't a known native property ("

Component Router

        ][routerLink]="['RoutingTest']">Routing Test
        <router-outlet></router-outlet>
        "): AppComponent@2:11

I found a vaguely related issue here; router-link directives broken after upgrading to angular2.0.0-beta.0. However, the "working example" in one of the answers is based on pre-beta code - which may well still work, but I would like to know why the code I have created is not working.

Any pointers would be gratefully received!