问:
TypeError: __init__() missing 1 required positional argument: 'output_size'
Hi I'm facing the below error. Please let me know how to go about it.

I'm facing error related to arguments in model.add(TimeDistributedDense(self.output_size))

```<code>    from __future__ import print_function
    from keras.preprocessing import sequence
    from keras.models import Sequential
    from keras.layers.core import Activation, RepeatVector, TimeDistributedDense, Dropout, Dense
    from keras.layers import recurrent
    from keras.layers.embeddings import Embedding
    import numpy as np
    from preprocessing import preprocess
    import pdb
    RNN = recurrent.LSTM

    class seq2seq(object):
    # Initialize model parameters
        def __init__(self, input_size, seqlen, output_size, input_dim = 100, \
             hidden_dim = 200):
            self.maxlen = seqlen
            self.input_size = input_size
            self.output_size = output_size
            self.input_dim = input_dim
            self.hidden_dim = hidden_dim

        def seq2seq_plain(self):
        # Plain seq2seq
            model = Sequential()
            model.add(Embedding(self.input_size , self.input_dim))
            model.add(RNN(self.hidden_dim, return_sequences=True))#, input_shape=(100, 128)))

            model.add(Dropout(0.25))
            model.add(RNN(self.hidden_dim))
            model.add(RepeatVector(self.maxlen))
            #model.add(RNN(self.hidden_dim, return_sequences=True))
            #model.add(Dropout(0.25))
            model.add(RNN(self.hidden_dim, return_sequences=True))
            model.add(TimeDistributedDense(self.output_size))
            model.add(Dropout(0.5))
            model.add(Activation('softmax'))

            model.compile(loss='categorical_crossentropy', optimizer='adam',
                  metrics=['accuracy'])
            return model

       def seq2seq_attention(self):
            raise NotImplementedError

    if __name__ == "__main__":
    # Test the model
    seq2seq = seq2seq(15, 5500)
    seq2seq.train_seq2seq()
</code>```

Error:

```<code>    Traceback (most recent call last):

     File "<ipython-input-36-392427814c8f>", line 50, in <module>
     seq2seq = seq2seq(15, 5500)

     TypeError: __init__() missing 1 required positional argument: 'output_size'
</code>```

答:
This is the constructor:

```<code>def __init__(self, input_size, seqlen, output_size, input_dim = 100, hidden_dim = 200)
</code>```

It means you have to at least pass values of input_size, seqlen and output_size, i.e you have to pass 3 parameters. Other parameters like input_dim and hidden_dim have default values, so you don't have to provide values for them while creating the object. But you have to pass 3 parameters while creating object.

You are currently creating the object by passing only 2 parameters.

```<code> seq2seq = seq2seq(15, 5500)
</code>```

Change it by giving 1 more parameter for output_size as it does not have any default value.

Modify:

Pass 1 more parameter for output_size

Object name should be different from class name.

Result:

```<code>seq2seq_obj = seq2seq(15, 5500, 10) # 1 more parameter for output_size
</code>```

Body:
Hi I'm facing the below error. Please let me know how to go about it.

I'm facing error related to arguments in model.add(TimeDistributedDense(self.output_size))

    from __future__ import print_function
    from keras.preprocessing import sequence
    from keras.models import Sequential
    from keras.layers.core import Activation, RepeatVector, TimeDistributedDense, Dropout, Dense
    from keras.layers import recurrent
    from keras.layers.embeddings import Embedding
    import numpy as np
    from preprocessing import preprocess
    import pdb
    RNN = recurrent.LSTM

    class seq2seq(object):
    # Initialize model parameters
        def __init__(self, input_size, seqlen, output_size, input_dim = 100, \
             hidden_dim = 200):
            self.maxlen = seqlen
            self.input_size = input_size
            self.output_size = output_size
            self.input_dim = input_dim
            self.hidden_dim = hidden_dim

        def seq2seq_plain(self):
        # Plain seq2seq
            model = Sequential()
            model.add(Embedding(self.input_size , self.input_dim))
            model.add(RNN(self.hidden_dim, return_sequences=True))#, input_shape=(100, 128)))

            model.add(Dropout(0.25))
            model.add(RNN(self.hidden_dim))
            model.add(RepeatVector(self.maxlen))
            #model.add(RNN(self.hidden_dim, return_sequences=True))
            #model.add(Dropout(0.25))
            model.add(RNN(self.hidden_dim, return_sequences=True))
            model.add(TimeDistributedDense(self.output_size))
            model.add(Dropout(0.5))
            model.add(Activation('softmax'))

            model.compile(loss='categorical_crossentropy', optimizer='adam',
                  metrics=['accuracy'])
            return model

       def seq2seq_attention(self):
            raise NotImplementedError

    if __name__ == "__main__":
    # Test the model
    seq2seq = seq2seq(15, 5500)
    seq2seq.train_seq2seq()

Error:

    Traceback (most recent call last):

     File "<ipython-input-36-392427814c8f>", line 50, in <module>
     seq2seq = seq2seq(15, 5500)

     TypeError: __init__() missing 1 required positional argument: 'output_size'

Body:
This is the constructor:

def __init__(self, input_size, seqlen, output_size, input_dim = 100, hidden_dim = 200)

It means you have to at least pass values of input_size, seqlen and output_size, i.e you have to pass 3 parameters. Other parameters like input_dim and hidden_dim have default values, so you don't have to provide values for them while creating the object. But you have to pass 3 parameters while creating object.

You are currently creating the object by passing only 2 parameters.

 seq2seq = seq2seq(15, 5500)

Change it by giving 1 more parameter for output_size as it does not have any default value.

Modify:

Pass 1 more parameter for output_size

Object name should be different from class name.

Result:

seq2seq_obj = seq2seq(15, 5500, 10) # 1 more parameter for output_size


来源: stackexchange

问:
Why is my MVC app throwing a blank page?
Deploying my ASP.NET MVC 2 application to an IIS7 staging server leads to a blank page, regardless of the action called. Attempts to access controller actions that require authentication are correctly redirected to /Account/LogOn, but this page too shows only a blank page on both my local machine and the remote server.

I have checked my site permissions and I think it is an assembly issue, but no errors show up in the Application log.

How do I determine the cause of the error?

I recently installed ASP.NET MVC 3 on my dev machine, but made no changes to this project and I am using StructureMap for DI, if that makes a difference.

答:
You could try installing Elmah from Nuget.

In the Package Manager Console, type install-package elmah. Then run your app.

Also, if you're not actually getting any errors, have you checked the rendered source in your browser? Your master page could have something commented out in it. Probably not though!

Another suggestion would be to empty the bin directory completely after doing a Clean Solution, rebuild, and try again.

In cases like this, it generally helps breaking the problem down to the smallest steps needed to replicate the problem. In your case, remove all routes, barring the one/s you need, empty out your master page and view to just a very simple 'hello world' and also comment out any code in your action so that it's not going off to the database or whatever else.

ContentLicense: CC BY-SA 2.5


问:
AJAX POST-method not allowed Error 405
I'm trying to send an email when I click on a button. For this I make an ajax call to a php file:

Ajax call:

```<code> function postAjax(arr) {
     $.ajax({
         url: "../BackEnd/AjaxHandler.php",
         data: { 'action': 'mail' },
         type: "GET"
     });
 }
</code>```

php file (Ajaxhandler.php)

```<code><?php
   if(isset($_GET['action']) && !empty($_GET['action'])) {
   $action = $_GET['action'];
   switch($action){
      case 'mail':
         mail('N.Suhner@wigasoft.ch', 'Mein Betreff', 'tsest');
         break;
      }
   }
?>
</code>```

call:

```<code>$("#mailto").click(function() {
   postAjax(listOfTasks);
 });
</code>```

In the call I make some more things but these are not relevant (styling).

When I click on the button I got an error that the POST-method is not allowed. Does anyone know what I am doing wrong?

答:
IMHO, if you got 405 post method not allowed, a workaround (well, not really a solution) can be trying with these settings:</p>

```<code>function postAjax(arr) {
  $.ajax({
   type: "GET",
   url: "../_BackEnd/AjaxHandler.php?id=12",
   dataType: "json"
  }).done(function(d){
      console.log(d);
  }).fail(function(j){
      console.log(j.responseText);
  });
 }
</code>```

ContentLicense: CC BY-SA 3.0

Title: AJAX POST-method not allowed Error 405

Body:
I'm trying to send an email when I click on a button. For this I make an ajax call to a php file:

Ajax call:

 function postAjax(arr) {
     $.ajax({
         url: "../BackEnd/AjaxHandler.php",
         data: { 'action': 'mail' },
         type: "GET"
     });
 }

php file (Ajaxhandler.php)

<?php
   if(isset($_GET['action']) && !empty($_GET['action'])) {
   $action = $_GET['action'];
   switch($action){
      case 'mail':
         mail('N.Suhner@wigasoft.ch', 'Mein Betreff', 'tsest');
         break;
      }
   }
?>

call:

$("#mailto").click(function() {
   postAjax(listOfTasks);
 });

In the call I make some more things but these are not relevant (styling).

When I click on the button I got an error that the POST-method is not allowed. Does anyone know what I am doing wrong?

