问:
html aligning inputs under each other
I'm trying to get the following snippet to work so that the selects are aligned exactly underneath each other.

Type:
<select style="width: 200px"></select>Created at:

Encoding:
<select style="width: 200px"></select>Updated at:

Collation: <select style=" width: 200px"></select>

```

As you can see it doesn't look quite right and I'm not sure how, I've been experimenting with stuff like display and box-sizing as you can see but none of these seem to have any effect, I also tried to align the text to the right which makes it a little better but it's still not perfect.

Any ideas?

答:
if you have a lot of items coming from loop for example

then you can use
 system like :

#test {
font:11px tahoma;
border-collapse: collapse;
text-align:center;
}

#test td {
padding: 1px 10px; margin:0;
text-align: center;
border:1px solid #faf0e6;
border-right:1px solid #d8d8d8;
}

#test td:first-child {
color:white;
background : orange;
width:30%;
}
#test td:nth-child(2) {
width:20%;
}
#test td:nth-child(3) {
text-align:left;
width:50%;
background : #f4f4f4 ;
}
select{
width:100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="test">
    <tr>
        <!--------->
        <td> Item 1  </td>
        <td> type : .mp4  </td>
        <td> <select></select> Created at: 2017</td>
    </tr>
    <tr>
        <!--------->
        <td> Item 2  </td>
        <td> type : .mov  </td>
        <td> <select></select> Created at: 2017</td>
    </tr>
    <tr>
        <!--------->
        <td> Item 3  </td>
        <td>type : .avi </td>
        <td> <select></select> Created at: 2017 </td>
    </tr>
</table></code>```

Title: html aligning inputs under each other

Body:
I'm trying to get the following snippet to work so that the selects are aligned exactly underneath each other.

Type:
<select style="width: 200px"></select>Created at:

Encoding:
<select style="width: 200px"></select>Updated at:

Collation: <select style=" width: 200px"></select>

As you can see it doesn't look quite right and I'm not sure how, I've been experimenting with stuff like display and box-sizing as you can see but none of these seem to have any effect, I also tried to align the text to the right which makes it a little better but it's still not perfect.

Any ideas?

Body:
if you have a lot of items coming from loop for example

then you can use <Table> system like :

#test {
font:11px tahoma;
border-collapse: collapse;
text-align:center;
}

#test td {
padding: 1px 10px; margin:0;
text-align: center;
border:1px solid #faf0e6;
border-right:1px solid #d8d8d8;
}

#test td:first-child {
color:white;
background : orange;
width:30%;
}
#test td:nth-child(2) {
width:20%;
}
#test td:nth-child(3) {
text-align:left;
width:50%;
background : #f4f4f4 ;
}
select{
width:100px;
}

<table id="test">
    <tr>
        <!--------->
        <td> Item 1  </td>
        <td> type : .mp4  </td>
        <td> <select></select> Created at: 2017</td>
    </tr>
    <tr>
        <!--------->
        <td> Item 2  </td>
        <td> type : .mov  </td>
        <td> <select></select> Created at: 2017</td>
    </tr>
    <tr>
        <!--------->
        <td> Item 3  </td>
        <td>type : .avi </td>
        <td> <select></select> Created at: 2017 </td>
    </tr>
</table>


来源: stackexchange

问:
Mysql database not showing the current date for NOW() function
I am using the NOW() with insert query so that I can get the currentTime when the query is triggered. But I get a time of 12 hours back in the database. How can I get the current Time ? Please help.</p>

答:
This might happen if the Timezone in your server configuration is different. Assuming that you are on a shared host, try adding the following lines when you are querying:

```<code>mysql_query("SET time_zone = '+05:30';");
</code>```

Source: http://wiki.dreamhost.com/Running_web_scripts_in_your_Timezone

Else try adding the following to your .htaccess file

```<code>SetEnv TZ Asia/Colombo
</code>```

A full list of all the Timezones http://www.php.net/manual/en/timezones.php

ContentLicense: CC BY-SA 2.5

Body:
This might happen if the Timezone in your server configuration is different. Assuming that you are on a shared host, try adding the following lines when you are querying:

mysql_query("SET time_zone = '+05:30';");

Source: http://wiki.dreamhost.com/Running_web_scripts_in_your_Timezone

Else try adding the following to your .htaccess file

SetEnv TZ Asia/Colombo

A full list of all the Timezones http://www.php.net/manual/en/timezones.php


问:
Webpack does not preserve symlinks in project path
I created a symlink for my "Dropbox (Personal)" folder so I could have an asset path without spaces. If I build my webpack project from a project there, however, it still uses the original path when running and referencing assets. I'm on OSX btw.

Current behavior

```<code>$ pwd
/Users/<me>/<SYMLINK>/<project>

$ webpack
> <project> dev /Users/<me>/<ORIGINAL>/<project>
</code>```

Desired behavior

```<code>$ pwd
/Users/<me>/<SYMLINK>/<project>

$ webpack
> <project> dev /Users/<me>/<SYMLINK>/<project>
</code>```

Does anyone know of a way to achieve the above? Thanks.

UPDATE

Turns out I needed to use a hard link for the Dropbox folder instead of a soft link. The soft link just meant it was basically an alias that always gets resolved to the real path. A hard link means it acts as an actual folder that contains links to the same data as the original. I used the following steps to do it properly:

Quit Dropbox app

$ mv "Dropbox (Personal)" Dropbox

$ ln -s Dropbox "Dropbox (Personal)"

I can now effectively use the Dropbox directory exactly the same as Dropbox Personal.

Also removing the webpack tag since the issue turned out to be unrelated to webpack.

答:
I think you need to enable symlinks - https://webpack.js.org/configuration/resolve/#resolve-symlinks</p>

```<code>resolve: {
  /* other stuff */
  symlinks: true
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I created a symlink for my "Dropbox (Personal)" folder so I could have an asset path without spaces. If I build my webpack project from a project there, however, it still uses the original path when running and referencing assets. I'm on OSX btw.

Current behavior

$ pwd
/Users/<me>/<SYMLINK>/<project>

$ webpack
> <project> dev /Users/<me>/<ORIGINAL>/<project>

Desired behavior

$ pwd
/Users/<me>/<SYMLINK>/<project>

$ webpack
> <project> dev /Users/<me>/<SYMLINK>/<project>

Does anyone know of a way to achieve the above? Thanks.

UPDATE

Turns out I needed to use a hard link for the Dropbox folder instead of a soft link. The soft link just meant it was basically an alias that always gets resolved to the real path. A hard link means it acts as an actual folder that contains links to the same data as the original. I used the following steps to do it properly:

Quit Dropbox app

$ mv "Dropbox (Personal)" Dropbox

$ ln -s Dropbox "Dropbox (Personal)"

I can now effectively use the Dropbox directory exactly the same as Dropbox Personal.

Also removing the webpack tag since the issue turned out to be unrelated to webpack.

Body:
I think you need to enable symlinks - https://webpack.js.org/configuration/resolve/#resolve-symlinks

resolve: {
  /* other stuff */
  symlinks: true
}


问:
Explanation of mobx observables
I've recently started exploring libraries for state management in JavaScript, and I came across Mobx. I've tried searching through the web unable to find an explanation about what those observables really are. I understand what they do, but I'd like a deeper understanding of how they work. As a library the observables obviously makes things easier for us without having to reason about them much, but I still feel like I'd like an explanation.

Is Mobx "just" an implementation of the observable pattern, or does it deviate in some manner?

答:
If you really want to know how something works, it's often best just to look at the code.

I'm no expert on the "observer pattern", but using @zvona's link it seems to me that "yes, mobx is just an implementation of the observer pattern."

Rationale based on that post:

Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

note that IObservable has a property named observers

Observers explicitly ask Observables to add them to the observer list the Observable maintains.

I'd say this is definitely something that happens in MobX via addObserver

Any new observer added to observable.observers array is of type IDerivation

Note the comment in that file pointing you to An in-depth explanation of MobX

Does [MobX] deviate [from the observer pattern] in some manner?

I already stated I'm not an expert in the textbook definition of the observer pattern. I couldn't find anything written by Michel Weststrate explicitly stating that MobX is an implementation of this pattern (not that I looked all that hard), but I'm going to go out on a limb and suggest that (like most JavaScript libraries) there is some deviation from the textbook. But I don't know if it's worth nitpicking those.

Title: Explanation of mobx observables


问:
Ionic: fast loading images
I am building a small app with Ionic 3 and angular 2/4

I have a problem to load a list of images from an URL (5MB per image)

It takes a lot of time to display my images.

How can I load images faster ?

There is any way to display images in low quality first ? (like Facebook and Whatsapp)

Any link, any tutorial, any blog ...

```<code>//js
private photo = "http://my-url.com";
private photo2 = "http://my-url-2.com";