Body:
IMHO, if you got 405 post method not allowed, a workaround (well, not really a solution) can be trying with these settings:

function postAjax(arr) {
  $.ajax({
   type: "GET",
   url: "../_BackEnd/AjaxHandler.php?id=12",
   dataType: "json"
  }).done(function(d){
      console.log(d);
  }).fail(function(j){
      console.log(j.responseText);
  });
 }


问:
Find first negative number and prepend a zero
I want to insert a 0 before the first occurrence of - followed by a number.

I have tried the below simple code.

```<code>$formula = '[ (((-594 - 0) )/ 55032411) *244 ]';
preg_match('/^-?\d+(\.\d+)?$/', $formula, $match);

print_r($match);
$result = str_replace($match[0],'0'.$match[0],$formula);
echo $result;
exit;
</code>```

I want the below result.

```<code>[ (((0-594 - 0) )/ 55032411) *244 ]
</code>```

答:
The solution using preg_replace function:

```<code>$formula = '[ (((-594 - 0) )/ 55032411) *244 ]';
$result = preg_replace('/-?\d+(\.\d+)?/', '0$0', $formula, 1);

print_r($result);
</code>```

The output:

```<code>[ (((0-594 - 0) )/ 55032411) *244 ]
</code>```

The 4th argument 1 passed to preg_replace is the maximum replacements for the pattern in the input string

Body:
I want to insert a 0 before the first occurrence of - followed by a number.

I have tried the below simple code.

$formula = '[ (((-594 - 0) )/ 55032411) *244 ]';
preg_match('/^-?\d+(\.\d+)?$/', $formula, $match);

print_r($match);
$result = str_replace($match[0],'0'.$match[0],$formula);
echo $result;
exit;

I want the below result.

[ (((0-594 - 0) )/ 55032411) *244 ]

Body:
The solution using preg_replace function:

$formula = '[ (((-594 - 0) )/ 55032411) *244 ]';
$result = preg_replace('/-?\d+(\.\d+)?/', '0$0', $formula, 1);

print_r($result);

The output:

[ (((0-594 - 0) )/ 55032411) *244 ]

The 4th argument 1 passed to preg_replace is the maximum replacements for the pattern in the input string


问:
Cannot resolve constructor and method for reason I don't know
```<code>public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }
</code>```

Is there something wrong with these lines of code??? I;ve got red line under the (this, NumbersActivity.class); and it says cannot resolve constuctor 'Intent(......)' and red text startActivity saying cannot re[enter image description here][1]solve method 'startActivity(android.content.Intent)'

I'm a totally new to this

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/tan_background"
    android:orientation="vertical"
    tools:context="com.example.android.miwok.MainActivity">

    <TextView
        android:id="@+id/numbers"
        style="@style/CategoryStyle"
        android:background="@color/category_numbers"
        android:text="@string/category_numbers"
        android:onClick="openNumbers"/>

    <TextView
        android:id="@+id/family"
        style="@style/CategoryStyle"
        android:background="@color/category_family"
        android:text="@string/category_family" />

    <TextView
        android:id="@+id/colors"
        style="@style/CategoryStyle"
        android:background="@color/category_colors"
        android:text="@string/category_colors" />

    <TextView
        android:id="@+id/phrases"
        style="@style/CategoryStyle"
        android:background="@color/category_phrases"
        android:text="@string/category_phrases" />

</LinearLayout>
</code>```

MainActivity.java

```<code>package com.example.android.miwok;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);
    }

    public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }
}
</code>```

AndroidManidest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.miwok">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NumbersActivity" >

        </activity>
        <activity android:name=".PhrasesActivity" >

        </activity>
        <activity android:name=".FamilyActivity" >

        </activity>
        <activity android:name=".ColorsActivity">

        </activity>
    </application>

</manifest>
</code>```

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

答:
No problem with using
Intent numbers = new Intent(MainActivity.this, NumbersActivity.class);
Intent numbers = new Intent(this, NumbersActivity.class);

please clean the project and rebuild and see if problem still exist or not,i think that will go away..

and if error will come studio will show you some message for the same kindly read that message and post it for helping the same..

Body:
public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }

Is there something wrong with these lines of code??? I;ve got red line under the (this, NumbersActivity.class); and it says cannot resolve constuctor 'Intent(......)' and red text startActivity saying cannot re[enter image description here][1]solve method 'startActivity(android.content.Intent)'

I'm a totally new to this

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/tan_background"
    android:orientation="vertical"
    tools:context="com.example.android.miwok.MainActivity">

    <TextView
        android:id="@+id/numbers"
        style="@style/CategoryStyle"
        android:background="@color/category_numbers"
        android:text="@string/category_numbers"
        android:onClick="openNumbers"/>

    <TextView
        android:id="@+id/family"
        style="@style/CategoryStyle"
        android:background="@color/category_family"
        android:text="@string/category_family" />

    <TextView
        android:id="@+id/colors"
        style="@style/CategoryStyle"
        android:background="@color/category_colors"
        android:text="@string/category_colors" />

    <TextView
        android:id="@+id/phrases"
        style="@style/CategoryStyle"
        android:background="@color/category_phrases"
        android:text="@string/category_phrases" />

</LinearLayout>

MainActivity.java

package com.example.android.miwok;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);
    }

    public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }
}

AndroidManidest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.miwok">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NumbersActivity" >

        </activity>
        <activity android:name=".PhrasesActivity" >

        </activity>
        <activity android:name=".FamilyActivity" >

        </activity>
        <activity android:name=".ColorsActivity">

        </activity>
    </application>

</manifest>

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY


问:
UIView borderWidth not visible
I want to have a rounded view with a black center and a colored border. When I set up my view like this:

```<code>myView.backgroundColor = UIColor.red
myView.layer.borderColor = UIColor.white.cgColor
myView.layer.borderWidth = 3
</code>```

I get just a red round. But when I go to the Debug View Hierarchy, I see, that myView has a white border. Madness! What do I make wrong?

iPhone:
and Debug View Hierarchy:

答:
You can use custom border and background like bellow

```<code>@IBDesignable class view_border_background: UIView {

private let gradientLayer : CAGradientLayer = CAGradientLayer()

 //let gradientLayer = CAGradientLayer()

// IBInspectable properties for the gradient colors
@IBInspectable var bottomColor: UIColor = UIColor(hex: 0xe5e5e5)
@IBInspectable var middleColor: UIColor = UIColor(hex: 0xe5e5e5)
@IBInspectable var topColor: UIColor = UIColor(hex: 0xe5e5e5)
@IBInspectable var bottomColorAlpha: CGFloat = 1.0
@IBInspectable var middleColorAlpha: CGFloat = 1.0
@IBInspectable var topColorAlpha: CGFloat = 1.0

// IBInspectable properties for rounded corners and border color / width
@IBInspectable var cornerSize: CGFloat = 0
@IBInspectable var borderSize: CGFloat = 1
@IBInspectable var borderColor: UIColor = colorize(hex: 0x8bc218)
@IBInspectable var borderAlpha: CGFloat = 1.0

override func draw(_ rect: CGRect) {

    // set up border and cornerRadius
    self.layer.cornerRadius = cornerSize
    self.layer.borderColor = borderColor.withAlphaComponent(borderAlpha).cgColor
    self.layer.borderWidth = borderSize

    self.layer.masksToBounds = true

    // set up gradient

    gradientLayer.frame = rect
    let c1 = bottomColor.withAlphaComponent(bottomColorAlpha).cgColor
    let c2 = middleColor.withAlphaComponent(middleColorAlpha).cgColor
    let c3 = topColor.withAlphaComponent(topColorAlpha).cgColor
    gradientLayer.colors = [c3, c2, c1]
    gradientLayer.startPoint = CGPoint(x: 0, y: 0)
    gradientLayer.endPoint = CGPoint(x: 0, y: 0)
   self.layer.insertSublayer(gradientLayer, at: 0)

}
override public func layoutSubviews() {
    super.layoutSubviews()

    gradientLayer.frame = self.layer.bounds
    }

  }
</code>```

Hex color convert

```<code>func colorize (hex: Int, alpha: Double = 1) -> UIColor {
let red = Double((hex & 0xFF0000) >> 16) / 255.0
let green = Double((hex & 0xFF00) >> 8) / 255.0
let blue = Double((hex & 0xFF)) / 255.0
var color: UIColor = UIColor( red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha:CGFloat(alpha) )
return color
</code>```

}

Just add "view_border_background" show identity inspector in VIView

Title: UIView borderWidth not visible

Body:
I want to have a rounded view with a black center and a colored border. When I set up my view like this:

myView.backgroundColor = UIColor.red
myView.layer.borderColor = UIColor.white.cgColor
myView.layer.borderWidth = 3

I get just a red round. But when I go to the Debug View Hierarchy, I see, that myView has a white border. Madness! What do I make wrong?

iPhone:
and Debug View Hierarchy:

Body:
You can use custom border and background like bellow

@IBDesignable class view_border_background: UIView {

private let gradientLayer : CAGradientLayer = CAGradientLayer()

 //let gradientLayer = CAGradientLayer()

// IBInspectable properties for the gradient colors
@IBInspectable var bottomColor: UIColor = UIColor(hex: 0xe5e5e5)
@IBInspectable var middleColor: UIColor = UIColor(hex: 0xe5e5e5)
@IBInspectable var topColor: UIColor = UIColor(hex: 0xe5e5e5)
@IBInspectable var bottomColorAlpha: CGFloat = 1.0
@IBInspectable var middleColorAlpha: CGFloat = 1.0
@IBInspectable var topColorAlpha: CGFloat = 1.0

// IBInspectable properties for rounded corners and border color / width
@IBInspectable var cornerSize: CGFloat = 0
@IBInspectable var borderSize: CGFloat = 1
@IBInspectable var borderColor: UIColor = colorize(hex: 0x8bc218)
@IBInspectable var borderAlpha: CGFloat = 1.0

override func draw(_ rect: CGRect) {

    // set up border and cornerRadius
    self.layer.cornerRadius = cornerSize
    self.layer.borderColor = borderColor.withAlphaComponent(borderAlpha).cgColor
    self.layer.borderWidth = borderSize

    self.layer.masksToBounds = true

    // set up gradient

    gradientLayer.frame = rect
    let c1 = bottomColor.withAlphaComponent(bottomColorAlpha).cgColor
    let c2 = middleColor.withAlphaComponent(middleColorAlpha).cgColor
    let c3 = topColor.withAlphaComponent(topColorAlpha).cgColor
    gradientLayer.colors = [c3, c2, c1]
    gradientLayer.startPoint = CGPoint(x: 0, y: 0)
    gradientLayer.endPoint = CGPoint(x: 0, y: 0)
   self.layer.insertSublayer(gradientLayer, at: 0)

}
override public func layoutSubviews() {
    super.layoutSubviews()

    gradientLayer.frame = self.layer.bounds
    }

  }

Hex color convert

func colorize (hex: Int, alpha: Double = 1) -> UIColor {
let red = Double((hex & 0xFF0000) >> 16) / 255.0
let green = Double((hex & 0xFF00) >> 8) / 255.0
let blue = Double((hex & 0xFF)) / 255.0
var color: UIColor = UIColor( red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha:CGFloat(alpha) )
return color

}

Just add "view_border_background" show identity inspector in VIView


问:
My laravel keeps redirecting to localhost/dashboard whenever I try to type something next to soulfy_repo/public_html/
My laravel keeps redirecting to localhost/dashboard whenever I try to type something next to soulfy_repo/public_html

someone mention that I need to change my .htaccess

This is my .htaccess

```<code> <IfModule mod_rewrite.c>
 <IfModule mod_negotiation.c>
       Options -MultiViews
   </IfModule>

   RewriteEngine On

   RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

   # Redirect Trailing Slashes If Not A Folder...
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)/$ /$1 [L,R=301]

   # Handle Front Controller...
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^ index.php [L]
 </IfModule>
</code>```

答: Remove RewriteBase / form .htaccess OR comment it.

Body:
My laravel keeps redirecting to localhost/dashboard whenever I try to type something next to soulfy_repo/public_html

someone mention that I need to change my .htaccess

This is my .htaccess

 <IfModule mod_rewrite.c>
 <IfModule mod_negotiation.c>
       Options -MultiViews
   </IfModule>

   RewriteEngine On

   RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

   # Redirect Trailing Slashes If Not A Folder...
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)/$ /$1 [L,R=301]

   # Handle Front Controller...
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^ index.php [L]
 </IfModule>


问:
Data type of time in Spring-Data-Rest
I want to store the time what data type should I used in spring framework ?
Database which I used is MySQL </p>

```<code>@Entity
public class ShopDetail {

@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String address;

    private Double latitude;

    private Double longitude;

    private float  rating;

    private Time openingTime;

    private Time closingTime;
    }
</code>```

答:
If you're using Java 8, the most business logic, entity fields may be using Instant - basic class in java.time API for representing a moment in the timeline in UTC.

If you need timezone data, you may consider using:

ZonedDateTime is an immutable representation of a date-time with a time-zone. This
  class stores all date and time fields

Another option LocalDateTime:

A date-time without a time-zone in the ISO-8601 calendar system, such
  as 2007-12-03T10:15:30

But then you would rely on a default system timezone which may bring contradicting results if a system timezone would change.

Check Java 8: What's the difference between Instant and LocalDateTime? or Hibernate with Java 8 LocalDate & LocalDateTime in Database for explicit explanation.

Title: Data type of time in Spring-Data-Rest

Body:
I want to store the time what data type should I used in spring framework ?
Database which I used is MySQL

@Entity
public class ShopDetail {

@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String address;

    private Double latitude;

    private Double longitude;

    private float  rating;

    private Time openingTime;

    private Time closingTime;
    }


问:
Need to write JUnit test for Scala code
I am new to Scala and Spark. I need to write JUnit for the following word count program:

```<code>import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark._

object SparkWordCount {

  def main(args: Array[String]) {

    meth()

  }

  def meth() {

    //Spark Config object having cluster information
    val sparkConfig = new SparkConf()
      .setAppName("SparkWordCount")
      .setMaster("local")

    val sc = new SparkContext(sparkConfig)

    val input = sc.textFile("C:\\SparkW\\input\\inp.txt")
    val count = input.flatMap(line ⇒ line.split(" "))
      .map(word ⇒ (word, 1))
      .reduceByKey(_ + _)
    count.saveAsTextFile("outfile")
    System.out.println("OK");

  }

}
</code>```

How do I write a test for this using JUnit?

答:
you can use one of the many scala spec/test libraries

a test can look like

```<code>import org.scalatest.{FlatSpec, Matchers}

class WordCountSpec extends FlatSpec with Matchers {
  "wordCount" should "return an empty output for an empty input" in
withLocalSparkContext { context =>
  val lines = context.emptyRDD[String]
  val words = WordCount.wordCount(lines).collect()
  words should be (Seq.empty)
}}
</code>```

check this for a full example Spec Class

there are example programs out there for scalatest specification etc, have a search around

Title: Need to write JUnit test for Scala code

Body:
I am new to Scala and Spark. I need to write JUnit for the following word count program:

import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark._

object SparkWordCount {

  def main(args: Array[String]) {

    meth()

  }

  def meth() {

    //Spark Config object having cluster information
    val sparkConfig = new SparkConf()
      .setAppName("SparkWordCount")
      .setMaster("local")

    val sc = new SparkContext(sparkConfig)

    val input = sc.textFile("C:\\SparkW\\input\\inp.txt")
    val count = input.flatMap(line ⇒ line.split(" "))
      .map(word ⇒ (word, 1))
      .reduceByKey(_ + _)
    count.saveAsTextFile("outfile")
    System.out.println("OK");

  }

}

How do I write a test for this using JUnit?

Body:
you can use one of the many scala spec/test libraries

a test can look like

import org.scalatest.{FlatSpec, Matchers}

class WordCountSpec extends FlatSpec with Matchers {
  "wordCount" should "return an empty output for an empty input" in
withLocalSparkContext { context =>
  val lines = context.emptyRDD[String]
  val words = WordCount.wordCount(lines).collect()
  words should be (Seq.empty)
}}

check this for a full example Spec Class

there are example programs out there for scalatest specification etc, have a search around


问:
How can I use joint primary keys and Kohana 3 ORM?
This is the table:

```<code>CREATE TABLE IF NOT EXISTS `requests` (
  `ctrc_id` varchar(45) NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT '0',
  `user_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`user_id`,`ctrc_id`),
  KEY `fk_requests_users1` (`user_id`)
)
</code>```

What I have to change in the model? Will ko3 ORM work?

答:
Kohana doesn't support compound primary keys. Take a look at the Search results for 'compound' on the Kohana forum to see if someone has solved this problem before.

You should also keep an eye on this issue for any signs of progress: Multi primary keys / foreign keys in ORM. It wont harm to add your support for the feature either.

Body:
This is the table:

CREATE TABLE IF NOT EXISTS `requests` (
  `ctrc_id` varchar(45) NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT '0',
  `user_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`user_id`,`ctrc_id`),
  KEY `fk_requests_users1` (`user_id`)
)

What I have to change in the model? Will ko3 ORM work?


问:
Can't destroy cookie and session in same time?
I'm trying to destroy visitors cookie and session at same time when he/she logs out. Like this:

```<code>setcookie($id, '', time()-13600, "/");
unset($_SESSION[$id]);
</code>```

Although cookie destroys but user is still logged in because session not destroying.

Note: I can't use session_unset() because it will destroy all the sessions.

PS: I solved my problem just by not setting session but only cookie, still i can't solve problem i asked above.

答:
well you could use session_destroy() in order to unset the session for current user.
the rest of sessions will stay unchanged.
this is how you do it</p>

```<code><?php
session_destroy();
</code>```

Body:
I'm trying to destroy visitors cookie and session at same time when he/she logs out. Like this:

setcookie($id, '', time()-13600, "/");
unset($_SESSION[$id]);

Although cookie destroys but user is still logged in because session not destroying.

Note: I can't use session_unset() because it will destroy all the sessions.

PS: I solved my problem just by not setting session but only cookie, still i can't solve problem i asked above.

Body:
well you could use session_destroy() in order to unset the session for current user.
the rest of sessions will stay unchanged.
this is how you do it