//html
<div> <img [src]="photo"> </div>
<div> <img [src]="photo2"> </div>
</code>```

Thank you !

答:
The most convenient ways imho are:

compression - the first thing you need to ask yourself: Do I really need a 5mb image? Is it too big? Can it be compressed (e.g. jpeg/png)?

thumbnails - 1 (or more) version of the original image which are a lot smaller and therefore a lot faster to load. In many cases (e.g. list, overview) you don't even need the original image because the size of your img container is way smaller. So one way is to only load + display the size you need for that specific usecase. When you really need the 5mb version you could start with the thumbnail and replace it when the fullsize one is finished loading. This doesn't reduce the loading time, but feels way smoother.

preloading - you could preload the images (e.g. when you know they will be shown soon) to remove the slow loading part when your image is actually displayed.

caching - when your images don't change that much you might consider caching the images on your device. That way whenever you need to load a 5mb image for the second time (even after app restart) it takes the local copy instead of the remote one and can be shown almost instantly.

Ideally (and depending on your usecase) you combine all four things: Compressed images, different sized versions of your images, preloading when necessary and caching to make sure an image is only loaded once.

In my apps I'm using the simple but great plugin ionic-image-loader which I can highly recommend. It's easy to implement and covers 3. and 4. with almost no effort.

I hope I could help!

Title: Ionic: fast loading images

Body:
I am building a small app with Ionic 3 and angular 2/4

I have a problem to load a list of images from an URL (5MB per image)

It takes a lot of time to display my images.

How can I load images faster ?

There is any way to display images in low quality first ? (like Facebook and Whatsapp)

Any link, any tutorial, any blog ...

//js
private photo = "http://my-url.com";
private photo2 = "http://my-url-2.com";

//html

Thank you !


问:
How to test a Bean with @Validated
I would like to test the resilience of a Spring Bean which it loads the configuration from a YML file.

In a test, I load a corrupt configuration in order to test if the annotation @Validated run in the proper way:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ServiceExample.class})
@Category({Fast.class})
@ActiveProfiles("profileWithBadConfiguration")
public class ServiceExampleTest {

@Test(expected=IllegalStateException.class)
public void test1() {

}

}
</code>```

When I try to test execute the test "test1", the JUnit file crash before executing the first tests. The idea is to detect the IllegalStateException in a Test.

Anyone knows, how to test it?

Technical links:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/annotation/Validated.html
https://docs.spring.io/spring/docs/4.1.x/spring-framework-reference/html/validation.html

Many thanks in advance

Juan Antonio

答: Instead of using Springs test annotations, you could load contexts manually inside the test methods. Examples are given in answers to this question: Use different Spring test context configuration for different test methods</p>

Title: How to test a Bean with @Validated

Body:
I would like to test the resilience of a Spring Bean which it loads the configuration from a YML file.

In a test, I load a corrupt configuration in order to test if the annotation @Validated run in the proper way:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ServiceExample.class})
@Category({Fast.class})
@ActiveProfiles("profileWithBadConfiguration")
public class ServiceExampleTest {

@Test(expected=IllegalStateException.class)
public void test1() {

}

}

When I try to test execute the test "test1", the JUnit file crash before executing the first tests. The idea is to detect the IllegalStateException in a Test.

Anyone knows, how to test it?

Technical links:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/annotation/Validated.html
https://docs.spring.io/spring/docs/4.1.x/spring-framework-reference/html/validation.html

Many thanks in advance

Juan Antonio


问:
What's the problem in my code? c# winforms
I have two forms Login and Main form. Initially, the Login form will be displayed and when the user is authenticated, the Main form will be displayed and the Login form will be closed.

It's kinda working, but I have to click the btnLogin (a Button in the Login form) twice to close the Login form and show the Main form.

Here's my code.

Program.cs (Login form)

```<code>namespace Login
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Login fLogin = new Login();
            if (fLogin.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new Main());
            }
        }
    }
}
</code>```

Login form

```<code>namespace Login
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            // initially btnLogin has a DialogResult property set to None
            Authenticate();
        }

        private void Authenticate()
        {
            SqlCeConnection conn = new SqlCeConnection(@"Data source=d:/BIMS.sdf");
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand(Properties.Resources.CheckIfUserExists, conn);
            cmd.Parameters.Add("username", txtUsername.Text.Trim());
            cmd.Parameters.Add("password", txtPassword.Text.Trim());

            SqlCeDataReader dr = cmd.ExecuteReader();
            bool hasRow = dr.Read();
            if (hasRow)
            {
                btnLogin.DialogResult = DialogResult.OK;
            }
        }
    }
}
</code>```

Where do you think I'm doing it wrong?
Thanks....

答:
As stated in the prev post, might be an issue with Authenticate method...
May be it is taking a bit longer to access db..
Below code would help us know if the Authenticate has completed processing...

```<code>private void btnLogin_Click(object sender, EventArgs e)
{
      btnLogin.Enabled = false;

      // initially btnLogin has a DialogResult property set to None
      Authenticate();
      // better place call to Authenticate in try catch blocks
      // to prevent btnLogin in a disabled state forever if Authenticate fails with
      // an exception ...
      // also if an exception occurs show that in a message box

      btnLogin.Enabled = true;
}
</code>```

And in Main, once the user has been authenticated, close the Login form

```<code> Login fLogin = new Login();
            if (fLogin.ShowDialog() == DialogResult.OK)
            {
                fLogin.Close();
                Application.Run(new Main());
            }
</code>```

Body:
I have two forms Login and Main form. Initially, the Login form will be displayed and when the user is authenticated, the Main form will be displayed and the Login form will be closed.

It's kinda working, but I have to click the btnLogin (a Button in the Login form) twice to close the Login form and show the Main form.

Here's my code.

Program.cs (Login form)

namespace Login
{
    static class Program
    {
        ///
        /// The main entry point for the application.
        ///
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Login fLogin = new Login();
            if (fLogin.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new Main());
            }
        }
    }
}

Login form

namespace Login
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            // initially btnLogin has a DialogResult property set to None
            Authenticate();
        }

        private void Authenticate()
        {
            SqlCeConnection conn = new SqlCeConnection(@"Data source=d:/BIMS.sdf");
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand(Properties.Resources.CheckIfUserExists, conn);
            cmd.Parameters.Add("username", txtUsername.Text.Trim());
            cmd.Parameters.Add("password", txtPassword.Text.Trim());

            SqlCeDataReader dr = cmd.ExecuteReader();
            bool hasRow = dr.Read();
            if (hasRow)
            {
                btnLogin.DialogResult = DialogResult.OK;
            }
        }
    }
}

Where do you think I'm doing it wrong?
Thanks....

Body:
As stated in the prev post, might be an issue with Authenticate method...
May be it is taking a bit longer to access db..
Below code would help us know if the Authenticate has completed processing...

private void btnLogin_Click(object sender, EventArgs e)
{
      btnLogin.Enabled = false;

      // initially btnLogin has a DialogResult property set to None
      Authenticate();
      // better place call to Authenticate in try catch blocks
      // to prevent btnLogin in a disabled state forever if Authenticate fails with
      // an exception ...
      // also if an exception occurs show that in a message box

      btnLogin.Enabled = true;
}

And in Main, once the user has been authenticated, close the Login form

 Login fLogin = new Login();
            if (fLogin.ShowDialog() == DialogResult.OK)
            {
                fLogin.Close();
                Application.Run(new Main());
            }


问:
AWS S3 Presigned URL with other query parameters
I create a pre-signed URL and get back something like

```<code>https://s3.amazonaws.com/MyBucket/MyItem/
?X-Amz-Security-Token=TOKEN
&X-Amz-Algorithm=AWS4-HMAC-SHA256
&X-Amz-Date=20171206T014837Z
&X-Amz-SignedHeaders=host
&X-Amz-Expires=3600
&X-Amz-Credential=CREDENTIAL
&X-Amz-Signature=SIGNATURE
</code>```

I can now curl this no problem. However, if I now add another query parameter, I will get back a 403, i.e.

```<code>https://s3.amazonaws.com/MyBucket/MyItem/
?X-Amz-Security-Token=TOKEN
&X-Amz-Algorithm=AWS4-HMAC-SHA256
&X-Amz-Date=20171206T014837Z
&X-Amz-SignedHeaders=host
&X-Amz-Expires=3600
&X-Amz-Credential=CREDENTIAL
&X-Amz-Signature=SIGNATURE
&Foo=123
</code>```

How come? Is it possible to generate a pre-signed url that supports custom queries?

答:
If you change one of the headers or add / subtract, then you have to resign the URL.

This is part of the AWS signing design and this process is designed for higher levels of security. One of the AWS reasons for changing to signing version 4 from signing version 2.

The signing design does not know which headers are important and which are not. That would create a nightmare trying to track all of the AWS services.

Body:
I create a pre-signed URL and get back something like

https://s3.amazonaws.com/MyBucket/MyItem/
?X-Amz-Security-Token=TOKEN
&X-Amz-Algorithm=AWS4-HMAC-SHA256
&X-Amz-Date=20171206T014837Z
&X-Amz-SignedHeaders=host
&X-Amz-Expires=3600
&X-Amz-Credential=CREDENTIAL
&X-Amz-Signature=SIGNATURE

I can now curl this no problem. However, if I now add another query parameter, I will get back a 403, i.e.

https://s3.amazonaws.com/MyBucket/MyItem/
?X-Amz-Security-Token=TOKEN
&X-Amz-Algorithm=AWS4-HMAC-SHA256
&X-Amz-Date=20171206T014837Z
&X-Amz-SignedHeaders=host
&X-Amz-Expires=3600
&X-Amz-Credential=CREDENTIAL
&X-Amz-Signature=SIGNATURE
&Foo=123

How come? Is it possible to generate a pre-signed url that supports custom queries?


问:
VB.NET Add TabPage with Indexed Label
What are you trying to accomplish?

I want to add a TabPage to a pre-existing TabControl with a Label that has an indexed name.

```<code>    Private Sub BtnAddReport_Click(sender As Object, e As EventArgs) Handles BtnAddReport.Click

    Dim rep As New OpenFileDialog
    rep.Title = "Add Report"
    rep.InitialDirectory = "C:\Customers"
    rep.FileName = ""
    rep.DefaultExt = ".html"
    rep.Filter = "HTML Documents|*.html"
    rep.Multiselect = False
    If rep.ShowDialog() = DialogResult.OK Then

        Dim newTab As TabPage = New TabPage With {.Text = Path.GetFileName(rep.FileName)}
        TabControl2.Controls.Add(newTab)

        Dim i As Integer
        For i = 1 To TabControl2.TabPages.Count
            Dim lbl As Label = New Label With {.Text = "Label" & i, .Location = New Point(3, 3)}
            newTab.Controls.Add(lbl)
        Next

    End If

End Sub
</code>```