<?php
session_destroy();


问:
Smart Table not refreshing on setTimeout
The code related to table generation is not working in the below function

```<code>function populateDataTable(repo_contributor,repo_langauges){
    $scope.rowCollection = [
        {firstName: 'Laurent', lastName: 'Renard', birthDate: new Date('1987-05-21'), balance: 102, email: 'whatever@gmail.com'},
        {firstName: 'Blandine', lastName: 'Faivre', birthDate: new Date('1987-04-25'), balance: -2323.22, email: 'oufblandou@gmail.com'},
        {firstName: 'Francoise', lastName: 'Frere', birthDate: new Date('1955-08-27'), balance: 42343, email: 'raymondef@gmail.com'}
    ];

 for (var key in repo_contributor){
    console.log(repo_contributor[key]);
    var repo_table_data = {};
    repo_table_data['repo_name'] = key;
    repo_table_data['contributors'] = repo_contributor[key].toString();
    repo_table_data['languages'] = repo_langauges[key].toString();
     console.log(repo_table_data);
    $scope.repo_info_list.push(repo_table_data);
}
    console.log("here now");
    console.log($scope.repo_info_list.length);

}
</code>```

the populateDataTable is being populated by the below code

```<code>setTimeout(populateDataTable,4000,$scope.repo_contributor,$scope.repo_languages);
</code>```

$scope.rowCollection is being set but not being displayed on table( table is empty).

However if $scope.rowCollection is placed outside the populateDataTable, the table is populated with correct values.

Your help is greatly appreciated.

答:
In setTimeOut try an arrow function like this:</p>

```<code>setTimeout( ()=> {
   populateDataTable($scope.repo_contributor,$scope.repo_languages);
  }, 3000)
</code>```

Body:
The code related to table generation is not working in the below function

function populateDataTable(repo_contributor,repo_langauges){
    $scope.rowCollection = [
        {firstName: 'Laurent', lastName: 'Renard', birthDate: new Date('1987-05-21'), balance: 102, email: 'whatever@gmail.com'},
        {firstName: 'Blandine', lastName: 'Faivre', birthDate: new Date('1987-04-25'), balance: -2323.22, email: 'oufblandou@gmail.com'},
        {firstName: 'Francoise', lastName: 'Frere', birthDate: new Date('1955-08-27'), balance: 42343, email: 'raymondef@gmail.com'}
    ];

 for (var key in repo_contributor){
    console.log(repo_contributor[key]);
    var repo_table_data = {};
    repo_table_data['repo_name'] = key;
    repo_table_data['contributors'] = repo_contributor[key].toString();
    repo_table_data['languages'] = repo_langauges[key].toString();
     console.log(repo_table_data);
    $scope.repo_info_list.push(repo_table_data);
}
    console.log("here now");
    console.log($scope.repo_info_list.length);

}

the populateDataTable is being populated by the below code

setTimeout(populateDataTable,4000,$scope.repo_contributor,$scope.repo_languages);

$scope.rowCollection is being set but not being displayed on table( table is empty).

However if $scope.rowCollection is placed outside the populateDataTable, the table is populated with correct values.

Your help is greatly appreciated.

Body:
In setTimeOut try an arrow function like this:

setTimeout( ()=> {
   populateDataTable($scope.repo_contributor,$scope.repo_languages);
  }, 3000)


问:
How to replace a html tag with nsattribute in swift?
For eg. replace a  tag with bold font. So that it can be applied as attributed text to label, textfield or textview

答:
You need to remove the ^ and $ anchors.

The ^ means start of string and $ means end of string (or line, depending on the options). That's why your first example works: in the first test string, the start of the string is really followed by your pattern and ends with it.

In the second test string, the pattern is found in the middle of the string, thus the ^... can't apply. If you would just remove the ^, the $ would apply on the second occurrence of the registration number and the output would be my car reg 1 - DD11 AAA  my car reg 2 - XX.

```<code>let myString = "my car reg 1 - DD11 AAA  my car reg 2 - AA22 BBB"
let regex = try! NSRegularExpression(pattern: "([A-HK-PRSVWY][A-HJ-PR-Y])\\s?([0][2-9]|[1-9][0-9])\\s?[A-HJ-PR-Z]{3}", options:        NSRegularExpressionOptions.CaseInsensitive)
let range = NSMakeRange(0, myString.characters.count)
let modString = regex.stringByReplacingMatchesInString(myString, options: [], range: range, withTemplate: "XX")
print(modString)
// Output: "my car reg 1 - XX  my car reg 2 - XX"
</code>```

Reference: https://stackoverflow.com/a/28503676/8169585

Body:
You need to remove the ^ and $ anchors.

The ^ means start of string and $ means end of string (or line, depending on the options). That's why your first example works: in the first test string, the start of the string is really followed by your pattern and ends with it.

In the second test string, the pattern is found in the middle of the string, thus the ^... can't apply. If you would just remove the ^, the $ would apply on the second occurrence of the registration number and the output would be my car reg 1 - DD11 AAA  my car reg 2 - XX.

let myString = "my car reg 1 - DD11 AAA  my car reg 2 - AA22 BBB"
let regex = try! NSRegularExpression(pattern: "([A-HK-PRSVWY][A-HJ-PR-Y])\\s?([0][2-9]|[1-9][0-9])\\s?[A-HJ-PR-Z]{3}", options:        NSRegularExpressionOptions.CaseInsensitive)
let range = NSMakeRange(0, myString.characters.count)
let modString = regex.stringByReplacingMatchesInString(myString, options: [], range: range, withTemplate: "XX")
print(modString)
// Output: "my car reg 1 - XX  my car reg 2 - XX"

Reference: https://stackoverflow.com/a/28503676/8169585


问:
Can any one give me some advice to make my for loop more efficient?
So I have this for loop with 36 if-queries inside. Any advice on making it more efficient?
You can view the complete code  here

Here's a sample of what it looks like:

```<code>$numbers = range(1, 36);
shuffle($numbers);
for ($m =0; $m<37; $m++){
    if ($numbers[$m] == "1"){
        $mirza[$m] = "RUTHIE";
        $mage[$m] = "3";
        $mquote[$m] = "I get to learn a lot of new things here, like sign language!";
        $link[$m] = "http://www.google.com";
    }

    if ($numbers[$m] == "2"){
        $mirza[$m] = "AIDA";
        $mage[$m] = "82";
        $mquote[$m] = "This is like a club and I know and like all the members. It's good therapy.";
        $link[$m] = "/about/";
    }

    if ($numbers[$m] == "3"){
        $mirza[$m] = "AMIRE";
        $mage[$m] = "4";
        $mquote[$m] = "I am learning how to share and make friends.";
        $link[$m] = "/about/";
    }
}
</code>```

答:
When you have this much data it really should be in a database (maybe XML or document style) or a text file.

Still, I'll show you a way to improve this by hard-coding all the data in one place and eliminating the need for any if or switch statements.  You should AT VERY LEAST change to switch statements, better still hard-code all the data in one place (below), better still get a database or CSV text file storing these values.

```<code>$data = array(
         array('mirza' => 'RUTHIE', 'mage' => '3', 'mquote' => 'I get to learn a lot of new things here, like sign language!', 'link' => 'http://www.google.com'),
         array(......
             );

$numbers = range(1, 36);
shuffle($numbers);
for ($m =0; $m<37; $m++){
     $index = $numbers[$m];
     $mirza[$m] = $data[$index]['mirza'];
     $mage[$m] = $data[$index]['mage'];
     $mquote[$m] = $data[$index]['mage'];
     $link[$m] = $data[$index]['link'];
 }
</code>```

Just to be clear, the 'efficiency' issue here isn't so much speed (though this way is faster).  Its that what you have is a nightmare to maintain and change.

You might do better to seriously reconsider the design of your app, specifically making an object with mirza, mage, mquote, link as fields.

Body:
So I have this for loop with 36 if-queries inside. Any advice on making it more efficient?
You can view the complete code  here

Here's a sample of what it looks like:

$numbers = range(1, 36);
shuffle($numbers);
for ($m =0; $m<37; $m++){
    if ($numbers[$m] == "1"){
        $mirza[$m] = "RUTHIE";
        $mage[$m] = "3";
        $mquote[$m] = "I get to learn a lot of new things here, like sign language!";
        $link[$m] = "http://www.google.com";
    }

    if ($numbers[$m] == "2"){
        $mirza[$m] = "AIDA";
        $mage[$m] = "82";
        $mquote[$m] = "This is like a club and I know and like all the members. It's good therapy.";
        $link[$m] = "/about/";
    }

    if ($numbers[$m] == "3"){
        $mirza[$m] = "AMIRE";
        $mage[$m] = "4";
        $mquote[$m] = "I am learning how to share and make friends.";
        $link[$m] = "/about/";
    }
}

Body:
When you have this much data it really should be in a database (maybe XML or document style) or a text file.

Still, I'll show you a way to improve this by hard-coding all the data in one place and eliminating the need for any if or switch statements.  You should AT VERY LEAST change to switch statements, better still hard-code all the data in one place (below), better still get a database or CSV text file storing these values.

$data = array(
         array('mirza' => 'RUTHIE', 'mage' => '3', 'mquote' => 'I get to learn a lot of new things here, like sign language!', 'link' => 'http://www.google.com'),
         array(......
             );

$numbers = range(1, 36);
shuffle($numbers);
for ($m =0; $m<37; $m++){
     $index = $numbers[$m];
     $mirza[$m] = $data[$index]['mirza'];
     $mage[$m] = $data[$index]['mage'];
     $mquote[$m] = $data[$index]['mage'];
     $link[$m] = $data[$index]['link'];
 }

Just to be clear, the 'efficiency' issue here isn't so much speed (though this way is faster).  Its that what you have is a nightmare to maintain and change.

You might do better to seriously reconsider the design of your app, specifically making an object with mirza, mage, mquote, link as fields.


问:
Sort array of objects by string property value
I have an array of JavaScript objects:

```<code>var objs = [
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];
</code>```

How can I sort them by the value of last_nom in JavaScript?

I know about sort(a,b), but that only seems to work on strings and numbers. Do I need to add a toString() method to my objects?

答:
Using Ramda,

npm install ramda

```<code>import R from 'ramda'
var objs = [
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];
var ascendingSortedObjs = R.sortBy(R.prop('last_nom'), objs)
var descendingSortedObjs = R.reverse(ascendingSortedObjs)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an array of JavaScript objects:

var objs = [
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];

How can I sort them by the value of last_nom in JavaScript?

I know about sort(a,b), but that only seems to work on strings and numbers. Do I need to add a toString() method to my objects?

Body:
Using Ramda,

npm install ramda

import R from 'ramda'
var objs = [
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];
var ascendingSortedObjs = R.sortBy(R.prop('last_nom'), objs)
var descendingSortedObjs = R.reverse(ascendingSortedObjs)


问:
Android - how to add new data to exiting unique key in firebase?
I want to add new data for child node that named "unique key" from "pibref.push().getkey". When I try to sign in first it works perfectly.
pic : my "dll dll" data inserted,
 but if I restart my app I get an error like this :

```<code>07-05 11:14:46.341 11765-11765/com.rintan.geistr.pib W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
07-05 11:14:46.346 11765-11765/com.rintan.geistr.pib W/System.err:     at com.rintan.geistr.pib.transfer.vdigital(transfer.java:161)
</code>```

.

```<code>public class SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,
    View.OnClickListener {
...
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_in);
    ...
    ...
    pibref = FirebaseDatabase.getInstance().getReference("Users");
    String key = pibref.push().getKey();

    Users = pibref.child(key);
}
public static DatabaseReference userkey(){
    DatabaseReference userr = new SignInActivity().Users;
    return userr;
}
</code>```

transfer.java

```<code>DatabaseReference UserKey = SignInActivity.userkey();
pibref_userkirim = UserKey.child("User_Transaksi");   //this is line 161
usr_tf = pibref_userkirim.child("Transfer");
usr_tf.child(stremailterima).setValue(transkirim);
</code>```

Help me please ... this is my semester project :'(

答:
Inside your override method of onComplete listenre do the following:

```<code>User user=new User();
user.setFirstName(firstname);
user.setLastname(lastname);

  mDatabase.child("UserNode").child(auth.getCurrentUser().getUid()).setValue(user, new DatabaseReference.CompletionListener() {
  @Override
   public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
      if(databaseError==null)
          {
              Log.e("final value", "Data is saved successfully");
          }
                 }
                   });
</code>```

declare this line on the top:

```<code> private DatabaseReference mDatabase;
</code>```

Hope it helps

Body:
I want to add new data for child node that named "unique key" from "pibref.push().getkey". When I try to sign in first it works perfectly.
pic : my "dll dll" data inserted,
 but if I restart my app I get an error like this :

07-05 11:14:46.341 11765-11765/com.rintan.geistr.pib W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
07-05 11:14:46.346 11765-11765/com.rintan.geistr.pib W/System.err:     at com.rintan.geistr.pib.transfer.vdigital(transfer.java:161)

.

public class SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,
    View.OnClickListener {
...
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_in);
    ...
    ...
    pibref = FirebaseDatabase.getInstance().getReference("Users");
    String key = pibref.push().getKey();

    Users = pibref.child(key);
}
public static DatabaseReference userkey(){
    DatabaseReference userr = new SignInActivity().Users;
    return userr;
}

transfer.java

DatabaseReference UserKey = SignInActivity.userkey();
pibref_userkirim = UserKey.child("User_Transaksi");   //this is line 161
usr_tf = pibref_userkirim.child("Transfer");
usr_tf.child(stremailterima).setValue(transkirim);

Help me please ... this is my semester project :'(

Body:
Inside your override method of onComplete listenre do the following:

User user=new User();
user.setFirstName(firstname);
user.setLastname(lastname);

  mDatabase.child("UserNode").child(auth.getCurrentUser().getUid()).setValue(user, new DatabaseReference.CompletionListener() {
  @Override
   public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
      if(databaseError==null)
          {
              Log.e("final value", "Data is saved successfully");
          }
                 }
                   });

declare this line on the top:

 private DatabaseReference mDatabase;

Hope it helps


问:
how can I make jqplot with selectable data points
This may be basic but I could not find an example or API to make the data point in a jqplot graph selectable. Highlighter seems to know when the mouse hovers a data point but does not make it selectable.</p>

答: You should use the plugin draggable.</p>

Body: You should use the plugin draggable.


问:
How to delete or disable Organization box from UserInfoPage?
Well, as the question says, is there any way to delete or disable organization box?

Here a screenshot:

答:
You can hide both Label and Edit box with CurPageChanged procedure in [Code] section.

[Code]
procedure CurPageChanged(CurPageID: Integer);
begin
  if CurPageID = wpUserInfo then begin
    WizardForm.UserInfoOrgLabel.Hide();
    WizardForm.UserInfoOrgEdit.Hide();
  end;
end;
```


问:
Action Mailer Not delivering Emails - MailCatcher and sendmail
I am using Rails 5. I have the following configurations in my config/environments/development.rb and config/environments/staging.rb.

config/environments/development.rb

```<code>config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { address: "localhost", port: 1025 }
</code>```

When I call the method that sends email, I get the following output.

```<code>Rendering mailer/consolidated_s3_storage_report.html.erb
Rendered mailer/consolidated_s3_storage_report.html.erb (0.4ms)
Mailer#consolidated_s3_storage_report: processed outbound mail in 17668.1ms
 => #<Mail::Message:86763960, Multipart: true, Headers: <From: mcds@sheridan.com>, <To: mcds.support@sheridan.com>, <Subject: 2017 July - S3 Storage Report>, <Mime-Version: 1.0>, <Content-Type: multipart/mixed; boundary="--==_mimepart_595c962cc36fb_1be1b2198436941"; charset=UTF-8>>
</code>```

But email is not delivered to my gmail. The 'from' address is 'default from' from which all other emails are sent. Please clarify why my emails are not delivered.

答:
You seem to be using Mailcatcher. Mailcatcher doesn't deliver messages, its to prevent messages from delivering to the actual To email addresses but lets you check of the message is framed correctly. Developers use Mailcatcher in development enviroments to see if the emails are rendered as they expect them to look like without spamming the To email holder.

All the emails that are sent to Mailcatcher can be viewed in a web interface. Visit http://localhost:1080 on your computer, you should be able to see all the emails you send so far from the development environment.

Body:
I am using Rails 5. I have the following configurations in my config/environments/development.rb and config/environments/staging.rb.

config/environments/development.rb

config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { address: "localhost", port: 1025 }

When I call the method that sends email, I get the following output.

Rendering mailer/consolidated_s3_storage_report.html.erb
Rendered mailer/consolidated_s3_storage_report.html.erb (0.4ms)
Mailer#consolidated_s3_storage_report: processed outbound mail in 17668.1ms
 => #<Mail::Message:86763960, Multipart: true, Headers: <From: mcds@sheridan.com>, <To: mcds.support@sheridan.com>, <Subject: 2017 July - S3 Storage Report>, <Mime-Version: 1.0>, <Content-Type: multipart/mixed; boundary="--==_mimepart_595c962cc36fb_1be1b2198436941"; charset=UTF-8>>

But email is not delivered to my gmail. The 'from' address is 'default from' from which all other emails are sent. Please clarify why my emails are not delivered.


问:
how to position myLocationButton google maps IOS
Currently, myLocationButton is buried behind a button, if you take a look at the button the myLocationButton is behind that button. How do I move the Y position of the myLocationButton?

答:
Use GMSMapView's padding to make this happen.

```<code>self.mapView.padding = UIEdgeInsetsMake(0, 0, 100, 0)
</code>```

Replace '100' with whatever space you want the location-button to be pushed up. You should probably replace it with the y-location of your book-button. For example:

```<code>let botPadding = self.view.frame.size.height - self.bookButton.frame.origin.y
self.mapView.padding = UIEdgeInsetsMake(0, 0, botPadding, 0)
</code>```

You can probably put this code wherever you want, maybe it'll work in viewDidLoad. But keep in mind that you'll have to call it again if your book-button is supposed to disappear at some point.
To make it dynamically placed, you could override viewDidLayoutSubviews or similar.

Body:
Use GMSMapView's padding to make this happen.