What do you expect the result to be?

Each time the button is clicked, a new tab is added with a label named "Label1", "Label2", etc.

What is the actual result you get?

This code creates a new tabpage and adds the label, but it's always named Label1 and does not increase by 1.

答:
Why do you have a For loop in there?  You only want to add one Label, right?  You should be creating one TabPage, creating one Label, adding the Label to the TabPage, then adding the TabPage to the TabControl.

```<code>Dim newTab As TabPage = New TabPage With {.Text = Path.GetFileName(rep.FileName)}
Dim lbl As Label = New Label With {.Text = "Label" & (TabControl2.TabPages.Count + 1), .Location = New Point(3, 3)}

newTab.Controls.Add(lbl)
TabControl2.TabPages.Add(newTab)
</code>```

Title: VB.NET Add TabPage with Indexed Label

Body:
What are you trying to accomplish?

I want to add a TabPage to a pre-existing TabControl with a Label that has an indexed name.

    Private Sub BtnAddReport_Click(sender As Object, e As EventArgs) Handles BtnAddReport.Click

    Dim rep As New OpenFileDialog
    rep.Title = "Add Report"
    rep.InitialDirectory = "C:\Customers"
    rep.FileName = ""
    rep.DefaultExt = ".html"
    rep.Filter = "HTML Documents|*.html"
    rep.Multiselect = False
    If rep.ShowDialog() = DialogResult.OK Then

        Dim newTab As TabPage = New TabPage With {.Text = Path.GetFileName(rep.FileName)}
        TabControl2.Controls.Add(newTab)

        Dim i As Integer
        For i = 1 To TabControl2.TabPages.Count
            Dim lbl As Label = New Label With {.Text = "Label" & i, .Location = New Point(3, 3)}
            newTab.Controls.Add(lbl)
        Next

    End If

End Sub

What do you expect the result to be?

Each time the button is clicked, a new tab is added with a label named "Label1", "Label2", etc.

What is the actual result you get?

This code creates a new tabpage and adds the label, but it's always named Label1 and does not increase by 1.

Body:
Why do you have a For loop in there?  You only want to add one Label, right?  You should be creating one TabPage, creating one Label, adding the Label to the TabPage, then adding the TabPage to the TabControl.

Dim newTab As TabPage = New TabPage With {.Text = Path.GetFileName(rep.FileName)}
Dim lbl As Label = New Label With {.Text = "Label" & (TabControl2.TabPages.Count + 1), .Location = New Point(3, 3)}

newTab.Controls.Add(lbl)
TabControl2.TabPages.Add(newTab)


问:
NoMethodError:undefined method `id' for nil:NilClass
I'm new to Rspec and I am trying to do the TDD. In the Application Controller, I have a method called set current user.

```<code>class ApplicationController < ActionController::Base
   protect_from_forgery with: :exception
   protected
    def set_current_user
      @current_user ||= User.find_by_session_token(cookies[:session_token])
      redirect_to login_path unless @current_user
    end
  end
</code>```

and here is the BlogsController.rb

```<code>class BlogsController < ApplicationController
  before_action :set_current_user
  before_action :has_user_and_hobby
  def blog_params
    params.require(:blog).permit(:title, :hobby_id, :user_id, :body, :rating)
  end

 ...

  def destroy
    @blog = Blog.find(params[:id])
    if @blog.user_id != @current_user.id
      flash[:notice] = "The blog #{@blog.title} only can be deleted by the author! It cannot be deleted by others."
      redirect_to hobby_blogs_path(@blog)
    else
      @blog.destroy
      flash[:notice] = "Blog '#{@blog.title}' deleted."
      redirect_back(fallback_location: root_path)
    end
  end
end
</code>```

And the rspec I wrote to test the destroy route is:

```<code>require 'spec_helper'
require 'rails_helper'

describe BlogsController do
    let(:fuser) { FactoryGirl.create(:fuser) }
    let(:hobby) { FactoryGirl.create(:hobby)}
    let(:blog) { FactoryGirl.create(:blog, hobby_id: hobby.id, user_id: fuser.id)}
    let(:comment) { FactoryGirl.create(:comment)}

...

    describe 'delete a blog' do
      before :each do
          allow_any_instance_of(ApplicationController).to receive(:set_current_user).and_return(fuser)
          allow_any_instance_of(BlogsController).to receive(:has_user_and_hobby).and_return(blog.user_id,hobby)
          allow(User).to receive(:find).with(blog.user_id).and_return(blog.user_id)

      it 'should redirect_back' do
          delete :destroy, params:{:hobby_id =>hobby.id, :id => blog.id}
          expect(response).to be_redirect
      end
   end
end
</code>```

When I try to run the spec, I get the error:

```<code>Failure/Error: if @blog.user_id != @current_user.id
 NoMethodError:
   undefined method `id' for nil:NilClass
</code>```

Does anyone know how to assist me in this? Greatly appreciate all the help.

答:
@current_user is nil in your test.

Your problem is here.

```<code>allow_any_instance_of(ApplicationController).to receive(:set_current_user).and_return(fuser)
</code>```

set_current_user doesn't actually return a user object, it assigns one to a @current_user variable and then possibly redirects.

It's much more the rails way do set your user in this manner:

```<code>class ApplicationController < ActionController::Base
  before_action :verify_current_user!

  def current_user
    @current_user || User.find_by_session_token(cookies[:session_token])
  end

  def verify_current_user!
    redirect_to login_path unless current_user
  end
end
</code>```

Then when referencing your currently signed in user, call the current_user method. The value will be memoized, so there is no performance penalty. You'll also be able to stub the current_user method as you are attempting in your test. In your controllers, always call current_user instead of @current_user.

Body:
I'm new to Rspec and I am trying to do the TDD. In the Application Controller, I have a method called set current user.

class ApplicationController < ActionController::Base
   protect_from_forgery with: :exception
   protected
    def set_current_user
      @current_user ||= User.find_by_session_token(cookies[:session_token])
      redirect_to login_path unless @current_user
    end
  end

and here is the BlogsController.rb

class BlogsController < ApplicationController
  before_action :set_current_user
  before_action :has_user_and_hobby
  def blog_params
    params.require(:blog).permit(:title, :hobby_id, :user_id, :body, :rating)
  end

 ...

  def destroy
    @blog = Blog.find(params[:id])
    if @blog.user_id != @current_user.id
      flash[:notice] = "The blog #{@blog.title} only can be deleted by the author! It cannot be deleted by others."
      redirect_to hobby_blogs_path(@blog)
    else
      @blog.destroy
      flash[:notice] = "Blog '#{@blog.title}' deleted."
      redirect_back(fallback_location: root_path)
    end
  end
end

And the rspec I wrote to test the destroy route is:

require 'spec_helper'
require 'rails_helper'

describe BlogsController do
    let(:fuser) { FactoryGirl.create(:fuser) }
    let(:hobby) { FactoryGirl.create(:hobby)}
    let(:blog) { FactoryGirl.create(:blog, hobby_id: hobby.id, user_id: fuser.id)}
    let(:comment) { FactoryGirl.create(:comment)}

...

    describe 'delete a blog' do
      before :each do
          allow_any_instance_of(ApplicationController).to receive(:set_current_user).and_return(fuser)
          allow_any_instance_of(BlogsController).to receive(:has_user_and_hobby).and_return(blog.user_id,hobby)
          allow(User).to receive(:find).with(blog.user_id).and_return(blog.user_id)

      it 'should redirect_back' do
          delete :destroy, params:{:hobby_id =>hobby.id, :id => blog.id}
          expect(response).to be_redirect
      end
   end
end

When I try to run the spec, I get the error:

Failure/Error: if @blog.user_id != @current_user.id
 NoMethodError:
   undefined method `id' for nil:NilClass

Does anyone know how to assist me in this? Greatly appreciate all the help.

Body:
@current_user is nil in your test.

Your problem is here.

allow_any_instance_of(ApplicationController).to receive(:set_current_user).and_return(fuser)

set_current_user doesn't actually return a user object, it assigns one to a @current_user variable and then possibly redirects.

It's much more the rails way do set your user in this manner:

class ApplicationController < ActionController::Base
  before_action :verify_current_user!

  def current_user
    @current_user || User.find_by_session_token(cookies[:session_token])
  end

  def verify_current_user!
    redirect_to login_path unless current_user
  end
end

Then when referencing your currently signed in user, call the current_user method. The value will be memoized, so there is no performance penalty. You'll also be able to stub the current_user method as you are attempting in your test. In your controllers, always call current_user instead of @current_user.


问:
How to load react/react-dom in a single html page?
React and/or react-dom are not loading properly.  But why not?

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src='babel.min.js'type='text/javascript'></script>
    <script src='react.js' type='text/javascript'></script>
    <script src='react-dom.js' type='text/javascript'></script>

    <script type="text/babel">

    class App extends React.Component {
        render() {
            return (
                <div>Hello world</div>
            );
        }
    }

    ReactDOM.render(
        <App />,
        document.getElementById('root')
    );
    </script>
</head>
<body>
    <div id="root">
    </div>
</body>
</html>
</code>```

The first complaint is
react.js:14 Uncaught ReferenceError: process is not defined
    at react.js:14

react.js and react-dom.js are both version 16.2.0

答:
You can use scripts hosted from a cdn like these...

```<code><script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</code>```

Just copy paste that and replace what you have... or if you want to host it on your own server, you can view source and copy paste them on a file. Also, please make sure that they're on the correct order.

You can also find a working example on this react guide - https://reactjs.org/docs/installation.html#creating-a-new-application

Hope this helps! Thank :)

UPDATE:

Other options you can do to setup React locally will be...

1.) Setup your local dev environment and workflow by using bundlers like Browserify or Webpack. For that you have to have knowledge with npm and webpack. Here's a good setup tutorial if you want to do it all by yourself - https://www.codecademy.com/articles/react-setup-i