self.mapView.padding = UIEdgeInsetsMake(0, 0, 100, 0)

Replace '100' with whatever space you want the location-button to be pushed up. You should probably replace it with the y-location of your book-button. For example:

let botPadding = self.view.frame.size.height - self.bookButton.frame.origin.y
self.mapView.padding = UIEdgeInsetsMake(0, 0, botPadding, 0)

You can probably put this code wherever you want, maybe it'll work in viewDidLoad. But keep in mind that you'll have to call it again if your book-button is supposed to disappear at some point.
To make it dynamically placed, you could override viewDidLayoutSubviews or similar.


问:
Mantis cannot connect to SQL Server
I am trying to install Mantis 2.5.1 with PHP 7.0.15 and MS SQL Server 2012. The database is already created and user has db owner permission. Pre-installation check has no errors, but when I try to install database, I get an error as:

SQLState: 08001 Error Code: 67 Message: [Microsoft][ODBC Driver 11 for
  SQL Server]Named Pipes Provider: Could not open a connection to SQL
  Server [67]. ....A network-related or instance-specific error has
  occurred while establishing a connection to SQL Server. Server is not
  found or not accessible. Check if instance name is correct and if SQL
  Server is configured to allow remote connections. ...

I have checked the following already:

Named pipes is already enabled on sql server.

I have copied php_sqlsrv_7_nts_x64.dll and php_pdo_sqlsrv_7_nts_x64.dll to php extension directory, and enabled them as extensions in PHP manager in IIS 7.

Connection to sql server is possible with same credentials (tested using conn.udl)

Settings in config_defaults_inc.php

```<code>$g_hostname = 'Driver={SQLServer};SERVER=server;DATABASE=dbname;UID=username;PWD=password;';

$g_db_username = 'username';

$g_db_password = 'password';

$g_db_type = 'odbc_mssql';
</code>```

What could I be missing? Pls help.

答:
ensure that your instance is configured for SQL Server authentication.

If you change the auth mode, you need to restart the instance, which can be done in SSMS by right click to the instance name --> restart.

Title: Mantis cannot connect to SQL Server

Body:
I am trying to install Mantis 2.5.1 with PHP 7.0.15 and MS SQL Server 2012. The database is already created and user has db owner permission. Pre-installation check has no errors, but when I try to install database, I get an error as:

SQLState: 08001 Error Code: 67 Message: [Microsoft][ODBC Driver 11 for
  SQL Server]Named Pipes Provider: Could not open a connection to SQL
  Server [67]. ....A network-related or instance-specific error has
  occurred while establishing a connection to SQL Server. Server is not
  found or not accessible. Check if instance name is correct and if SQL
  Server is configured to allow remote connections. ...

I have checked the following already:

Named pipes is already enabled on sql server.

I have copied php_sqlsrv_7_nts_x64.dll and php_pdo_sqlsrv_7_nts_x64.dll to php extension directory, and enabled them as extensions in PHP manager in IIS 7.

Connection to sql server is possible with same credentials (tested using conn.udl)

Settings in config_defaults_inc.php

$g_hostname = 'Driver={SQLServer};SERVER=server;DATABASE=dbname;UID=username;PWD=password;';

$g_db_username = 'username';

$g_db_password = 'password';

$g_db_type = 'odbc_mssql';

What could I be missing? Pls help.


问:
MapKit overlay does not appear
I'm trying to add a circle overlay to my map. I followed the apple docs and got this far, but the overlay doesn't appear when I run the app. Here's my code...

```<code>@IBOutlet var map: MKMapView!
let location = CLLocationCoordinate2DMake(40.73085, -73.99750)
let regionRadius: CLLocationDistance = 5500

func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
    let diskRenderer: MKCircleRenderer = MKCircleRenderer.init()
    diskRenderer.fillColor = UIColor.init(red: 0, green: 192, blue: 295, alpha: 1)
    return diskRenderer
}

override func viewDidLoad() {
    super.viewDidLoad()

    let coordinateRegion = MKCoordinateRegionMakeWithDistance(location, regionRadius, regionRadius)
    map.setRegion(coordinateRegion, animated: true)
    let diskOverlay: MKCircle = MKCircle.init(centerCoordinate: location, radius: 5000)
    map.addOverlay(diskOverlay)

    // Do any additional setup after loading the view.
}
</code>```

I'm teaching myself all this stuff so forgive me if i've made an obvious mistake.

答:
objc in a class that is set as a mkmapviewdelegate:</p>

```<code>- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKPolygon class]]) {
        MKPolygon *polygon = (MKPolygon *)overlay;
        MKPolygonRenderer *renderer = [[MKPolygonRenderer alloc] initWithPolygon:polygon];
        renderer.strokeColor = [UIColor blueColor];
        renderer.lineWidth = 5.;
        return renderer;
    }
    return [[MKOverlayRenderer alloc] initWithOverlay:overlay];
}
</code>```

Title: MapKit overlay does not appear

Body:
I'm trying to add a circle overlay to my map. I followed the apple docs and got this far, but the overlay doesn't appear when I run the app. Here's my code...

@IBOutlet var map: MKMapView!
let location = CLLocationCoordinate2DMake(40.73085, -73.99750)
let regionRadius: CLLocationDistance = 5500

func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
    let diskRenderer: MKCircleRenderer = MKCircleRenderer.init()
    diskRenderer.fillColor = UIColor.init(red: 0, green: 192, blue: 295, alpha: 1)
    return diskRenderer
}

override func viewDidLoad() {
    super.viewDidLoad()

    let coordinateRegion = MKCoordinateRegionMakeWithDistance(location, regionRadius, regionRadius)
    map.setRegion(coordinateRegion, animated: true)
    let diskOverlay: MKCircle = MKCircle.init(centerCoordinate: location, radius: 5000)
    map.addOverlay(diskOverlay)

    // Do any additional setup after loading the view.
}

I'm teaching myself all this stuff so forgive me if i've made an obvious mistake.

Body:
objc in a class that is set as a mkmapviewdelegate:

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKPolygon class]]) {
        MKPolygon *polygon = (MKPolygon *)overlay;
        MKPolygonRenderer *renderer = [[MKPolygonRenderer alloc] initWithPolygon:polygon];
        renderer.strokeColor = [UIColor blueColor];
        renderer.lineWidth = 5.;
        return renderer;
    }
    return [[MKOverlayRenderer alloc] initWithOverlay:overlay];
}


问:
Add Part to Design Programmatically in Solidworks 2016
I've been trying to build an importer add-in. The user can open a file that outlines the various modifications to be applied to a standard part. I would like to pick out the standard part from the toolbox, and insert it, but I've been having trouble figuring it out.

I started working with the Toolbox API, but then realized it's for managing the contents in the toolbox, not inserting them. I've read the intro documentation on the other APIs, but none seem appropriate.

However, I did notice that the toolbox itself is an add-in, so would that mean I'll have to somehow communicate with it from my add-in? Perhaps this is more suited for a programmatic macro? I'm open to other solutions. Aside from these ideas I'm completely lost.

答:
I couldn't find anything useful in the API as well.
As a possible solution I can suggest loading toolbox files directly, for me they are located around

C:\SOLIDWORKS Data 2016\browser\AS\pins\parallel pins\split pin
  as.sldprt

Alternatively if you need more control you can work with toolbox database directly. You can find it here

C:\Program Files\SOLIDWORKS Corp\SOLIDWORKS\Toolbox\data
  utilities\lang\English\swbrowser.sldedb

Note that for current version of Solidworks it's SQLite file db, for older solidworks version it's MS Access file db.


问:
Draw a line in a bitmap (possibly with piston)
I want to draw a line in a bitmap, e.g. from pixel (10, 10) to pixel (90, 90). The line must have a specific width.

Using piston image, I am able to draw a single pixel:

```<code>let mut image = ImageBuffer::<image::Rgb<u8>>::new(100, 100);
image.get_pixel_mut(5, 5).data = [255, 255, 255];
image.save("output.png");
</code>```

However there is no method to draw a line.

I suppose I have to use piston::graphics for that, but I can’t find any ressource how to do it (any example involves a window that provides a context on which graphics works on).

答:
In addition to the great answer above: there is now direct support for drawing lines and many more shapes (even texts) in the imageproc library (see also the examples there):</p>

```<code>extern crate image;
extern crate imageproc;

use image::{Rgb, RgbImage};
use imageproc::drawing::draw_line_segment_mut;

fn main() {
    let mut img = RgbImage::new(100, 100);
    draw_line_segment_mut(
        &mut img,
        (5f32, 5f32),              // start point
        (95f32, 95f32),            // end point
        Rgb([69u8, 203u8, 133u8]), // RGB colors
    );
    img.save("output.png").unwrap();
}
</code>```

Body:
I want to draw a line in a bitmap, e.g. from pixel (10, 10) to pixel (90, 90). The line must have a specific width.

Using piston image, I am able to draw a single pixel:

let mut image = ImageBuffer::<image::Rgb<u8>>::new(100, 100);
image.get_pixel_mut(5, 5).data = [255, 255, 255];
image.save("output.png");

However there is no method to draw a line.

I suppose I have to use piston::graphics for that, but I can’t find any ressource how to do it (any example involves a window that provides a context on which graphics works on).