2.) Use create-react-app, which is a quick starter kit from Facebook. Here's the link to their repo - https://github.com/facebookincubator/create-react-app

Body:
React and/or react-dom are not loading properly.  But why not?

<!DOCTYPE html>

    <meta charset="UTF-8">

The first complaint is
react.js:14 Uncaught ReferenceError: process is not defined
    at react.js:14

react.js and react-dom.js are both version 16.2.0

Body:
You can use scripts hosted from a cdn like these...

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

Just copy paste that and replace what you have... or if you want to host it on your own server, you can view source and copy paste them on a file. Also, please make sure that they're on the correct order.

You can also find a working example on this react guide - https://reactjs.org/docs/installation.html#creating-a-new-application

Hope this helps! Thank :)

UPDATE:

Other options you can do to setup React locally will be...

1.) Setup your local dev environment and workflow by using bundlers like Browserify or Webpack. For that you have to have knowledge with npm and webpack. Here's a good setup tutorial if you want to do it all by yourself - https://www.codecademy.com/articles/react-setup-i

2.) Use create-react-app, which is a quick starter kit from Facebook. Here's the link to their repo - https://github.com/facebookincubator/create-react-app


问:
Toggle Style Javascript
I am trying to write a simple toggle function in Javascript. What it does is take an element, a style name, and a desired value. If the current value of that style on the element is the empty string, that means it hasn't been set, so we set it to the given value. Otherwise, set it to the empty string to disable it.

My code is below:

```<code>function toggleStyle(el, styleName, value) {
  if (el.styleName === '')
  {
    el.styleName = value;
  }
  else
  {
    el.styleName = '';
  }
}
</code>```

However, I'm unsure how I call this function if I want to toggle the visbility of a box. I know to directly change the visibility: I would normally do:

```<code>var box = document.getElementById("box");
box.style.display = "none";
</code>```

But how would I call my toggleStyle to do this? I've tried writing:

```<code>toggleStyle (box, display, "none");
toggleStyle (box, style.display, "none");
toggleStyle (box.style, display, "none");
</code>```

but nothing seems to work.

答:
You should write it like this instead:

```<code>function toggleProp(obj, prop, value){
    obj[prop] = obj[prop] ? "" : value;
}

toggleProp(box.style, "display", "none");
</code>```

You should also learn how to use the debugger:

From this we can see that it was because the variable display is not defined before using it.

Title: Toggle Style Javascript

Body:
I am trying to write a simple toggle function in Javascript. What it does is take an element, a style name, and a desired value. If the current value of that style on the element is the empty string, that means it hasn't been set, so we set it to the given value. Otherwise, set it to the empty string to disable it.

My code is below:

function toggleStyle(el, styleName, value) {
  if (el.styleName === '')
  {
    el.styleName = value;
  }
  else
  {
    el.styleName = '';
  }
}

However, I'm unsure how I call this function if I want to toggle the visbility of a box. I know to directly change the visibility: I would normally do:

var box = document.getElementById("box");
box.style.display = "none";

But how would I call my toggleStyle to do this? I've tried writing:

toggleStyle (box, display, "none");
toggleStyle (box, style.display, "none");
toggleStyle (box.style, display, "none");

but nothing seems to work.

Body:
You should write it like this instead:

function toggleProp(obj, prop, value){
    obj[prop] = obj[prop] ? "" : value;
}

toggleProp(box.style, "display", "none");

You should also learn how to use the debugger:

From this we can see that it was because the variable display is not defined before using it.


问:
How to run for loop asynchronously with inquirer prompt
```<code>var fs = require("fs");
var inquirer = require("inquirer");
var words = ["ALPHA","BRAVO","CHARLIE","DELTA","ECHO","FOXTROT","GOLF","HOTEL","INDIA","JULIET","KILO","LIMA","MIKE","NOVEMBER","OSCAR","PAPA","QUEBEC","ROMEO","SIERRA","TANGO","UNIFORM","VICTOR","WHISKEY","XRAY","YANKEE","ZULU"];

function nodeMan() {
  var wrongs = 0;
  var lettersGuessed = [];
  var word = words[Math.floor(Math.random()*words.length)];
  var goldenBoy = word.split("");
  var blank = "_" * word.length;

  console.log(blank);

  for (var i = 0; wrongs < 10; i++) {
    var neem = "Question " + i;
    inquirer.prompt([{name: neem, message: "Guess a letter"}]).then(function(response) {
      console.log("print");
      lettersGuessed.push(resposne.name);
      if (response.name.length < 1 && lettersGuessed.indexOf(response.name)) {
        console.log(" first if statement cleared");
        for (var u = 0; u < goldenBoy.length; u++) {
          if (goldenBoy[u] === response.name) {
            blank[u] = response.name;
            console.log(blank);
          }
        }
      }
    })
  }
}
nodeMan();
</code>```

Trying to run this asynchronously. As of rn I get an infinite loop of "Guess a letter" prompts. Need help getting inquirer to shoot one question at a time instead of infinitely. Thanks for your time!

to set up a test folder don't forget to npm init and inquirer

答:
You can't use a for loop and need to use a recursion: inside the response to your question, you need to decide if you are going to ask another question and fire up that same question again (from within your callback).

Here is a basic code structure to get you going:

```<code>function nodeMan()
  let wrong = 0; // Store the number of wrong answers
  const askQuestion = () => {
    inquirer.prompt([{name: neem, message: "Guess a letter"}]).then((response) => {
      // Here check the answer and decide if you want to ask another question
      // [...]
      wrong++;
      // As long as less than 10 wrong answers, ask the question again
      if (wrong < 10) {
        // Ask the next question
        askQuestion (); // Recursion !
      }
    }
  };
  askQuestion();
}
nodeMan();
</code>```

Body:
var fs = require("fs");
var inquirer = require("inquirer");
var words = ["ALPHA","BRAVO","CHARLIE","DELTA","ECHO","FOXTROT","GOLF","HOTEL","INDIA","JULIET","KILO","LIMA","MIKE","NOVEMBER","OSCAR","PAPA","QUEBEC","ROMEO","SIERRA","TANGO","UNIFORM","VICTOR","WHISKEY","XRAY","YANKEE","ZULU"];

function nodeMan() {
  var wrongs = 0;
  var lettersGuessed = [];
  var word = words[Math.floor(Math.random()*words.length)];
  var goldenBoy = word.split("");
  var blank = "_" * word.length;

  console.log(blank);

  for (var i = 0; wrongs < 10; i++) {
    var neem = "Question " + i;
    inquirer.prompt([{name: neem, message: "Guess a letter"}]).then(function(response) {
      console.log("print");
      lettersGuessed.push(resposne.name);
      if (response.name.length < 1 && lettersGuessed.indexOf(response.name)) {
        console.log(" first if statement cleared");
        for (var u = 0; u < goldenBoy.length; u++) {
          if (goldenBoy[u] === response.name) {
            blank[u] = response.name;
            console.log(blank);
          }
        }
      }
    })
  }
}
nodeMan();

Trying to run this asynchronously. As of rn I get an infinite loop of "Guess a letter" prompts. Need help getting inquirer to shoot one question at a time instead of infinitely. Thanks for your time!

to set up a test folder don't forget to npm init and inquirer

Body:
You can't use a for loop and need to use a recursion: inside the response to your question, you need to decide if you are going to ask another question and fire up that same question again (from within your callback).

Here is a basic code structure to get you going:

function nodeMan()
  let wrong = 0; // Store the number of wrong answers
  const askQuestion = () => {
    inquirer.prompt([{name: neem, message: "Guess a letter"}]).then((response) => {
      // Here check the answer and decide if you want to ask another question
      // [...]
      wrong++;
      // As long as less than 10 wrong answers, ask the question again
      if (wrong < 10) {
        // Ask the next question
        askQuestion (); // Recursion !
      }
    }
  };
  askQuestion();
}
nodeMan();

ContentLicense: CC BY-SA 4.0


问:
TypeError when creating a new MatTable with Angular Material 2
I'm creating a table using mat-table (from MatTableModule) but I'm getting the following error:

```<code>ERROR TypeError: Cannot read property 'addClass' of undefined
  at MatHeaderCell.CdkHeaderCell (table.es5.js:275)
  at new MatHeaderCell (table.es5.js:132)
  at createClass (core.js:12166)
  at createDirectiveInstance (core.js:12011)
  at createViewNodes (core.js:13449)
  at createEmbeddedView (core.js:13327)
  at callWithDebugContext (core.js:14740)
  at Object.debugCreateEmbeddedView [as createEmbeddedView] (core.js:14070)
  at TemplateRef_.createEmbeddedView (core.js:11414)
  at ViewContainerRef_.createEmbeddedView (core.js:11130)
</code>```

The error in the console appears related to the first occurrence of <mat-header-cell *matHeaderCellDef> ID </mat-header-cell> tag.

I can't understand what is not working since the same code worked like a charm until yesterday evening.

The table in the component.html file

```<code><mat-table #table [dataSource]="dataSource" style="text-align:center">
    <!-- Id Column -->
    <ng-container matColumnDef="id">
        <mat-header-cell *matHeaderCellDef> ID </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.id}} </mat-cell>
    </ng-container>
    <!-- Creation date Column -->
    <ng-container matColumnDef="created">
        <mat-header-cell *matHeaderCellDef> Created </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.created}} </mat-cell>
    </ng-container>
    <!-- Device ID Column -->
    <ng-container matColumnDef="deviceId">
        <mat-header-cell *matHeaderCellDef> Device ID </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.deviceId}} </mat-cell>
    </ng-container>
    <!-- Failures Column -->
    <ng-container matColumnDef="failures">
        <mat-header-cell *matHeaderCellDef> No. Failures </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.failures}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</code>```

In my component TypeScript file I defined data as:

```<code>export class MyComponent implements OnInit {
  displayedColumns = ['id', 'created', 'deviceId', 'failures'];
  dataSource:MatTableDataSource<Element>;

  constructor() { }

  ngOnInit() {
    this.dataSource = new MatTableDataSource<Element>(ELEMENTS);
  }
}

export interface Element {
  id: string;
  created: string;
  deviceId: string;
  failures: number;
}
const ELEMENTS: Element[] = [
  {id: 'Hydrogen', created: "123", deviceId: "ABC123", failures: 0},
  {id: 'Helium', created: "123", deviceId: "123ABC", failures: 3},
  {id: 'Lithium', created: "123", deviceId: "ABCEF5", failures: 0},
  {id: 'Beryllium', created: "123", deviceId: "ABC123", failures: 2},
  {id: 'Boron', created: "123", deviceId: "67ABC3", failures: 0},
];
</code>```

So, apparently, data in TS and table cells in HTML are matched, what is causing this error to show up?

Update

Used library versions from package.json:

@angular/cdk: ^5.0.0-rc.1;

@angular/material: ^5.0.0-rc.2;

答:
In your package.json can you check the version of Angular material you have.
What ever version you have, make sure your @angular/cdk is the same version.

That is likely you problem. I believe the problem is you may have higher version of angular material probably "@angular/material": "5.0.0-rc.3" and in that version the renderer parameter passed to CdkHeaderCell is not being passed any longer and for that reason you have to update     "@angular/cdk": "5.0.0-rc.3" as well

Body:
I'm creating a table using mat-table (from MatTableModule) but I'm getting the following error:

ERROR TypeError: Cannot read property 'addClass' of undefined
  at MatHeaderCell.CdkHeaderCell (table.es5.js:275)
  at new MatHeaderCell (table.es5.js:132)
  at createClass (core.js:12166)
  at createDirectiveInstance (core.js:12011)
  at createViewNodes (core.js:13449)
  at createEmbeddedView (core.js:13327)
  at callWithDebugContext (core.js:14740)
  at Object.debugCreateEmbeddedView [as createEmbeddedView] (core.js:14070)
  at TemplateRef_.createEmbeddedView (core.js:11414)
  at ViewContainerRef_.createEmbeddedView (core.js:11130)

The error in the console appears related to the first occurrence of <mat-header-cell *matHeaderCellDef> ID </mat-header-cell> tag.

I can't understand what is not working since the same code worked like a charm until yesterday evening.

The table in the component.html file

<mat-table #table [dataSource]="dataSource" style="text-align:center">

    <ng-container matColumnDef="id">
        <mat-header-cell *matHeaderCellDef> ID </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.id}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="created">
        <mat-header-cell *matHeaderCellDef> Created </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.created}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="deviceId">
        <mat-header-cell *matHeaderCellDef> Device ID </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.deviceId}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="failures">
        <mat-header-cell *matHeaderCellDef> No. Failures </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.failures}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>

In my component TypeScript file I defined data as:

export class MyComponent implements OnInit {
  displayedColumns = ['id', 'created', 'deviceId', 'failures'];
  dataSource:MatTableDataSource<Element>;

  constructor() { }

  ngOnInit() {
    this.dataSource = new MatTableDataSource<Element>(ELEMENTS);
  }
}

export interface Element {
  id: string;
  created: string;
  deviceId: string;
  failures: number;
}
const ELEMENTS: Element[] = [
  {id: 'Hydrogen', created: "123", deviceId: "ABC123", failures: 0},
  {id: 'Helium', created: "123", deviceId: "123ABC", failures: 3},
  {id: 'Lithium', created: "123", deviceId: "ABCEF5", failures: 0},
  {id: 'Beryllium', created: "123", deviceId: "ABC123", failures: 2},
  {id: 'Boron', created: "123", deviceId: "67ABC3", failures: 0},
];

So, apparently, data in TS and table cells in HTML are matched, what is causing this error to show up?

Update

Used library versions from package.json:

@angular/cdk: ^5.0.0-rc.1;

@angular/material: ^5.0.0-rc.2;


问:
How to learn professional JavaScript in two days?
I really need to learn professional javascript in two days because I am gonna have to hit the
ground running (real world project). I have little which can be approximated to no knowledge of JavaScript or website development. Any help would be appreciated greatly.</p>

答:
This article is a great source of up to date, modern JavaScript resources:
http://blog.reybango.com/2010/12/15/what-to-read-to-get-up-to-speed-in-javascript/</p>


问:
Magento 2.2.1 unable to save product - error Narrowing occurred during type inference. Please file a bug report on bugs.php.net
Yesterday i updated a module and with the composer update command also some magento framework files were updated. After that saving a product after adjusting stock is not possible anymore, PhP error shows up:

```<code>Warning: Narrowing occurred during type inference. Please file a bug report on bugs.php.net in /home/jilco01/public_html/vendor/composer/ClassLoader.php on line 444 and product is not saved
</code>```

My magento 2.2.1 runs on Php 7.1.12 and with Opcache and Redis.

答:
This is not a solution to the bug of PHP 7.1.12, but can help you to avoid this warning while coming out a patch or a new version (I suppose it could be solved then).

The problem is with the OPCache library, that "... improves PHP performance by storing precompiled script bytecode in shared memory..." more info: http://php.net/manual/en/intro.opcache.php.

The "solution" is clear the cache when the application is loaded. This is easy if you have an "single entry point" application (when you use a framework, for example). Just put the next function at the beginin of your index.php (or equivalent) file:

```<code>opcache_reset();
</code>```

I'm not sure that this could be used in production servers, because could turn the application heavy.

Body:
Yesterday i updated a module and with the composer update command also some magento framework files were updated. After that saving a product after adjusting stock is not possible anymore, PhP error shows up:

Warning: Narrowing occurred during type inference. Please file a bug report on bugs.php.net in /home/jilco01/public_html/vendor/composer/ClassLoader.php on line 444 and product is not saved

My magento 2.2.1 runs on Php 7.1.12 and with Opcache and Redis.

Body:
This is not a solution to the bug of PHP 7.1.12, but can help you to avoid this warning while coming out a patch or a new version (I suppose it could be solved then).

The problem is with the OPCache library, that "... improves PHP performance by storing precompiled script bytecode in shared memory..." more info: http://php.net/manual/en/intro.opcache.php.

The "solution" is clear the cache when the application is loaded. This is easy if you have an "single entry point" application (when you use a framework, for example). Just put the next function at the beginin of your index.php (or equivalent) file:

opcache_reset();

I'm not sure that this could be used in production servers, because could turn the application heavy.


答:
Two things:

First, change your toggleStyle function so that it modifies the element's style property directly, and use bracket notation to dynamically access the property element of the style object:

```<code>function toggleStyle(el, styleName, value) {
    if (el.style[styleName] === '') {
        el.style[styleName] = value;
    } else {
        el.style[styleName] = '';
    }
}
</code>```

Second, pass a string of the style property when you use toggleStyle:

```<code>toggleStyle(box, "display", "none"); // display needs to be in quotes
</code>```

Title: Toggle Style Javascript

Body:
Two things:

First, change your toggleStyle function so that it modifies the element's style property directly, and use bracket notation to dynamically access the property element of the style object:

function toggleStyle(el, styleName, value) {
    if (el.style[styleName] === '') {
        el.style[styleName] = value;
    } else {
        el.style[styleName] = '';
    }
}

Second, pass a string of the style property when you use toggleStyle:

toggleStyle(box, "display", "none"); // display needs to be in quotes


问:
How to record screen with Android Studio
I connect my phone to Android Studio and code. I want to record my phone screen. I saw this but that button is disabled in my Android Studio. I can capture screens but can't record. Can someone help me with this?

UPDATE

This is how it is there in my Android studio. The button is disabled

答:
Maybe you should just change a phone,like this:

When using HUAWEI,the screen record is disabled:

But when changing to Nubia, it works!


问:
Memory configurations
I had a question about memory config.  I am running a 3 node cluster with Spark, Cassandra, Hadoop, Thrift and Yarn.  I want to store my files in hdfs, so i loaded hadoop.  I am finding that i am running out of memory when running my queries.  I was able to figure out how to restrict cassandra to run in less than 4gb.  Is there such a setting for hadoop?  How about Yarn?  As i only use hadoop to load up my flat files, i think setting it to 1 or 2gb should be fine.  My boxes have 32gb of ram and 16 cores each.   </p>

答:
It is hard to say without the error message you are facing. But if you want to check about allocation of memory at your workers you can setup these two configurations at your yarn-site.xml:

```<code><name>yarn.nodemanager.resource.memory-mb</name>
  <value>40960</value> <!-- 40 GB -->

<name>yarn.scheduler.maximum-allocation-mb</name> <!-Max RAM-per-container->
  <value>8192</value>
</code>```

You can see more details here in this question.

Title: Memory configurations

Body:
It is hard to say without the error message you are facing. But if you want to check about allocation of memory at your workers you can setup these two configurations at your yarn-site.xml:

<name>yarn.nodemanager.resource.memory-mb</name>
  <value>40960</value> <!-- 40 GB -->

<name>yarn.scheduler.maximum-allocation-mb</name> <!-Max RAM-per-container->
  <value>8192</value>

You can see more details here in this question.


问:
Can't submit apps to AppStore: ERROR ITMS-90534: "Invalid Toolchain

ERROR ITMS-90534: "Invalid Toolchain.

New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds." ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."

I found this error during upload IPA to account.

答: Apparently it was a deployment problem in Apple Servers. I tried after 3 hours and magically disappeared.</p>


问:
Adding Json Object into url
I want to be able to delete item based on the book_id.