Body:
In addition to the great answer above: there is now direct support for drawing lines and many more shapes (even texts) in the imageproc library (see also the examples there):

extern crate image;
extern crate imageproc;

use image::{Rgb, RgbImage};
use imageproc::drawing::draw_line_segment_mut;

fn main() {
    let mut img = RgbImage::new(100, 100);
    draw_line_segment_mut(
        &mut img,
        (5f32, 5f32),              // start point
        (95f32, 95f32),            // end point
        Rgb([69u8, 203u8, 133u8]), // RGB colors
    );
    img.save("output.png").unwrap();
}


问:
HttpException (0x80004005): Request timed out ASP.Net
I just want to ask if theres a way to increase the executionTimeOut of a particular page? and not the whole application?</p>

```<code><configuration>
  <system.web>
   <httpRuntime executionTimeout="90" maxRequestLength="4096" useFullyQualifiedRedirectUrl="false"
minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" />
 </system.web>
</configuration>
</code>```

答:
put in Web Config File  </p>

```<code> <location path="Report.aspx">
    <system.web>
      <httpRuntime executionTimeout="3600" maxRequestLength="10240"/>
    </system.web>
  </location>
</code>```

Body:
I just want to ask if theres a way to increase the executionTimeOut of a particular page? and not the whole application?

<configuration>
  <system.web>
   <httpRuntime executionTimeout="90" maxRequestLength="4096" useFullyQualifiedRedirectUrl="false"
minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" />
 </system.web>
</configuration>

Body:
put in Web Config File

 <location path="Report.aspx">
    <system.web>
      <httpRuntime executionTimeout="3600" maxRequestLength="10240"/>
    </system.web>
  </location>


问:
passing iterators to lambda
I want to use the lambda expression for the following codes,

```<code>long long noOfways =0;
 auto dist =0;
 for(auto iter = noChocolets.begin()+1;iter!=noChocolets.end();iter++)
 {
     dist+=*(iter)-*(iter-1);
     noOfways+=  minOper(dist);
 }
</code>```

I particularly want to convert  for loop to a lambda expression. How can I do that?

答:
Try with std::accumulate.

```<code> accumulate(noChocolets.begin()+1, noChocolets.end(), noChocolets[0],
    [&](long long left, long long right){
        dist += right-left;
        noOfways += minOper(dist);
        return right;
    });
</code>```

Seems to work, although this is a strange and obscure solution. The original one is much cleaner if you ask me. I would consider this one to be an abuse of the accumulate method and DO NOT RECOMMEND to use it.

Working example

Title: passing iterators to lambda

Body:
I want to use the lambda expression for the following codes,

long long noOfways =0;
 auto dist =0;
 for(auto iter = noChocolets.begin()+1;iter!=noChocolets.end();iter++)
 {
     dist+=*(iter)-*(iter-1);
     noOfways+=  minOper(dist);
 }

I particularly want to convert  for loop to a lambda expression. How can I do that?

Body:
Try with std::accumulate.

 accumulate(noChocolets.begin()+1, noChocolets.end(), noChocolets[0],
    [&](long long left, long long right){
        dist += right-left;
        noOfways += minOper(dist);
        return right;
    });

Seems to work, although this is a strange and obscure solution. The original one is much cleaner if you ask me. I would consider this one to be an abuse of the accumulate method and DO NOT RECOMMEND to use it.

Working example


问:
Add multiple images in one with .Net Chart Controls
Written in power shell, I'm using .Net Chart Controls to create some charts, graphs. At the moment, I'm able to save those charts, graphs separately to each image file as the following:

```<code>$mailHash = @{"Email Set"=$emailPer;"No Email"=$noEmailPer}

$outFilePic= "C:\My Documents\Documents"

Function drawPie ($hash){

    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Windows.Forms.DataVisualization
    $Chart = New-object System.Windows.Forms.DataVisualization.Charting.Chart
    $ChartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea
    $Series = New-Object -TypeName System.Windows.Forms.DataVisualization.Charting.Series
    $ChartTypes = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]

    $Series.ChartType = $ChartTypes::Pie
    $Chart.Series.Add($Series)
    $Chart.ChartAreas.Add($ChartArea)
    $Chart.Series['Series1'].Points.DataBindXY($hash.keys, $hash.values)
    $Chart.Series[‘Series1’][‘PieLabelStyle’] = ‘Disabled’

    $Legend = New-Object System.Windows.Forms.DataVisualization.Charting.Legend
    $Legend.IsEquallySpacedItems = $True
    $Legend.BorderColor = 'Black'
    $Chart.Legends.Add($Legend)
    $chart.Series["Series1"].LegendText = "#VALX (#VALY%)"

    $Chart.Width = 700
    $Chart.Height = 400
    $Chart.Left = 10
    $Chart.Top = 10
    $Chart.BackColor = [System.Drawing.Color]::White
    $Chart.BorderColor = 'Black'
    $Chart.BorderDashStyle = 'Solid'

    $ChartTitle = New-Object System.Windows.Forms.DataVisualization.Charting.Title
    $ChartTitle.Text = 'Email '
    $Font = New-Object System.Drawing.Font @('Microsoft Sans Serif','12', [System.Drawing.FontStyle]::Bold)
    $ChartTitle.Font =$Font
    $Chart.Titles.Add($ChartTitle)
    $Chart.SaveImage($outFilePic, 'jpeg')
}
</code>```

Above is dynamic function to create to pie chart. Hence, many different charts will be created as well. How to save those in one image?

答:
Can you try the below version, I have added multiple series and legends to the same chart object (I have made series name fetching dynamic for this) and saved it:</p>

```<code>Function drawPie ($chart,$hash,$ChartT){

    $ChartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea
    $Series = New-Object -TypeName System.Windows.Forms.DataVisualization.Charting.Series

    $Series.ChartType = $ChartT
    $Chart.Series.Add($Series)
    $Chart.ChartAreas.Add($ChartArea)

    $Chart.Series[$series.name].Points.DataBindXY($hash.keys, $hash.values)
    $Chart.Series[$series.name][‘PieLabelStyle’] = ‘Disabled’
    $Chart.Series[$series.name].ChartArea = $ChartArea.name

    $Legend = New-Object System.Windows.Forms.DataVisualization.Charting.Legend
    $Legend.IsEquallySpacedItems = $True
    $Legend.BorderColor = 'Black'
    $Chart.Legends.Add($Legend)
    $chart.Series[$series.name].LegendText = "#VALX (#VALY%)"
    $chart.Series[$series.name].Legend = $Legend.name

}

$mailHash = @{"Email Set"=$emailPer;"No Email"=$noEmailPer}
#modify this path
$outFilePic= "d:\temp\stala.jpeg"
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Windows.Forms.DataVisualization
$Chart = New-object System.Windows.Forms.DataVisualization.Charting.Chart
$Chart.Width = 1400
$Chart.Height = 800
$Chart.Left = 10
$Chart.Top = 10
$Chart.BackColor = [System.Drawing.Color]::White
$Chart.BorderColor = 'Black'
$Chart.BorderDashStyle = 'Solid'
$ChartTypes = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]
$data = @{"10"="5";"20"="5";"30"="100";}
$data2 = @{"100"="1";"200"="49";"300"="50";}
drawPie $chart $data $ChartTypes::Pie
drawPie $chart $data2 $ChartTypes::Bar
$Chart.SaveImage($outFilePic, 'jpeg')
</code>```

Body:
Written in power shell, I'm using .Net Chart Controls to create some charts, graphs. At the moment, I'm able to save those charts, graphs separately to each image file as the following:

$mailHash = @{"Email Set"=$emailPer;"No Email"=$noEmailPer}

$outFilePic= "C:\My Documents\Documents"

Function drawPie ($hash){

    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Windows.Forms.DataVisualization
    $Chart = New-object System.Windows.Forms.DataVisualization.Charting.Chart
    $ChartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea
    $Series = New-Object -TypeName System.Windows.Forms.DataVisualization.Charting.Series
    $ChartTypes = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]

    $Series.ChartType = $ChartTypes::Pie
    $Chart.Series.Add($Series)
    $Chart.ChartAreas.Add($ChartArea)
    $Chart.Series['Series1'].Points.DataBindXY($hash.keys, $hash.values)
    $Chart.Series[‘Series1’][‘PieLabelStyle’] = ‘Disabled’

    $Legend = New-Object System.Windows.Forms.DataVisualization.Charting.Legend
    $Legend.IsEquallySpacedItems = $True
    $Legend.BorderColor = 'Black'
    $Chart.Legends.Add($Legend)
    $chart.Series["Series1"].LegendText = "#VALX (#VALY%)"

    $Chart.Width = 700
    $Chart.Height = 400
    $Chart.Left = 10
    $Chart.Top = 10
    $Chart.BackColor = [System.Drawing.Color]::White
    $Chart.BorderColor = 'Black'
    $Chart.BorderDashStyle = 'Solid'

    $ChartTitle = New-Object System.Windows.Forms.DataVisualization.Charting.Title
    $ChartTitle.Text = 'Email '
    $Font = New-Object System.Drawing.Font @('Microsoft Sans Serif','12', [System.Drawing.FontStyle]::Bold)
    $ChartTitle.Font =$Font
    $Chart.Titles.Add($ChartTitle)
    $Chart.SaveImage($outFilePic, 'jpeg')
}

Above is dynamic function to create to pie chart. Hence, many different charts will be created as well. How to save those in one image?

Body:
Can you try the below version, I have added multiple series and legends to the same chart object (I have made series name fetching dynamic for this) and saved it:

Function drawPie ($chart,$hash,$ChartT){

    $ChartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea
    $Series = New-Object -TypeName System.Windows.Forms.DataVisualization.Charting.Series

    $Series.ChartType = $ChartT
    $Chart.Series.Add($Series)
    $Chart.ChartAreas.Add($ChartArea)

    $Chart.Series[$series.name].Points.DataBindXY($hash.keys, $hash.values)
    $Chart.Series[$series.name][‘PieLabelStyle’] = ‘Disabled’
    $Chart.Series[$series.name].ChartArea = $ChartArea.name

    $Legend = New-Object System.Windows.Forms.DataVisualization.Charting.Legend
    $Legend.IsEquallySpacedItems = $True
    $Legend.BorderColor = 'Black'
    $Chart.Legends.Add($Legend)
    $chart.Series[$series.name].LegendText = "#VALX (#VALY%)"
    $chart.Series[$series.name].Legend = $Legend.name

}

$mailHash = @{"Email Set"=$emailPer;"No Email"=$noEmailPer}
#modify this path
$outFilePic= "d:\temp\stala.jpeg"
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Windows.Forms.DataVisualization
$Chart = New-object System.Windows.Forms.DataVisualization.Charting.Chart
$Chart.Width = 1400
$Chart.Height = 800
$Chart.Left = 10
$Chart.Top = 10
$Chart.BackColor = [System.Drawing.Color]::White
$Chart.BorderColor = 'Black'
$Chart.BorderDashStyle = 'Solid'
$ChartTypes = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]
$data = @{"10"="5";"20"="5";"30"="100";}
$data2 = @{"100"="1";"200"="49";"300"="50";}
drawPie $chart $data $ChartTypes::Pie
drawPie $chart $data2 $ChartTypes::Bar
$Chart.SaveImage($outFilePic, 'jpeg')


问:
terraform - how to add s3 Object Created trigger for lambda
How do I add a trigger to aws lambda using terraform?
the desired trigger is s3, object created all.

my terraform source code arouond the lambda is:

```<code>module "s3-object-created-lambda" {
  source = "../../../../../modules/lambda"
  s3_bucket = "${var.s3_lambda_bucket}"
  s3_key = "${var.s3_lambda_key}"
  name = "${var.lambda_some_name}"
  handler = "code.handler"
  env = {
    lambda_name = "${var.lambda_base_name}"
    lambda_version = "${var.lambda_version}"
  }
}
</code>```

trying to figure out how do I add the trigger.
via the aws console it is super simple.

答:
After some reading in:
https://www.terraform.io/docs/providers/aws/r/s3_bucket_notification.html

the solution is:

```<code>resource "aws_s3_bucket_notification" "bucket_notification" {
  bucket = "${data.terraform_remote_state.stack.bucket_id}"

  lambda_function {
    lambda_function_arn = "${module.some_lambda.lambda_arn}"
    events              = ["s3:ObjectCreated:*"]
    filter_prefix       = "${var.cluster_name}/somepath/"
    filter_suffix       = ".txt"
  }
}
</code>```

Body:
How do I add a trigger to aws lambda using terraform?
the desired trigger is s3, object created all.

my terraform source code arouond the lambda is:

module "s3-object-created-lambda" {
  source = "../../../../../modules/lambda"
  s3_bucket = "${var.s3_lambda_bucket}"
  s3_key = "${var.s3_lambda_key}"
  name = "${var.lambda_some_name}"
  handler = "code.handler"
  env = {
    lambda_name = "${var.lambda_base_name}"
    lambda_version = "${var.lambda_version}"
  }
}

trying to figure out how do I add the trigger.
via the aws console it is super simple.

Body:
After some reading in:
https://www.terraform.io/docs/providers/aws/r/s3_bucket_notification.html

the solution is:

resource "aws_s3_bucket_notification" "bucket_notification" {
  bucket = "${data.terraform_remote_state.stack.bucket_id}"

  lambda_function {
    lambda_function_arn = "${module.some_lambda.lambda_arn}"
    events              = ["s3:ObjectCreated:*"]
    filter_prefix       = "${var.cluster_name}/somepath/"
    filter_suffix       = ".txt"
  }
}


问:
Kendo grid editable false is not working
In my Kendo Grid I want to make a field not editable ,my data source is getting by a Ajax call, I did like the following but does not work:</p>

```<code>$("#turbingrid").kendoGrid({
    dataSource: result,
    scrollable: false,
schema: {
    model: {
        id: "DeviceIP",
        fields: {
            DeviceIP: {
                editable:false
            }
        }
    }
    columns: [
        { field: 'DeviceIP', title: 'DeviceIP', width: '100px'},
        { field: 'Producer', title: 'Producer', width: '80px'},
        editable: "popup"
});
</code>```

答:
You don't declare the schema attributes as part of the kendoGrid initialisation. These attributes belong to the dataSource.

Declare a kendo dataSource before your kendoGrid initilisation, using the data returned via Ajax, then use this dataSource in your kendoGrid, like the following:

```<code>var dataSource= new kendo.data.DataSource({
    data: result,
    schema: {
      model: {
        id: "DeviceIP",
        fields: {
            DeviceIP: {
                editable:false
            }
        }
      }
    }
});
</code>```

And the kendo grid initialisation code will look like (note you had declared the last part, columns and editable, incorrectly):

```<code>$("#turbingrid").kendoGrid({
    dataSource: dataSource,
    scrollable: false,
    columns: [
        { field: 'DeviceIP', title: 'DeviceIP', width: '100px'},
        { field: 'Producer', title: 'Producer', width: '80px'}
    ],
    editable: "popup"
});
</code>```

Body:
In my Kendo Grid I want to make a field not editable ,my data source is getting by a Ajax call, I did like the following but does not work:

$("#turbingrid").kendoGrid({
    dataSource: result,
    scrollable: false,
schema: {
    model: {
        id: "DeviceIP",
        fields: {
            DeviceIP: {
                editable:false
            }
        }
    }
    columns: [
        { field: 'DeviceIP', title: 'DeviceIP', width: '100px'},
        { field: 'Producer', title: 'Producer', width: '80px'},
        editable: "popup"
});

Body:
You don't declare the schema attributes as part of the kendoGrid initialisation. These attributes belong to the dataSource.

Declare a kendo dataSource before your kendoGrid initilisation, using the data returned via Ajax, then use this dataSource in your kendoGrid, like the following:

var dataSource= new kendo.data.DataSource({
    data: result,
    schema: {
      model: {
        id: "DeviceIP",
        fields: {
            DeviceIP: {
                editable:false
            }
        }
      }
    }
});

And the kendo grid initialisation code will look like (note you had declared the last part, columns and editable, incorrectly):

$("#turbingrid").kendoGrid({
    dataSource: dataSource,
    scrollable: false,
    columns: [
        { field: 'DeviceIP', title: 'DeviceIP', width: '100px'},
        { field: 'Producer', title: 'Producer', width: '80px'}
    ],
    editable: "popup"
});


问:
Laravel 5 how to get route action name?
I'm trying to get the current route action, but I'm not sure how to go about it. In Laravel 4 I was using Route::currentRouteAction() but now it's a bit different.

I'm trying to do Route::getActionName() in my controller but it keeps giving me method not found.

```<code><?php namespace App\Http\Controllers;

use Route;

class HomeController extends Controller
{
    public function getIndex()
    {
        echo 'getIndex';
        echo Route::getActionName();
    }
}
</code>```

答:
You may use to get the controller details form the request itself</p>

```<code>$request->route()->getAction()
</code>```

Title: Laravel 5 how to get route action name?

Body:
I'm trying to get the current route action, but I'm not sure how to go about it. In Laravel 4 I was using Route::currentRouteAction() but now it's a bit different.

I'm trying to do Route::getActionName() in my controller but it keeps giving me method not found.

<?php namespace App\Http\Controllers;

use Route;

class HomeController extends Controller
{
    public function getIndex()
    {
        echo 'getIndex';
        echo Route::getActionName();
    }
}

Body:
You may use to get the controller details form the request itself

$request->route()->getAction()


问:
What code analysis tools do you use for your Java projects?
What code analysis tools do you use on your Java projects?

I am interested in all kinds

static code analysis tools (FindBugs, PMD, and any others)

code coverage tools (Cobertura, Emma, and any others)

any other instrumentation-based tools

anything else, if I'm missing something

If applicable, also state what build tools you use and how well these tools integrate with both your IDEs and build tools.

If a tool is only available a specific way (as an IDE plugin, or, say, a build tool plugin) that information is also worth noting.

答: Checkstyle is another one I've used at a previous company... it's mainly for style checking, but it can do some static analysis too.  Also, Clover for code coverage, though be aware it is not a free tool.</p>

LastEditorDisplayName: Ned Batchelder