```<code>tbody.insertAdjacentHTML('beforeend', '<tr><td>' + obj.book_id + '</td><td>' + <a href="delete_books?book_id=" + obj.book_id + >Delete</a> + '</td></tr>'
</code>```

I am not sure how to form the url. The link can't seem to work.
I want to be able to retrieve the id and delete in my  servlet file.

答:
good question, however, it is not advisable to base your delete request on a URL query which can be easily manipulated by others. Sending the json object through an AJAX call is a better practice.
- Notty Boi</p>

Title: Adding Json Object into url

Body:
I want to be able to delete item based on the book_id.

tbody.insertAdjacentHTML('beforeend', '
' + obj.book_id + '	' + Delete + '
'

I am not sure how to form the url. The link can't seem to work.
I want to be able to retrieve the id and delete in my  servlet file.


答: Seriously, two days is about enough to get a feel for the basics. It's nowhere near enough time to get to "professional" level (whatever that means exactly). The more experience you have with other languages, the easier it will be, though.

Title: How to learn professional JavaScript in two days?

Body:
I really need to learn professional javascript in two days because I am gonna have to hit the
ground running (real world project). I have little which can be approximated to no knowledge of JavaScript or website development. Any help would be appreciated greatly.


问:
How to connect google DialogFlow (free or enterprise) to a SIP PBX?
I am wondering if dialog flow can be connected to a SIP device, for a PBX system.

What needs to be done? What is missing?

Does dialog flow also include the voice recognition or is it only to analyze text and google voice does the recognition?

答:
Dialogflow offers integrations with phone services via Twilio for both their Programmable Chat and IP Messaging systems.

If that does not satisfy your requirements you can create your own SIP PBX integration using Dialogflow's query (v1) or detectIntent (v2) API to send user's querys from SIP PBX to your Dialogflow agent.  Dialogflow's v2 API includes support for audio requests (both streaming audio and audio files).


问:
EditText Reducing the layout above
I've looked for similar problems but couldn't finally solve mine

I have an editText on the bottom of my activity and a viewPager including a listView above it.

The problem is that the listView is minimized when I focus the editText or even hidden in landscape. When I click on the editText that it gets focused, it reduices the Fragment's height including the listView.

Despite the fact that my viewPager is constraintly attached to the editText and that the viewPager's Fragment is height set to match_parent, there is a huge gap between the listView and the bottom editText.

The only thing I see between the bottom editText and the listView is the viewPager's Background. So it's actually the fragment's layout that is resized.

I've noticed that the problem disappears when I set the editText's height to a constant value. The fact is that I need to let it on wrap_content because I'm using multilines property so I need the editText to expand.

What is completely crazy is that the gap between the two elements depends on the editText's hint lenght. In the screenshot below, it's set to "Message" but if I set a longer hint like "New message" the gap will be lot bigger !

Here is part of the activity's layout

```<code><android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="@color/colorAccent"
    app:layout_constraintBottom_toTopOf="@id/LayoutMsgBar"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/navigationBar" />

<android.support.constraint.ConstraintLayout
    android:id="@+id/LayoutMsgBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/darkGrey"
    android:focusableInTouchMode="true"
    android:theme="@style/msgBar"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@id/viewPager">

    <EditText
        android:id="@+id/editTextMsg"
        android:layout_width="0dip"
        android:layout_height="wrap_content"

        android:layout_weight="1"
        android:background="@android:color/transparent"
        android:hint="@string/nv_msg"
        android:inputType="textMultiLine|textCapSentences"

        android:maxLength="2000"
        android:maxLines="4"
        android:paddingBottom="10dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"

        android:paddingTop="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/sendButton"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toEndOf="@+id/moreButton"
        app:layout_constraintTop_toTopOf="parent" />
</code>```

and the Fragment layout that is called by the view pager

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:id="@+id/messagesListView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</ListView>
</code>```

What I have before I swipe or click on the editText

What I get after click on editText then reduce it

I've set the viewPager's background color to orange. It's not hidding the listView, it's below it.

My point is basically that my listView stays attached to the bottomBar, so to the editText

If you have an idea that would be awesome !

答:
Well, I solved it by replacing my bottom bar constraintLayout by a linear layout.
I don't get it, the constraints were right, but that worked.</p>

Title: EditText Reducing the layout above

Body:
I've looked for similar problems but couldn't finally solve mine

I have an editText on the bottom of my activity and a viewPager including a listView above it.

The problem is that the listView is minimized when I focus the editText or even hidden in landscape. When I click on the editText that it gets focused, it reduices the Fragment's height including the listView.

Despite the fact that my viewPager is constraintly attached to the editText and that the viewPager's Fragment is height set to match_parent, there is a huge gap between the listView and the bottom editText.

The only thing I see between the bottom editText and the listView is the viewPager's Background. So it's actually the fragment's layout that is resized.

I've noticed that the problem disappears when I set the editText's height to a constant value. The fact is that I need to let it on wrap_content because I'm using multilines property so I need the editText to expand.

What is completely crazy is that the gap between the two elements depends on the editText's hint lenght. In the screenshot below, it's set to "Message" but if I set a longer hint like "New message" the gap will be lot bigger !

Here is part of the activity's layout

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="@color/colorAccent"
    app:layout_constraintBottom_toTopOf="@id/LayoutMsgBar"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/navigationBar" />

<android.support.constraint.ConstraintLayout
    android:id="@+id/LayoutMsgBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/darkGrey"
    android:focusableInTouchMode="true"
    android:theme="@style/msgBar"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@id/viewPager">

    <EditText
        android:id="@+id/editTextMsg"
        android:layout_width="0dip"
        android:layout_height="wrap_content"

        android:layout_weight="1"
        android:background="@android:color/transparent"
        android:hint="@string/nv_msg"
        android:inputType="textMultiLine|textCapSentences"

        android:maxLength="2000"
        android:maxLines="4"
        android:paddingBottom="10dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"

        android:paddingTop="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/sendButton"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toEndOf="@+id/moreButton"
        app:layout_constraintTop_toTopOf="parent" />

and the Fragment layout that is called by the view pager

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:id="@+id/messagesListView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</ListView>

What I have before I swipe or click on the editText

What I get after click on editText then reduce it

I've set the viewPager's background color to orange. It's not hidding the listView, it's below it.

My point is basically that my listView stays attached to the bottomBar, so to the editText

If you have an idea that would be awesome !


问:
How Deadlock Happen resolved on Same Table insertion and update
I have a SSIS package with a task to load data. For some reason i need to update and insert same destination table. This happen deadlock

I use SSIS MULTI-CAST control.

What to do? how to resolve this situation?

答:
In your OLE DB Destination, change the access mode from "FastLoad" to "Table or View". The former will take a table lock which is generally better for large inserts but in your scenario, you need the table to remain "unlocked." Your performance will suffer since you'll be issuing singleton inserts but I guess that doesn't really matter since you'll also be doing singleton updates with your "OLE DB Command"

Finally, I think you're doing this wrong. The multicast essentially duplicates a row so that you can direct it to N components. I generally see people trying to detect whether a row exists in the target and then either insert or update it based on that lookup. But that's the lookup component, not a multicast. Maybe you're doing a type 2 dimension or something but even then, there will be better ways to accomplish this versus what you're showing in the picture.


问:
Mysql database not showing the current date for NOW() function
I am using the NOW() with insert query so that I can get the currentTime when the query is triggered. But I get a time of 12 hours back in the database. How can I get the current Time ? Please help.</p>

答:
I believe you can do, in your SQL query:

DATE_ADD(now(), INTERVAL 12 HOUR);

This will take the current time and <s>subtract</s> add 12 hours <s>from</s> to it.


问:
Configuring X-Frame-Options Response Header on AWS CloudFront and S3
I'd like to add X-Frame-Options HTTP response header for static content hosted on Amazon S3 with a Cloudfront cache. How can I add these headers?

答:
You can add the x-frame-options header to the response from CloudFront / S3 using a Lambda@Edge function. The lambda code runs within the local edge locations, but needs to be created and maintained in the us-east-1 region.

The example code here uses nodeJS 6.10 to add the response header

```<code>'use strict';
 exports.handler = (event, context, callback) => {
   const response = event.Records[0].cf.response;
   const headers = response.headers;
   response.headers['x-frame-options'] = [{"key":"X-Frame-Options","value":"SAMEORIGIN"}];
   console.log(response.headers);
   callback(null, response);
 };
</code>```

Create a definitive version of the Lambda, then set the Lambda Version's trigger configuration as the CloudFront origin-response Event type for your path pattern behavior.

The example code logs events to CloudWatch logs service for debugging purposes. If you don't already have one you will need to setup a lambda execution IAM role that allows a policy allowing CloudWatch logs actions to be assumed by edgelambda.amazonaws.com and lambda.amazonaws.com.

Basic Lambda Execution Policy allowing logs to be written to CloudWatch:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*",
            "Effect": "Allow"
        }
    ]
}
</code>```

Trust Relationship allowing Lambda and Lambda@Edge to assume the role :

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "edgelambda.amazonaws.com",
          "lambda.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
</code>```

It would be better if AWS simply allowed the x-frame-options header to be set in the GUI but until then this solution works and will allow you to keep your Security Auditors happy.

Body:
You can add the x-frame-options header to the response from CloudFront / S3 using a Lambda@Edge function. The lambda code runs within the local edge locations, but needs to be created and maintained in the us-east-1 region.

The example code here uses nodeJS 6.10 to add the response header

'use strict';
 exports.handler = (event, context, callback) => {
   const response = event.Records[0].cf.response;
   const headers = response.headers;
   response.headers['x-frame-options'] = [{"key":"X-Frame-Options","value":"SAMEORIGIN"}];
   console.log(response.headers);
   callback(null, response);
 };

Create a definitive version of the Lambda, then set the Lambda Version's trigger configuration as the CloudFront origin-response Event type for your path pattern behavior.

The example code logs events to CloudWatch logs service for debugging purposes. If you don't already have one you will need to setup a lambda execution IAM role that allows a policy allowing CloudWatch logs actions to be assumed by edgelambda.amazonaws.com and lambda.amazonaws.com.

Basic Lambda Execution Policy allowing logs to be written to CloudWatch:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*",
            "Effect": "Allow"
        }
    ]
}

Trust Relationship allowing Lambda and Lambda@Edge to assume the role :

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "edgelambda.amazonaws.com",
          "lambda.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

It would be better if AWS simply allowed the x-frame-options header to be set in the GUI but until then this solution works and will allow you to keep your Security Auditors happy.


问:
How to get code coverage of files not hit by our test cases, it shows only which are hit
We are working for getting code coverage by our test cases for the product. But the thing is that coverage tool does not show the files which are not at all hit.

We are using coverage command to run our processes like this:

coverage run -a --rcfile=/home/coveragerc -L

So we get a code coverage of 57%. Which has all the files which are hit. If a file is not hit then it is not included in coverage calculation. So it files which are not hit, are calculated, then actual coverage will be around 45%.

Please help how can I achieve it.

答: You want the --source option.  It specifies the root of the source tree, so coverage.py can find all the source files, and include them even if they were never run: http://coverage.readthedocs.io/en/coverage-4.4.2/source.html


答:
bracket notation is what you need and you need to pass strings.

function toggleStyle(el, styleName, value) {
  if (el.style[styleName] !== value) {  //better to check that it is not the value you have
    el.style[styleName] = value;
  } else {
    el.style[styleName] = '';
  }
}

var btn = document.querySelector("button")
var div = document.querySelector("#foo")
btn.addEventListener("click", function () {
  toggleStyle(div, "display", "none")
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button">Click Me</button>
<div id="foo">FOO</div></code>```

Where would this fail? Color codes are one thing, but this is the basic step in the right direction.

Title: Toggle Style Javascript

Body:
bracket notation is what you need and you need to pass strings.

function toggleStyle(el, styleName, value) {
  if (el.style[styleName] !== value) {  //better to check that it is not the value you have
    el.style[styleName] = value;
  } else {
    el.style[styleName] = '';
  }
}

var btn = document.querySelector("button")
var div = document.querySelector("#foo")
btn.addEventListener("click", function () {
  toggleStyle(div, "display", "none")
});

<button type="button">Click Me</button>
<div id="foo">FOO</div>

Where would this fail? Color codes are one thing, but this is the basic step in the right direction.


问:
Simple Vue.js with webpack
I know basically nothing about javascript/webpack/npm/whatever but I am trying a simple Vue.js app.

It looks like this:

index.html

```<code><!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Vue Test</title>
  </head>
  <body>
    <div class="vue-app">
      {{ message }}
    </div>
    <script src="/static/testvue.bundle.js"></script>
  </body>
</html>
</code>```

main.js

```<code>import Vue from 'vue';

new Vue({
    data: {
        message: 'Testing Vue'
    },
    el: '.vue-app'
});
</code>```

webpack.config.js

```<code>var path = require('path');

module.exports = {
    entry: './main.js',
    output: {
        filename: 'testvue.bundle.js',
        path: path.join(__dirname, '')
    },
    devServer: {
        inline: true,
        port: 8080
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',

                query: {
                    presets: ['es2015']
                }
            }
        ]
    }
};
</code>```

When I go to the webpage, it is blank and I see this in the "elements" in the console:

```<code><!--function (e,n,r,o){return Ce(t,e,n,r,o,!0)}-->
</code>```

Any idea what's going on and how to make it work? It's like it's trying to do something, but something doesn't line up. I've tried changing a few things that I have seen differently like using #vue-app instead of .vue-app or changing it to be under 'body' and then putting the {{message}} directly into the body but that doesn't help and I dont know what the difference is.

答:
You need to return message in data.

new Vue({
        data() {
            return {
              message: 'Testing Vue'
            }
        },
        el: '.vue-app'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.min.js"></script>
<!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Vue Test</title>
  </head>
  <body>
        <div class="vue-app">
      {{ message }}
        </div>
    <script src="/static/testvue.bundle.js"></script>
  </body>
</html></code>```

Title: Simple Vue.js with webpack

Body:
I know basically nothing about javascript/webpack/npm/whatever but I am trying a simple Vue.js app.

It looks like this:

index.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Vue Test</title>

      {{ message }}

main.js

import Vue from 'vue';

new Vue({
    data: {
        message: 'Testing Vue'
    },
    el: '.vue-app'
});

webpack.config.js

var path = require('path');

module.exports = {
    entry: './main.js',
    output: {
        filename: 'testvue.bundle.js',
        path: path.join(__dirname, '')
    },
    devServer: {
        inline: true,
        port: 8080
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',

                query: {
                    presets: ['es2015']
                }
            }
        ]
    }
};

When I go to the webpage, it is blank and I see this in the "elements" in the console:

Any idea what's going on and how to make it work? It's like it's trying to do something, but something doesn't line up. I've tried changing a few things that I have seen differently like using #vue-app instead of .vue-app or changing it to be under 'body' and then putting the {{message}} directly into the body but that doesn't help and I dont know what the difference is.

Body:
You need to return message in data.

new Vue({
        data() {
            return {
              message: 'Testing Vue'
            }
        },
        el: '.vue-app'
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.min.js"></script>
<!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Vue Test</title>
  </head>
  <body>
        <div class="vue-app">
      {{ message }}
        </div>
    <script src="/static/testvue.bundle.js"></script>
  </body>
</html>


问:
Alternative to direct calling of store.dispatch()
Since in the latest redux-observable (0.17) is direct calling of store.dispatch() deprecated, I wonder what is an alternative if I need to dispatch actions from the outside of my redux app.

Example:

Let's say I have this function which initialize native module and set up native handler.

```<code>const configure = (dispatch) => {
    const printingModule = NativeModules.PrintingManager
    const eventEmitter = new NativeEventEmitter(printingModule)

    eventEmitter.addListener(
        "PrintingManagerNewPrinterConnected",
        (payload) => dispatch({
            type: PRINTER_MANAGER_NEW_PRINTER_CONNECTED,
            payload: {
                macAddress: payload[2],
                connectionType: payload[3],
            },
        }))

    printingModule.initialize()
}
</code>```

What I typically do is that I will call this function from observable after something like APP_STARTUP_FINISHED:

```<code>const appStatePrepared = (action$: Object, { dispatch }) =>
    action$.ofType(APP_STATE_PREPARED)
        .switchMap(() => {
            configurePrinters(dispatch)
        })
</code>```

What is the correct solution for this?

Thanks!

答:
When using RxJS the ideal is to compose streams. So in this case we need to some how create a stream of "PrintingManagerNewPrinterConnected" events that we can then map each to their own PRINTER_MANAGER_NEW_PRINTER_CONNECTED action.a

Let's first learn how to do this completely custom.

Custom Observables

Creating your own custom Observables is very similar to creating a Promise. So say you had the most simple Promise in the world that just immediately resolves to the number 1

const items = new Promise(resolve => {
  resolve(1);
});
```

<p>The equivalent Observable looks super similar</p>

<pre class="lang-js prettyprint-override"><code>const items = new Observable(observer => {
  observer.next(1);
  observer.complete();
});
</code>```

Visually, the main differences are that instead of being passed (resolve, reject) callbacks we're given an Observer because there is next, error, and complete.

Semantically, Observables can represent more than one value by calling observer.next as many times as they'd like until they call observer.complete() to signal the end of the stream; this is in contrast to Promises, which only represent a single value.

Observables are also lazy and synchronous by default, whereas Promises are always eager and async.

Now that we have that understanding we want to take that and wrap your NativeEventEmitter API which uses addEventListener.

const configurePrinters = () => {
  return new Observable(observer => {
    const printingModule = NativeModules.PrintingManager;
    const eventEmitter = new NativeEventEmitter(printingModule);

    eventEmitter.addListener(
      'PrintingManagerNewPrinterConnected',
      (payload) => observer.next(payload)
    );

    printingModule.initialize();
  });
};

configurePrinters()
  .subscribe(payload => console.log(payload));
```

<p>This works and is super simple, but there's one problem with it: we should call <code>removeListener</code> when they unsubscribe so that we clean up after ourselves and don't leak memory.</p>

<p>To do that, we need to return a subscription inside our custom Observable. A subscription in this context is an object that has an <code>unsubscribe()</code> method on it, which will be called automatically when the subscriber unsubscribes, an error is triggered, or your observable completes. This is your chance to clean up.</p>

<pre class="lang-js prettyprint-override"><code>const items = new Observable(observer => {
  let i = 0;
  const timer = setInterval(() => {
    observer.next(i++);
  }, 1000);

  // return a subscription that has our timer cleanup logic
  return {
    unsubscribe: () => {
      clearInterval(timer);
    }
  };
});
</code>```

Because returning an object is a bit verbose RxJS supports a shorthand where you just return a function which itself will be treated as the unsubscribe method.

const items = new Observable(observer => {
  let i = 0;
  const timer = setInterval(() => {
    observer.next(i++);
  }, 1000);

  // return an "unsubscribe" function that has our timer cleanup logic
  return () => {
    clearInterval(timer);
  };
});
```

<p>Now we can apply this to our example, where we want to remove our listener when our unsubscribe teardown function is called.</p>

<pre class="lang-js prettyprint-override"><code>const configurePrinters = () => {
  return new Observable(observer => {
    const printingModule = NativeModules.PrintingManager;
    const eventEmitter = new NativeEventEmitter(printingModule);

    const listener = (payload) => observer.next(payload);

    eventEmitter.addListener(
      'PrintingManagerNewPrinterConnected',
      listener
    );

    printingModule.initialize();

    return () => eventEmitter.removeListener(
      'PrintingManagerNewPrinterConnected',
      listener
    );
  });
};
</code>```

Now let's turn this into a reusable utility function

const fromPrinterEvent = (eventName) => {
  return new Observable(observer => {
    const printingModule = NativeModules.PrintingManager;
    const eventEmitter = new NativeEventEmitter(printingModule);

    const listener = (payload) => observer.next(payload);
    eventEmitter.addListener(eventName, listener);
    printingModule.initialize();

    return () => eventEmitter.removeListener(eventName, listener);
  });
};

fromPrinterEvent('PrintingManagerNewPrinterConnected')
  .subscribe(payload => console.log(payload));
```

<h3>Observable.fromEvent</h3>

<p>While <code>NativeEventEmitter</code> is a react-native thing, it follows the node-style EventEmitter interface and RxJS already comes with a utility helper to create an Observable from them to save you the effort. It's called <code>fromEvent</code>, found at <code>Observable.fromEvent</code> or <code>import { fromEvent } from 'rxjs/observables/fromEvent'</code>.</p>

<pre class="lang-js prettyprint-override"><code>const fromPrinterEvent = (eventName) => {
  return Observable.defer(() => {
    const printingModule = NativeModules.PrintingManager;
    const eventEmitter = new NativeEventEmitter(printingModule);
    printingModule.initialize();

    return Observable.fromEvent(eventEmitter, eventName);
  });
};
</code>```

Here I also wrapped it in Observable.defer so that we don't create the NativeEventEmitter or printingModule.initialize() until someone actually subscribes (maintain laziness). This may or may not be neccesary for you, I don't know what PrintingManager does or how it behaves. e.g. it might be desirable to only create a single emitter and to initialize the module upfront.

const printingModule = NativeModules.PrintingManager;
const printerEmitter = new NativeEventEmitter(printingModule);
printingModule.initialize();

const fromPrinterEvent = (eventName) =>
  Observable.fromEvent(printerEmitter, eventName);
```

<p>So keep in mind that I'm just showing patterns without knowing what PrintingManager, etc does.</p>

<h2>Use it within redux-observable</h2>

<p>To use this within redux-observable and your epic is now the same as you'd use any other Observable. So we'll want to map the values from it to actions and
 mergeMap, switchMap, concatMap, or exhaustMap that into our top-level stream.</p>

<p>Something like this:</p>

<pre class="lang-js prettyprint-override"><code>const appStatePrepared = action$ =>
  action$.ofType(APP_STATE_PREPARED)
      .switchMap(() =>
        fromPrinterEvent('PrintingManagerNewPrinterConnected')
          .map(payload => ({
            type: PRINTER_MANAGER_NEW_PRINTER_CONNECTED,
            payload: {
              macAddress: payload[2],
              connectionType: payload[3],
            }
          }))
      );
</code>```

Remember that many streams, including our custom fromPrinterEvent('PrintingManagerNewPrinterConnected'), go forever until you unsubscribe from them. So if you only want one you'd use .take(1). If you want to unsubscribe when you receive another action you'd use .takeUntil(action$.ofType(WHATEVER)), etc. Normal RxJS patterns.

Body:
Since in the latest redux-observable (0.17) is direct calling of store.dispatch() deprecated, I wonder what is an alternative if I need to dispatch actions from the outside of my redux app.

Example:

Let's say I have this function which initialize native module and set up native handler.

const configure = (dispatch) => {
    const printingModule = NativeModules.PrintingManager
    const eventEmitter = new NativeEventEmitter(printingModule)

    eventEmitter.addListener(
        "PrintingManagerNewPrinterConnected",
        (payload) => dispatch({
            type: PRINTER_MANAGER_NEW_PRINTER_CONNECTED,
            payload: {
                macAddress: payload[2],
                connectionType: payload[3],
            },
        }))

    printingModule.initialize()
}

What I typically do is that I will call this function from observable after something like APP_STARTUP_FINISHED:

const appStatePrepared = (action$: Object, { dispatch }) =>
    action$.ofType(APP_STATE_PREPARED)
        .switchMap(() => {
            configurePrinters(dispatch)
        })

What is the correct solution for this?

Thanks!

Body:
When using RxJS the ideal is to compose streams. So in this case we need to some how create a stream of "PrintingManagerNewPrinterConnected" events that we can then map each to their own PRINTER_MANAGER_NEW_PRINTER_CONNECTED action.a

Let's first learn how to do this completely custom.

Custom Observables

Creating your own custom Observables is very similar to creating a Promise. So say you had the most simple Promise in the world that just immediately resolves to the number 1

const items = new Promise(resolve => {
  resolve(1);
});

The equivalent Observable looks super similar

const items = new Observable(observer => {
  observer.next(1);
  observer.complete();
});

Visually, the main differences are that instead of being passed (resolve, reject) callbacks we're given an Observer because there is next, error, and complete.

Semantically, Observables can represent more than one value by calling observer.next as many times as they'd like until they call observer.complete() to signal the end of the stream; this is in contrast to Promises, which only represent a single value.

Observables are also lazy and synchronous by default, whereas Promises are always eager and async.

Now that we have that understanding we want to take that and wrap your NativeEventEmitter API which uses addEventListener.

const configurePrinters = () => {
  return new Observable(observer => {
    const printingModule = NativeModules.PrintingManager;
    const eventEmitter = new NativeEventEmitter(printingModule);

    eventEmitter.addListener(
      'PrintingManagerNewPrinterConnected',
      (payload) => observer.next(payload)
    );

    printingModule.initialize();
  });
};

configurePrinters()
  .subscribe(payload => console.log(payload));

This works and is super simple, but there's one problem with it: we should call removeListener when they unsubscribe so that we clean up after ourselves and don't leak memory.

To do that, we need to return a subscription inside our custom Observable. A subscription in this context is an object that has an unsubscribe() method on it, which will be called automatically when the subscriber unsubscribes, an error is triggered, or your observable completes. This is your chance to clean up.

const items = new Observable(observer => {
  let i = 0;
  const timer = setInterval(() => {
    observer.next(i++);
  }, 1000);

  // return a subscription that has our timer cleanup logic
  return {
    unsubscribe: () => {
      clearInterval(timer);
    }
  };
});

Because returning an object is a bit verbose RxJS supports a shorthand where you just return a function which itself will be treated as the unsubscribe method.

const items = new Observable(observer => {
  let i = 0;
  const timer = setInterval(() => {
    observer.next(i++);
  }, 1000);

  // return an "unsubscribe" function that has our timer cleanup logic
  return () => {
    clearInterval(timer);
  };
});

Now we can apply this to our example, where we want to remove our listener when our unsubscribe teardown function is called.

const configurePrinters = () => {
  return new Observable(observer => {
    const printingModule = NativeModules.PrintingManager;
    const eventEmitter = new NativeEventEmitter(printingModule);

    const listener = (payload) => observer.next(payload);

    eventEmitter.addListener(
      'PrintingManagerNewPrinterConnected',
      listener
    );

    printingModule.initialize();

    return () => eventEmitter.removeListener(
      'PrintingManagerNewPrinterConnected',
      listener
    );
  });
};

Now let's turn this into a reusable utility function

const fromPrinterEvent = (eventName) => {
  return new Observable(observer => {
    const printingModule = NativeModules.PrintingManager;
    const eventEmitter = new NativeEventEmitter(printingModule);

    const listener = (payload) => observer.next(payload);
    eventEmitter.addListener(eventName, listener);
    printingModule.initialize();

    return () => eventEmitter.removeListener(eventName, listener);
  });
};

fromPrinterEvent('PrintingManagerNewPrinterConnected')
  .subscribe(payload => console.log(payload));

Observable.fromEvent

While NativeEventEmitter is a react-native thing, it follows the node-style EventEmitter interface and RxJS already comes with a utility helper to create an Observable from them to save you the effort. It's called fromEvent, found at Observable.fromEvent or import { fromEvent } from 'rxjs/observables/fromEvent'.

const fromPrinterEvent = (eventName) => {
  return Observable.defer(() => {
    const printingModule = NativeModules.PrintingManager;
    const eventEmitter = new NativeEventEmitter(printingModule);
    printingModule.initialize();

    return Observable.fromEvent(eventEmitter, eventName);
  });
};

Here I also wrapped it in Observable.defer so that we don't create the NativeEventEmitter or printingModule.initialize() until someone actually subscribes (maintain laziness). This may or may not be neccesary for you, I don't know what PrintingManager does or how it behaves. e.g. it might be desirable to only create a single emitter and to initialize the module upfront.

const printingModule = NativeModules.PrintingManager;
const printerEmitter = new NativeEventEmitter(printingModule);
printingModule.initialize();

const fromPrinterEvent = (eventName) =>
  Observable.fromEvent(printerEmitter, eventName);

So keep in mind that I'm just showing patterns without knowing what PrintingManager, etc does.

Use it within redux-observable

To use this within redux-observable and your epic is now the same as you'd use any other Observable. So we'll want to map the values from it to actions and
 mergeMap, switchMap, concatMap, or exhaustMap that into our top-level stream.

Something like this:

const appStatePrepared = action$ =>
  action$.ofType(APP_STATE_PREPARED)
      .switchMap(() =>
        fromPrinterEvent('PrintingManagerNewPrinterConnected')
          .map(payload => ({
            type: PRINTER_MANAGER_NEW_PRINTER_CONNECTED,
            payload: {
              macAddress: payload[2],
              connectionType: payload[3],
            }
          }))
      );

Remember that many streams, including our custom fromPrinterEvent('PrintingManagerNewPrinterConnected'), go forever until you unsubscribe from them. So if you only want one you'd use .take(1). If you want to unsubscribe when you receive another action you'd use .takeUntil(action$.ofType(WHATEVER)), etc. Normal RxJS patterns.