问:
CSS - Trying to apply styling to a class within a class within a modal popup
EDIT:
I have still not found a solution however i have managed to avoid the issue entirely. If someone know why this doesn't work it would be incredibly helpful so i know for the future. Thank you

-

I can't seem to get this to work and i've tried searching everywhere for an answer.

This is the gist of it (all nested within a modalPopup Panel.

```<code><div class="body">
<div>
     <div class="left">
         <asp:Label runat="server" Text="Name:" />
    </div>
     <div class="right">
         <asp:TextBox runat="server" ID="txtName" Text="" />
     </div>
</div>
</code>```

Also i should add that i can add styles to the body class with no issue.

I have tried these in CSS:

```<code>.modalPopup .body.left {}

.modalPopup .body .left {}

.modalPopup .body > left {}

.modalPopUp .body > .left {}
</code>```

And the same for the right class.

Am i missing something incredibly obvious?

I can give you more code/information if needed feel free to ask away.

Thank you in advance.

EDIT:

Here is all the Code

```<code>    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="smsBatchUI.Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolKit" %>

<!DOCTYPE html>
<link href="modalpopup.css" rel="stylesheet" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <div>
            <asp:Button ID="Button2" Text="Pop Up" runat="server" style="display:none" />
            <ajaxToolKit:ModalPopupExtender TargetControlID="Button2" ID="mp1" runat="server" PopupControlID="Panel1"
                    CancelControlID="ButtonCancel" BackgroundCssClass="modalBackground">
            </ajaxToolKit:ModalPopupExtender>
            <asp:Panel ID="Panel1" runat="server" style="display:normal" align="center" CssClass="modalPopup">
                <div class="header">
                    <header>
                        Batch SMS Messaging
                    </header>
                </div>
                <div class="body">
                    <asp:CheckBox ID="chkVerify" runat="server" style="display:none" Checked="false" AutoPostBack="true" /><br />

                    <div>
                        <div class="left">
                            <asp:Label runat="server" Text="Name:" />
                        </div>
                        <div class="right">
                            <asp:TextBox runat="server" ID="txtName" Text="" />
                        </div>
                    </div>

                    <div>
                        <div class="left">
                            <asp:Label runat="server" Text="Number:" />
                        </div>
                        <div class="right">
                            <asp:TextBox runat="server" ID="txtNo" />
                        </div>
                    </div>

                    <div>
                        <div class="left">
                            <asp:Label runat="server" Text="Message:  " />
                        </div>
                        <div class="right">
                            <asp:TextBox runat="server" ID="txtMessage" />
                        </div>
                    </div>

                    <div>
                        <div class="left">
                            <asp:Label runat="server" Text="Template: " />
                        </div>
                        <div class="right">
                            <asp:DropDownList runat="server" Width="200px" ID="ddlTemplate">
                                <asp:ListItem Text="Select Template" Value="DefaultValue"></asp:ListItem>
                                <asp:ListItem Text="HR" Value="HR"></asp:ListItem>
                                <asp:ListItem Text="CT" Value="CT"></asp:ListItem>
                                <asp:ListItem Text="IT" Value="IT"></asp:ListItem>
                            </asp:DropDownList>
                        </div>
                    </div>

                    <div>
                        <div class="left">
                            <asp:Label runat="server" Text="Send Date: " />
                        </div>
                        <div class="right">
                            <asp:TextBox runat="server" ID="txtDate" Text="YYYY-MM-DD" /><asp:Label runat="server" Text="(YYYY-MM-DD)" Font-Size="10px" />
                        </div>
                    </div>

                    <asp:Label runat="server" Text="Preview" style="padding-top: 0px" />
                    <br />
                    <asp:TextBox runat="server"  Height="150px" Width="300px" ID="txtPreview" Text="Click Preview to see your message before you Submit it." TextMode="MultiLine" /> <br />
                </div>
                <div class="footer">
                    <asp:Button runat="server" Text="Preview" ID="btnPreview" OnClientClick="Preview();" />
                    <asp:Button runat="server" Text="Submit" ID="btnSubmit" OnClick="btnSubmit_Click" OnClientClick="Validate()" /> <br />
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                    <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="btnUpload_Click" /> <br /> <br />
                    <asp:Button ID="ButtonCancel" runat="server" Text="Close" />
                </div>
            </asp:Panel>
        </div>
    </form>
</body>
</html>
</code>```

And the CSS:

```<code>body { color: #373d3f; }
.modalBackground
    {
        background-color: floralwhite;
        filter: alpha(opacity=60);
        opacity: 0.6;
    }
.modalPopup
    {
        background-color: #E8ECED;
        width: 400px;
        border:1px solid #666666;
        border-radius: 12px;
        padding:0
    }
.modalPopup .header
    {
        background-color: #014B96;
        height: 30px;
        color: White;
        line-height: 30px;
        text-align: center;
        font-weight: bold;
        border-top-left-radius: 8px;
        border-top-right-radius: 8px;
        font-family: Helvetica, Arial;
    }
.modalPopup .body
    {
        min-height: 50px;
        line-height: 30px;
        text-align: center;
        font-weight: bold;
        padding-left: 10px;
        padding-right: 10px;
        font-family: Helvetica, Arial;
        display: inline-block;
    }
.modalPopup > .body > .left
    {
        width: 30%;
        float: left;
        text-align: right;
    }
.modalPopup > .body >.right
    {
        width: 65%;
        margin-left: 10px;
        float:left;
    }
.modalPopup .buttonalignleft
    {
        text-align: left;
    }
.modalPopup .footer
    {
        padding: 6px;
    }
</code>```

答:
I hope that can help.

*{
margin:0;
padding: 0;

}

p{color:#fff;}
html,body{
width:100%;
height:100%;
}

.modalPopup{
position:relevant;
width:100%;
height:100%;
background-color:#fd3;
}

.modalPopup .body {
position:absolute;
width:90%;
height:90%;
background-color:#f00;
left:5%;
top:5%;
}

.modalPopup .body .left {
width:50%;
height:100%;
background-color:#0f0;
float:left;
}
.modalPopup .body .right {
width:50%;
height:100%;
background-color:#00f;
float:left;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="modalPopup">
<div class="body">
<div class="left">
<p>Left</p>
</div>
<div class="right">
<p>Right</p>
</div>
</div>
</div></code>```

Body:
EDIT:
I have still not found a solution however i have managed to avoid the issue entirely. If someone know why this doesn't work it would be incredibly helpful so i know for the future. Thank you

-

I can't seem to get this to work and i've tried searching everywhere for an answer.

This is the gist of it (all nested within a modalPopup Panel.

         <asp:Label runat="server" Text="Name:" />

         <asp:TextBox runat="server" ID="txtName" Text="" />

Also i should add that i can add styles to the body class with no issue.

I have tried these in CSS:

.modalPopup .body.left {}

.modalPopup .body .left {}

.modalPopup .body > left {}

.modalPopUp .body > .left {}

And the same for the right class.

Am i missing something incredibly obvious?

I can give you more code/information if needed feel free to ask away.

Thank you in advance.

EDIT:

Here is all the Code

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="smsBatchUI.Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolKit" %>

<!DOCTYPE html>
<link href="modalpopup.css" rel="stylesheet" />

    <title></title>

    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

            <asp:Button ID="Button2" Text="Pop Up" runat="server" style="display:none" />
            <ajaxToolKit:ModalPopupExtender TargetControlID="Button2" ID="mp1" runat="server" PopupControlID="Panel1"
                    CancelControlID="ButtonCancel" BackgroundCssClass="modalBackground">
            </ajaxToolKit:ModalPopupExtender>
            <asp:Panel ID="Panel1" runat="server" style="display:normal" align="center" CssClass="modalPopup">

                        Batch SMS Messaging

                    <asp:CheckBox ID="chkVerify" runat="server" style="display:none" Checked="false" AutoPostBack="true" />

                            <asp:Label runat="server" Text="Name:" />

                            <asp:TextBox runat="server" ID="txtName" Text="" />

                            <asp:Label runat="server" Text="Number:" />

                            <asp:TextBox runat="server" ID="txtNo" />

                            <asp:Label runat="server" Text="Message:  " />

                            <asp:TextBox runat="server" ID="txtMessage" />

                            <asp:Label runat="server" Text="Template: " />

                            <asp:DropDownList runat="server" Width="200px" ID="ddlTemplate">
                                <asp:ListItem Text="Select Template" Value="DefaultValue"></asp:ListItem>
                                <asp:ListItem Text="HR" Value="HR"></asp:ListItem>
                                <asp:ListItem Text="CT" Value="CT"></asp:ListItem>
                                <asp:ListItem Text="IT" Value="IT"></asp:ListItem>
                            </asp:DropDownList>

                            <asp:Label runat="server" Text="Send Date: " />

                            <asp:TextBox runat="server" ID="txtDate" Text="YYYY-MM-DD" /><asp:Label runat="server" Text="(YYYY-MM-DD)" Font-Size="10px" />

                    <asp:Label runat="server" Text="Preview" style="padding-top: 0px" />

                    <asp:TextBox runat="server"  Height="150px" Width="300px" ID="txtPreview" Text="Click Preview to see your message before you Submit it." TextMode="MultiLine" />

                    <asp:Button runat="server" Text="Preview" ID="btnPreview" OnClientClick="Preview();" />
                    <asp:Button runat="server" Text="Submit" ID="btnSubmit" OnClick="btnSubmit_Click" OnClientClick="Validate()" />

                    <asp:FileUpload ID="FileUpload1" runat="server" />
                    <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="btnUpload_Click" />

                    <asp:Button ID="ButtonCancel" runat="server" Text="Close" />

            </asp:Panel>

    </form>

And the CSS:

body { color: #373d3f; }
.modalBackground
    {
        background-color: floralwhite;
        filter: alpha(opacity=60);
        opacity: 0.6;
    }
.modalPopup
    {
        background-color: #E8ECED;
        width: 400px;
        border:1px solid #666666;
        border-radius: 12px;
        padding:0
    }
.modalPopup .header
    {
        background-color: #014B96;
        height: 30px;
        color: White;
        line-height: 30px;
        text-align: center;
        font-weight: bold;
        border-top-left-radius: 8px;
        border-top-right-radius: 8px;
        font-family: Helvetica, Arial;
    }
.modalPopup .body
    {
        min-height: 50px;
        line-height: 30px;
        text-align: center;
        font-weight: bold;
        padding-left: 10px;
        padding-right: 10px;
        font-family: Helvetica, Arial;
        display: inline-block;
    }
.modalPopup > .body > .left
    {
        width: 30%;
        float: left;
        text-align: right;
    }
.modalPopup > .body >.right
    {
        width: 65%;
        margin-left: 10px;
        float:left;
    }
.modalPopup .buttonalignleft
    {
        text-align: left;
    }
.modalPopup .footer
    {
        padding: 6px;
    }

Body:
I hope that can help.

*{
margin:0;
padding: 0;

}

p{color:#fff;}
html,body{
width:100%;
height:100%;
}

.modalPopup{
position:relevant;
width:100%;
height:100%;
background-color:#fd3;
}

.modalPopup .body {
position:absolute;
width:90%;
height:90%;
background-color:#f00;
left:5%;
top:5%;
}

.modalPopup .body .left {
width:50%;
height:100%;
background-color:#0f0;
float:left;
}
.modalPopup .body .right {
width:50%;
height:100%;
background-color:#00f;
float:left;}

<div class="modalPopup">
<div class="body">
<div class="left">
<p>Left</p>
</div>
<div class="right">
<p>Right</p>
</div>
</div>
</div>


来源: stackexchange

问:
Swipe event propagation with nested div doesn't work
Hi I've the following html structure:

```<code><div class="container">

        <div class="scroller">
            <div id ="goldenPage" class="page active">
                <div class="block text">
                    <div class="rich-text"></div>
                </div>
                <div class="block">
                    <div class="form"></div>
                </div>
                <div class="block">
                    <ul class="menu"></ul>
                </div>
            </div>
            <div id ="cachePage" class="page"></div>
        </div>

    </div>
</code>```

If I bind a swipe event on div with class container using code

```<code>var myElement = $(".container")[0];
            var hammertime = new Hammer(myElement);
            hammertime.on("swiperight",function(){
                console.debug(" manage swiperight event.");
                });
</code>```

and if I swipe nothing happen (except if I swipe on the bottom of my page because the internal div with scroller class is fewer height than parent div). If I bind the swipe on div with class scroller the swipe is correctly binded. The scroller div is binded with jquery scrollpane plugin.
Any ideas?!

答:
DEMO — Make sure your JavaScript/jQuery is fired after the document.ready event.

If the JavaScript fires before the element is available in the DOM, your JavaScript will not find the element, and thus be unable to bind the (swiperight) event to the element.

Using jQuery, this can be achieved by wrapping your JavaScript code in:

```<code>$(function() {
    // Your code here.
    console.log("Ready!");
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi I've the following html structure:

If I bind a swipe event on div with class container using code

var myElement = $(".container")[0];
            var hammertime = new Hammer(myElement);
            hammertime.on("swiperight",function(){
                console.debug(" manage swiperight event.");
                });

and if I swipe nothing happen (except if I swipe on the bottom of my page because the internal div with scroller class is fewer height than parent div). If I bind the swipe on div with class scroller the swipe is correctly binded. The scroller div is binded with jquery scrollpane plugin.
Any ideas?!

Body:
DEMO — Make sure your JavaScript/jQuery is fired after the document.ready event.

If the JavaScript fires before the element is available in the DOM, your JavaScript will not find the element, and thus be unable to bind the (swiperight) event to the element.

Using jQuery, this can be achieved by wrapping your JavaScript code in:

$(function() {
    // Your code here.
    console.log("Ready!");
});


问:
Regex : Everything in group except white space
I have this regex right here :

```<code>^(@include rem\(\s*(.*)),\s*(.*)\)
</code>```

That matches this string :

```<code>@include rem( padding-top, $alert-padding );
</code>```

I want to be able that the group with $alert-padding ignores the white space at the end. I tried doing :

```<code>^(@include rem\(\s*(.*)),\s*(/S)\)
</code>```

replace the .* by /S but it doesn't match.

You can play around with the regex here :
https://regex101.com/r/9rouVU/1/

答:
You may use \S+ to match 1 or more non-whitespace characters:

```<code>^(@include rem\(\s*(\S+))\s*,\s*(\S+)\s*\)
</code>```

See the regex dem0

Details:

^  - start of string

(@include rem\(\s*(\S+)) - Group 1 capturing:

@include rem\( - a literal substring @include rem(

\s* - 0+ whitespaces

(\S+) - Group 2 capturing 1+ non-whitespace symbols

\s*,\s* - 0+ whitespaces, , and again 0+ whitespaces

(\S+) - 1+ non-whitespace symbols

\s*  - 0+ whitespaces

\) - a literal ).

Body:
I have this regex right here :

^(@include rem\(\s*(.*)),\s*(.*)\)

That matches this string :

@include rem( padding-top, $alert-padding );

I want to be able that the group with $alert-padding ignores the white space at the end. I tried doing :

^(@include rem\(\s*(.*)),\s*(/S)\)

replace the .* by /S but it doesn't match.

You can play around with the regex here :
https://regex101.com/r/9rouVU/1/

Body:
You may use \S+ to match 1 or more non-whitespace characters:

^(@include rem\(\s*(\S+))\s*,\s*(\S+)\s*\)

See the regex dem0

Details:

^  - start of string

(@include rem\(\s*(\S+)) - Group 1 capturing:

@include rem\( - a literal substring @include rem(

\s* - 0+ whitespaces

(\S+) - Group 2 capturing 1+ non-whitespace symbols

\s*,\s* - 0+ whitespaces, , and again 0+ whitespaces

(\S+) - 1+ non-whitespace symbols

\s*  - 0+ whitespaces

\) - a literal ).


问:
How can I get the current session information from express-session?
I am using express-session to store my session data for my Node app as follows:

```<code>import express from 'express';
import session from 'express-session';
import connectRedis from 'connect-redis';

const app = express();
const RedisStore = connectRedis(session);

app.use(session({
    secret: 'keyboard kat',
    store: new RedisStore({
        url: '//redis:6379',
    }),
    resave: false,
    saveUninitialized: false,
    proxy: true,
    cookie: {
        secure: true,
    },
}));
</code>```

and I'm trying to get the information of the current session in the browser. I tried typing session in the console to no avail. Similarly, adding a console.log(session) below where I set up use of the session in the app doesn't work. How can I get the current session information from express-session?

答:
You can simply use your app with a function that references the session

```<code>app.use(function (req, res, next) {
    console.log(req.session)
})
</code>```

but it will print to the command line running your Node server rather than the console of the browser.

Body:
I am using express-session to store my session data for my Node app as follows:

import express from 'express';
import session from 'express-session';
import connectRedis from 'connect-redis';

const app = express();
const RedisStore = connectRedis(session);

app.use(session({
    secret: 'keyboard kat',
    store: new RedisStore({
        url: '//redis:6379',
    }),
    resave: false,
    saveUninitialized: false,
    proxy: true,
    cookie: {
        secure: true,
    },
}));

and I'm trying to get the information of the current session in the browser. I tried typing session in the console to no avail. Similarly, adding a console.log(session) below where I set up use of the session in the app doesn't work. How can I get the current session information from express-session?

Body:
You can simply use your app with a function that references the session

app.use(function (req, res, next) {
    console.log(req.session)
})

but it will print to the command line running your Node server rather than the console of the browser.


问:
Cannot restore variables from saved variables, TensorFlow 1.0, python 3.5.1
I new to tensorflow, when I try to restore saved parameters from saved variables I got "NotFoundError: Key b_1 not found in checkpoint" the complete code is at below. Thank you for your help!

```<code>import tensorflow as tf
import numpy as np
## save to a file
## need to use the same shape and dtype when restore
W = tf.Variable([[1,2,3],[3,4,5]], dtype=tf.float32, name='W')
b = tf.Variable([[1,2,3]],dtype=tf.float32, name='b')

# initialization
init = tf.global_variables_initializer()
saver = tf.train.Saver()

with tf.Session() as sess:
    sess.run(init)
    saver.save(sess, 'C:\Temp\TensorFlow\save\save.ckpt')
</code>```

Below is the restore part:
    ## restore variables

```<code>W = tf.Variable(np.arange(6).reshape((2,3)), dtype=tf.float32, name='W')
b = tf.Variable(np.arange(3).reshape((1,3)), dtype=tf.float32, name='b')

saver = tf.train.Saver()
with tf.Session() as sess:
    saver.restore(sess, 'C:\Temp\TensorFlow\save\save.ckpt')
    print('weights', sess.run(W))
    print('biases', sess.run(b))
</code>```

答:
The default behavior of tf.train.Saver is to save (or restore) every variable in tf.all_variables() (in addition to any other "saveable objects") using their name property as a key.

I suspect that if you print out W.name and b.name in the restore part of your program, you will get "W_1" and "b_1". Why do you get these names when you specified name='W' and name='b'? There must have already been variables with those names in the current TensorFlow graph, and so TensorFlow assumes that you were intentionally creating new variables, and appends a suffix ("_1", "_2", etc.) to make the name unique. For example, if you ran the two code fragments from your question one after the other in the same script (or Jupyter notebook), you would see this problem.

There are a few ways to avoid this problem:

An easy but crude way is to call tf.reset_default_graph() before the restore part of your program. This resets the current graph to being empty, so the variables will end up having the names "W" and "b" as you intended.

You can achieve a similar effect by wrapping the restore part in a with tf.Graph().as_default(): block, which ensures the variables are created in an empty graph.

You can override the mapping between variables in the checkpoint and tf.Variable objects by passing a var_list argument to the tf.train.Saver constructor as follows:

```<code>saver = tf.train.Saver(var_list={"W": W, "b", b})
</code>```

Body:
I new to tensorflow, when I try to restore saved parameters from saved variables I got "NotFoundError: Key b_1 not found in checkpoint" the complete code is at below. Thank you for your help!

import tensorflow as tf
import numpy as np
## save to a file
## need to use the same shape and dtype when restore
W = tf.Variable([[1,2,3],[3,4,5]], dtype=tf.float32, name='W')
b = tf.Variable([[1,2,3]],dtype=tf.float32, name='b')

# initialization
init = tf.global_variables_initializer()
saver = tf.train.Saver()

with tf.Session() as sess:
    sess.run(init)
    saver.save(sess, 'C:\Temp\TensorFlow\save\save.ckpt')

Below is the restore part:
    ## restore variables

W = tf.Variable(np.arange(6).reshape((2,3)), dtype=tf.float32, name='W')
b = tf.Variable(np.arange(3).reshape((1,3)), dtype=tf.float32, name='b')

saver = tf.train.Saver()
with tf.Session() as sess:
    saver.restore(sess, 'C:\Temp\TensorFlow\save\save.ckpt')
    print('weights', sess.run(W))
    print('biases', sess.run(b))

Body:
The default behavior of tf.train.Saver is to save (or restore) every variable in tf.all_variables() (in addition to any other "saveable objects") using their name property as a key.

I suspect that if you print out W.name and b.name in the restore part of your program, you will get "W_1" and "b_1". Why do you get these names when you specified name='W' and name='b'? There must have already been variables with those names in the current TensorFlow graph, and so TensorFlow assumes that you were intentionally creating new variables, and appends a suffix ("_1", "_2", etc.) to make the name unique. For example, if you ran the two code fragments from your question one after the other in the same script (or Jupyter notebook), you would see this problem.

There are a few ways to avoid this problem:

An easy but crude way is to call tf.reset_default_graph() before the restore part of your program. This resets the current graph to being empty, so the variables will end up having the names "W" and "b" as you intended.

You can achieve a similar effect by wrapping the restore part in a with tf.Graph().as_default(): block, which ensures the variables are created in an empty graph.

You can override the mapping between variables in the checkpoint and tf.Variable objects by passing a var_list argument to the tf.train.Saver constructor as follows:

saver = tf.train.Saver(var_list={"W": W, "b", b})


问:
How can I write and read an empty case class with play-json?
I have an empty case class corresponding to an HTTP GET request:

```<code>case class GetFoo() extends MyQueryRequest {
  // ...
}
</code>```

and each message has a companion object with describes its implicit JSON writer and reader:

```<code>object GetFoo extends MyImplicitJsonProvider[GetFoo] {
  implicit val write = Json.writes[GetFoo]
  implicit val read = Json.reads[GetFoo]
}
</code>```

However, because GetFoo takes no parameters, there's no way to (de)serialize it:

Unapply of object GetFoo has no parameters. Are you using an empty case class?

A workaround to inject a dummy Boolean variable into the constructor for GetFoo, but this is a kludge. I'd like to make GetFoo (de)serializable as an empty JSON object. How can I do that?

Since GET requests don't send data, it would be even better to make the reader/writer throw an exception if it were being used since the request shouldn't need to be written or read ever, but is required by the extended class.

My design relies on the GetX class extending MyQueryRequest and and the GetX companion object extending MyImplicitJsonProvider[GetX].

答:
Throwing an error

If you just want to have non implemented implicit values, you may very well do

```<code>implicit def format: Format[GetFoo] = ???
</code>```

This will add the implicit in the scope whenever you need it, but will throw a NotImplementedException if it is invoked.

Dummy serialization

If you want (de)serialization as empty JsObject, just implement it as such:

```<code>implicit val nonStrictReads = Reads.pure(GetFoo()) // does not check anything on the `JsValue`, always give a `JsSuccess(GetFoo())`
implicit val strictReads = Reads[GetFoo](json => json.validate[JsObject].filter(_.values.isEmpty).map(_ => GetFoo())
implicit val writes = OWrites[GetFoo](_ => Json.obj())
</code>```

Better catch it while you can

However, it would be better to catch the error at compile time, by ensuring (through stronger typing) that your request has no content. To do this, I would need more information on MyQueryRequest and MyImplicitJsonProvider to help you, but I would imagine doing something like MyQueryRequest[NoContent] or MyQueryRequest[JsValue] depending on when you have some content or not. Then one would require JSON serializer, while the other would not.

By the way, you might want to replace your empty case class by a case object, to avoid unnecessary multiple allocations (unless you do some ).

Body:
I have an empty case class corresponding to an HTTP GET request:

case class GetFoo() extends MyQueryRequest {
  // ...
}

and each message has a companion object with describes its implicit JSON writer and reader:

object GetFoo extends MyImplicitJsonProvider[GetFoo] {
  implicit val write = Json.writes[GetFoo]
  implicit val read = Json.reads[GetFoo]
}

However, because GetFoo takes no parameters, there's no way to (de)serialize it:

Unapply of object GetFoo has no parameters. Are you using an empty case class?

A workaround to inject a dummy Boolean variable into the constructor for GetFoo, but this is a kludge. I'd like to make GetFoo (de)serializable as an empty JSON object. How can I do that?

Since GET requests don't send data, it would be even better to make the reader/writer throw an exception if it were being used since the request shouldn't need to be written or read ever, but is required by the extended class.

My design relies on the GetX class extending MyQueryRequest and and the GetX companion object extending MyImplicitJsonProvider[GetX].

Body:
Throwing an error

If you just want to have non implemented implicit values, you may very well do

implicit def format: Format[GetFoo] = ???

This will add the implicit in the scope whenever you need it, but will throw a NotImplementedException if it is invoked.

Dummy serialization

If you want (de)serialization as empty JsObject, just implement it as such:

implicit val nonStrictReads = Reads.pure(GetFoo()) // does not check anything on the `JsValue`, always give a `JsSuccess(GetFoo())`
implicit val strictReads = Reads[GetFoo](json => json.validate[JsObject].filter(_.values.isEmpty).map(_ => GetFoo())
implicit val writes = OWrites[GetFoo](_ => Json.obj())

Better catch it while you can

However, it would be better to catch the error at compile time, by ensuring (through stronger typing) that your request has no content. To do this, I would need more information on MyQueryRequest and MyImplicitJsonProvider to help you, but I would imagine doing something like MyQueryRequest[NoContent] or MyQueryRequest[JsValue] depending on when you have some content or not. Then one would require JSON serializer, while the other would not.

By the way, you might want to replace your empty case class by a case object, to avoid unnecessary multiple allocations (unless you do some ).


问:
How to dynamically create block of content and then add class?
I'm pretty bad at Angularjs, sorry. I need to create 'commentary box' onclick, then i need to insert this "box" to global-wrap-container (it's a class name).

Here i have my "comment box"

```<code>  <div class="comment-reply-wrap" >
    <div class="comment">
      <div class="info" >
        <div class="left-side-info">
          <img src="img/avatar.png" alt="avatar" class="avatar">
          <span class="name">{{repUsers.name}}</span>
        </div>
        <div class="right-side-info">
          <p class="user-text" ng-bind-html='repUsers.text'>
            <img class="comment-image" src="">
          </p>
        </div>
        <div class="bottom">
          <span class="comment-email">{{repUsers.email}}</span>
          <span class="comment-date">10/29/2010 at 6:40AM</span>
          <button type="submit" class="reply" ng-click="createReplyForm($event)">
            <i class="fa fa-reply" aria-hidden="true"></i>
          </button>
        </div>
      </div>
    </div>
  </div>
</code>```

Here is the function, where i push information and "commentary" appears.

```<code>$scope.addRepUser = function() {
$scope.bool = false;

//Dynamically create array of objects and push data
  $scope.repUsers.push({
  name: $scope.repUser.name,
  email: $scope.repUser.email,
  text: $scope.repUser.text
  });

//Clear input fields in main form
$scope.repUser.name = '';
$scope.repUser.email = '';
$scope.repUser.text = ''; };
</code>```

答:
You need to stop thinking 'insert div' like, this is not jquery.
In angular, you can put a div in your html that will be showed depending on a boolean value of your scope.

```<code><div ng-show="shouldBeDisplayed"></div>
</code>```

And in the controller:

```<code>function displayDiv(){
    $scope.shouldBeDisplayed = true;
    //use the line below if you want to toggle show
    //$scope.shouldBeDisplayed = !$scope.shouldBeDisplayed;
}
</code>```

To display the list of comments, you need to use an array:

```<code>$scope.comments = [];
</code>```

On submit you have to push your object inside this array. It will be displayed with an ng-repeat:

```<code><div class="your-class" ng-repat="comment in comments">
</div>
</code>```

The mechanic here should be:

click answer comment

controller should update the boolean value on click

it will display your form (and hide the list if you want to)

submit form

push the values into the desired list and update the boolean to hide the form

Working fiddle: http://jsfiddle.net/4t37u642/

Body:
I'm pretty bad at Angularjs, sorry. I need to create 'commentary box' onclick, then i need to insert this "box" to global-wrap-container (it's a class name).

Here i have my "comment box"

          {{repUsers.name}}

          {{repUsers.email}}
          10/29/2010 at 6:40AM
          <button type="submit" class="reply" ng-click="createReplyForm($event)">

          </button>

Here is the function, where i push information and "commentary" appears.

$scope.addRepUser = function() {
$scope.bool = false;

//Dynamically create array of objects and push data
  $scope.repUsers.push({
  name: $scope.repUser.name,
  email: $scope.repUser.email,
  text: $scope.repUser.text
  });

//Clear input fields in main form
$scope.repUser.name = '';
$scope.repUser.email = '';
$scope.repUser.text = ''; };

Body:
You need to stop thinking 'insert div' like, this is not jquery.
In angular, you can put a div in your html that will be showed depending on a boolean value of your scope.

<div ng-show="shouldBeDisplayed"></div>

And in the controller:

function displayDiv(){
    $scope.shouldBeDisplayed = true;
    //use the line below if you want to toggle show
    //$scope.shouldBeDisplayed = !$scope.shouldBeDisplayed;
}

To display the list of comments, you need to use an array:

$scope.comments = [];

On submit you have to push your object inside this array. It will be displayed with an ng-repeat:

<div class="your-class" ng-repat="comment in comments">
</div>

The mechanic here should be:

click answer comment

controller should update the boolean value on click

it will display your form (and hide the list if you want to)

submit form

push the values into the desired list and update the boolean to hide the form

Working fiddle: http://jsfiddle.net/4t37u642/


问:
How to output GRANT permissions in Generate Scripts
I've been putting my database under source control by running Tasks > Generate Scripts > Script entire database and all database objects. Problem is that after granting a user a couple permissions on the db and re-scripting, I noticed there is no difference in the generated script. Is there a way to automatically generate this??

答: Tools->Options->Sql Server Object Explorer->Scripting->Object Scriptiong Options->Script permissions</p>


问:
Pandas Category sub-group 0 counts
I'm new to Pandas, and trying to generate a table of subgroup counts maintaining the category order, and showing zero counts. It's a simple category with 4 options.

Without grouping it works as expected, but with grouping it isn't displaying zero counts (see last group).

In [21]:

```<code>df2['Call_cat'] = df2['Group_INV'].astype('category')
counts = df2['Call_cat'].value_counts(dropna=True, sort=False)
counts
</code>```

Out[21]:

```<code>1.0    35773
2.0      290
3.0     8680
4.0    18867
Name: Call_cat, dtype: int64
</code>```

In [22]:

grouped = df2.groupby('Z1')['Call_cat'].value_counts(dropna=True, sort=False)
grouped

Out[22]:

```<code>Z1    Call_cat
ZLZO  1.0         2961
      2.0           24
      3.0          476
      4.0         1221
ZZRE  1.0          307
      2.0            2
      3.0          152
      4.0          197
ZZMB  1.0          904
      3.0          198
      4.0          906
</code>```

答:
You can create a MultiIndex from all combinations of values of two grouping columns and reindex the groupby result with this multiindex. Then fill NaN values with zeros.

```<code>import pandas as pd
# example data
df = pd.DataFrame({'a':list('xxxyyy'), 'b':[1,2,3,1,2,2]})
#    a  b
# 0  x  1
# 1  x  2
# 2  x  3
# 3  y  1
# 4  y  2
# 5  y  2

multi_index = pd.MultiIndex.from_product([df.a.unique(), df.b.unique()],
                                         names=['a', 'b'])\
                           .sort_values()
df.groupby(['a','b']).size().reindex(multi_index).fillna(0).astype(int)
</code>```

This produces

```<code>a  b
x  1    1
   2    1
   3    1
y  1    1
   2    2
   3    0
</code>```

Title: Pandas Category sub-group 0 counts

Body:
I'm new to Pandas, and trying to generate a table of subgroup counts maintaining the category order, and showing zero counts. It's a simple category with 4 options.

Without grouping it works as expected, but with grouping it isn't displaying zero counts (see last group).

In [21]:

df2['Call_cat'] = df2['Group_INV'].astype('category')
counts = df2['Call_cat'].value_counts(dropna=True, sort=False)
counts

Out[21]:

1.0    35773
2.0      290
3.0     8680
4.0    18867
Name: Call_cat, dtype: int64

In [22]:

grouped = df2.groupby('Z1')['Call_cat'].value_counts(dropna=True, sort=False)
grouped

Out[22]:

Z1    Call_cat
ZLZO  1.0         2961
      2.0           24
      3.0          476
      4.0         1221
ZZRE  1.0          307
      2.0            2
      3.0          152
      4.0          197
ZZMB  1.0          904
      3.0          198
      4.0          906

Body:
You can create a MultiIndex from all combinations of values of two grouping columns and reindex the groupby result with this multiindex. Then fill NaN values with zeros.

import pandas as pd
# example data
df = pd.DataFrame({'a':list('xxxyyy'), 'b':[1,2,3,1,2,2]})
#    a  b
# 0  x  1
# 1  x  2
# 2  x  3
# 3  y  1
# 4  y  2
# 5  y  2

multi_index = pd.MultiIndex.from_product([df.a.unique(), df.b.unique()],
                                         names=['a', 'b'])\
                           .sort_values()
df.groupby(['a','b']).size().reindex(multi_index).fillna(0).astype(int)

This produces

a  b
x  1    1
   2    1
   3    1
y  1    1
   2    2
   3    0


问:
Kafka Streams wrong joined results of 2 simple KTables
I'm doing join between 2 simple KTables and let suppose that I have 2 topics with the following data, see details:

First topic

1 | Victor C.

1 | Vadim C.

2 | Vasile P.

3 | Vitalie C.

4 | Oleg C.

Second topic

1 | Programmer

2 | Administrator

3 | Manager

SQL behaviour is obviously clear when I'm doing the following query and the output is clear understandable for me:

```<code>SELECT * FROM firstTable
INNER JOIN secondTable
ON firstTable.ID = secondTable.ID
</code>```

1 | Victor C. | 1 | Programmer

1 | Vadim C. | 1 | Programmer

2 | Vasile P. |   2 | Administrator

3 | Vitalie C. |  3 | Manager

So, I'm playing arround Kafka and I tried to do the same behaviour but results of joined streams completely confused my mind

See the code snippet details:

  @Test
  public void joinKTableToKTableWhereKeyValueIsIntegerAndString() throws Exception {
      InternalTestConfiguration itc = getInternalTestConfiguration();
      List < String > topics = Arrays.asList(itc.getFirstTopic(), itc.getSecondTopic(), itc.getProjectionTopic(), itc.getFirstKeyedTopic(), itc.getSecondKeyedTopic());
      KafkaStreams streams = null;

      try {
          Integer partitions = 1;
          Integer replication = 1;
          RestUtils.createTopics(topics, partitions, replication, new Properties());

          List < KeyValue < Integer, String >> employees = Arrays.asList(
              new KeyValue < > (1, "Victor C."),
              new KeyValue < > (1, "Vadim C."),
              new KeyValue < > (2, "Vasile P."),
              new KeyValue < > (3, "Vitalie C."),
              new KeyValue < > (4, "Oleg C.")
          );

          List < KeyValue < Integer, String >> specialities = Arrays.asList(
              new KeyValue < > (1, "Programmer"),
              new KeyValue < > (2, "Administrator"),
              new KeyValue < > (3, "Manager")
          );

          List < KeyValue < Integer, String >> expectedResults = Arrays.asList(
              new KeyValue < > (1, "Victor C./Programmer"),
              new KeyValue < > (1, "Vadim C./Programmer"),
              new KeyValue < > (2, "Vasile P./Administrator"),
              new KeyValue < > (3, "Vitalie C../Manager")
          );

          final Serde < Integer > keySerde = Serdes.Integer();
          final Serde < String > valueSerde = Serdes.String();

          Properties streamsConfiguration = new Properties();
          streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, itc.getAppIdConfig());
          streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS_CONFIG);
          streamsConfiguration.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, ZOOKEEPER_CONNECT_CONFIG);
          streamsConfiguration.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.Integer().getClass().getName());
          streamsConfiguration.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
          streamsConfiguration.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 10 * 1000);
          //streamsConfiguration.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
          streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
          streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getAbsolutePath());

          KStreamBuilder builder = new KStreamBuilder();

          KTable < Integer, String > firstKTable = builder.table(keySerde, valueSerde, itc.getFirstTopic(), itc.getFirstStore());
          KTable < Integer, String > secondKTable = builder.table(keySerde, valueSerde, itc.getSecondTopic(), itc.getSecondStore());
          KTable < Integer, String > projectionKTable = firstKTable.join(secondKTable, (l, r) - > {
              return l + "/" + r;
          });

          projectionKTable.to(keySerde, valueSerde, itc.getProjectionTopic());

          streams = new KafkaStreams(builder, streamsConfiguration);

          streams.start();

          Properties cfg1 = new Properties();
          cfg1.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS_CONFIG);
          cfg1.put(ProducerConfig.ACKS_CONFIG, "all");
          cfg1.put(ProducerConfig.RETRIES_CONFIG, 0);
          cfg1.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
          cfg1.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
          IntegrationTestUtils.produceKeyValuesSynchronously(itc.getFirstTopic(), employees, cfg1);

          Properties cfg2 = new Properties();
          cfg2.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS_CONFIG);
          cfg2.put(ProducerConfig.ACKS_CONFIG, "all");
          cfg2.put(ProducerConfig.RETRIES_CONFIG, 0);
          cfg2.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
          cfg2.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
          IntegrationTestUtils.produceKeyValuesSynchronously(itc.getSecondTopic(), specialities, cfg2);

          Properties consumerConfig = new Properties();
          consumerConfig.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS_CONFIG);
          consumerConfig.put(ConsumerConfig.GROUP_ID_CONFIG, itc.getGroupIdConfig());
          consumerConfig.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
          consumerConfig.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class);
          consumerConfig.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

          List < KeyValue < Integer, String >> actualResults = IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(consumerConfig, itc.getProjectionTopic(), expectedResults.size());

          assertThat(actualResults).containsExactlyElementsOf(expectedResults);
      } finally {
          if (streams != null) {
              streams.close();
          }

          RestUtils.deleteTopics(topics);
      }
  }
```

I expect the same results as SQL have but this is not true.

Results with //streamsConfiguration.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0)" disabled

1, Vadim C./Programmer

2, Vasile P./Administrator

3, Vitalie C./Manager

1, Vadim C./Programmer

2, Vasile P./Administrator

3, Vitalie C./Manager

Results with streamsConfiguration.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0); enabled

1, Vadim C./Programmer

2, Vasile P./Administrator

3, Vitalie C./Manager

Anyway both of results are not the same as SQL, please help me to understand this because I'm already killing my self :(

答:
In your SQL comparison, the number does not seem to be a primary key because both Victor C. and Vadim C. are associated with 1

This doesn't work in the KTable if the number is the key of the message – Vadim C. is overwriting Victor C.. That's why you only have three different people in the output.

The second part of your question concerning the caching behaviour of the KTables. With caching enabled (your first example), the joins are triggered when the caches are flushed (30 seconds by default). There is also an issue with duplicates when caching is enabled. This doesn't occur when you disabled caching, so that's the "correct" output without duplicates.

I recently blogged about join behaviour in Kafka 0.10.1 (so not the newest release which changed a few semantics). Maybe that's helpful to you.

Body:
I'm doing join between 2 simple KTables and let suppose that I have 2 topics with the following data, see details:

First topic

1 | Victor C.

1 | Vadim C.

2 | Vasile P.

3 | Vitalie C.

4 | Oleg C.

Second topic

1 | Programmer

2 | Administrator

3 | Manager

SQL behaviour is obviously clear when I'm doing the following query and the output is clear understandable for me:

SELECT * FROM firstTable
INNER JOIN secondTable
ON firstTable.ID = secondTable.ID

1 | Victor C. | 1 | Programmer

1 | Vadim C. | 1 | Programmer

2 | Vasile P. |   2 | Administrator

3 | Vitalie C. |  3 | Manager

So, I'm playing arround Kafka and I tried to do the same behaviour but results of joined streams completely confused my mind

See the code snippet details:

  @Test
  public void joinKTableToKTableWhereKeyValueIsIntegerAndString() throws Exception {
      InternalTestConfiguration itc = getInternalTestConfiguration();
      List < String > topics = Arrays.asList(itc.getFirstTopic(), itc.getSecondTopic(), itc.getProjectionTopic(), itc.getFirstKeyedTopic(), itc.getSecondKeyedTopic());
      KafkaStreams streams = null;

      try {
          Integer partitions = 1;
          Integer replication = 1;
          RestUtils.createTopics(topics, partitions, replication, new Properties());

          List < KeyValue < Integer, String >> employees = Arrays.asList(
              new KeyValue < > (1, "Victor C."),
              new KeyValue < > (1, "Vadim C."),
              new KeyValue < > (2, "Vasile P."),
              new KeyValue < > (3, "Vitalie C."),
              new KeyValue < > (4, "Oleg C.")
          );

          List < KeyValue < Integer, String >> specialities = Arrays.asList(
              new KeyValue < > (1, "Programmer"),
              new KeyValue < > (2, "Administrator"),
              new KeyValue < > (3, "Manager")
          );

          List < KeyValue < Integer, String >> expectedResults = Arrays.asList(
              new KeyValue < > (1, "Victor C./Programmer"),
              new KeyValue < > (1, "Vadim C./Programmer"),
              new KeyValue < > (2, "Vasile P./Administrator"),
              new KeyValue < > (3, "Vitalie C../Manager")
          );

          final Serde < Integer > keySerde = Serdes.Integer();
          final Serde < String > valueSerde = Serdes.String();

          Properties streamsConfiguration = new Properties();
          streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, itc.getAppIdConfig());
          streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS_CONFIG);
          streamsConfiguration.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, ZOOKEEPER_CONNECT_CONFIG);
          streamsConfiguration.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.Integer().getClass().getName());
          streamsConfiguration.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
          streamsConfiguration.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 10 * 1000);
          //streamsConfiguration.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
          streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
          streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getAbsolutePath());

          KStreamBuilder builder = new KStreamBuilder();

          KTable < Integer, String > firstKTable = builder.table(keySerde, valueSerde, itc.getFirstTopic(), itc.getFirstStore());
          KTable < Integer, String > secondKTable = builder.table(keySerde, valueSerde, itc.getSecondTopic(), itc.getSecondStore());
          KTable < Integer, String > projectionKTable = firstKTable.join(secondKTable, (l, r) - > {
              return l + "/" + r;
          });

          projectionKTable.to(keySerde, valueSerde, itc.getProjectionTopic());

          streams = new KafkaStreams(builder, streamsConfiguration);

          streams.start();

          Properties cfg1 = new Properties();
          cfg1.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS_CONFIG);
          cfg1.put(ProducerConfig.ACKS_CONFIG, "all");
          cfg1.put(ProducerConfig.RETRIES_CONFIG, 0);
          cfg1.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
          cfg1.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
          IntegrationTestUtils.produceKeyValuesSynchronously(itc.getFirstTopic(), employees, cfg1);

          Properties cfg2 = new Properties();
          cfg2.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS_CONFIG);
          cfg2.put(ProducerConfig.ACKS_CONFIG, "all");
          cfg2.put(ProducerConfig.RETRIES_CONFIG, 0);
          cfg2.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
          cfg2.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
          IntegrationTestUtils.produceKeyValuesSynchronously(itc.getSecondTopic(), specialities, cfg2);

          Properties consumerConfig = new Properties();
          consumerConfig.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS_CONFIG);
          consumerConfig.put(ConsumerConfig.GROUP_ID_CONFIG, itc.getGroupIdConfig());
          consumerConfig.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
          consumerConfig.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class);
          consumerConfig.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

          List < KeyValue < Integer, String >> actualResults = IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(consumerConfig, itc.getProjectionTopic(), expectedResults.size());

          assertThat(actualResults).containsExactlyElementsOf(expectedResults);
      } finally {
          if (streams != null) {
              streams.close();
          }

          RestUtils.deleteTopics(topics);
      }
  }

I expect the same results as SQL have but this is not true.

Results with //streamsConfiguration.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0)" disabled

1, Vadim C./Programmer

2, Vasile P./Administrator

3, Vitalie C./Manager

1, Vadim C./Programmer

2, Vasile P./Administrator

3, Vitalie C./Manager

Results with streamsConfiguration.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0); enabled

1, Vadim C./Programmer

2, Vasile P./Administrator

3, Vitalie C./Manager

Anyway both of results are not the same as SQL, please help me to understand this because I'm already killing my self :(


问:
Save Members in a different database
Is there a way to save members in a different database? (I'm talking about the whole member's tables not member properties)

The reason for me asking this is to not worry about members data during content freeze implementation and parallel website migration.

答:
You can easily make your own implementation of a MembershipProvider and replace this with the build-in membership provider in the web.config.

However, I would rather review your website upgrade process to avoid a "content" freeze. E.g. if you use the Umbraco Cloud offering, you can push your changes online to upgrade a website while maintaining your content).

Also packages like Umbraco courrier, Umbraco Deploy, chauffeur and USync allow you to rule out a "content freeze".

Title: Save Members in a different database


问:
simple time series db
I am looking for a simple time series database. The sort of database that could take raw stock tick data for example and for company X and company Y in a split second return end of day data, or data at 3pm, or similar types of query. I dont know what google uses for http://www.google.com/finance?q=INDEXDJX  however that's the sort of data and speed I am looking for. Some of the high end time series dbs cost the earth and do far more than I need. Are there opensource or nearly-free dbs out there that would be appropriate for this?</p>

答:
What amount of data are we talking about here?

I use MySQL to all my projects, including one where I actually collected all the stocks on OMX and NASDAQ every evening for about 2 years. MySQL had no problems at all to search and sort on my local machine.

MySQL are available in a community version (FREE) and if you need you can scale up and buy a license.

MySQL was first developed by a Swedish team (MySQL AB) and then first bought by Sun and later by Oracle.

Download the free MySQL at http://mysql.com/products/community/ and read about it on the Wiki.

Update

I saw that MySQL are used by big sites like Flickr, Facebook, Wikipedia, Google, Nokia.com and YouTube. I think this speaks for itself when it comes to how competent MySQL are.

ContentLicense: CC BY-SA 2.5

Title: simple time series db


问:
Detect key event while mouse over DOM element
I know how to detect key events on the document. I also know how to detect mousemove events in a DOM element.

But I don't know how to detect a key event when it happens with the mouse over an element and the mouse it not moving.

I guess I could set a boolean that will set to true by mousemove an to false by mouseout on the DOM element. But is there a more proper way to do this?

I have found a question that is directly relevant but unanswered (and the comments don't really help):

Detect shift key while already over element

答:
Here's an expansion of my comment above.

Using vanilla JavaScript you can set event listeners on an element for onmouseover and onmouseleave. These event listeners toggle a boolean variable, which is just a flag to say whether the mouse if currently over the element or not.

Then add another event listener on the window for key presses. On key press, if our boolean is true, then run your code, if it's not, do nothing.

```<code>var mouseOn = false;

document.getElementById('div').onmouseover = function() {
    console.log('mouseover');
    mouseOn = true;
}

document.getElementById('div').onmouseleave = function() {
    console.log('mouseleave');
    mouseOn = false;
}

window.onkeypress = function(e) {
    if(mouseOn == true) {
    console.log(e.key)
  }
}
</code>```

Here's the fiddle: https://jsfiddle.net/6wpeLbx9/ (note: the window object in the fiddle is just the panel containing the red square - in order for key presses to be noticed you first have to click on the panel to focus it)

I'm sure my code can be more concise...

Hope that helps!

Body:
Here's an expansion of my comment above.

Using vanilla JavaScript you can set event listeners on an element for onmouseover and onmouseleave. These event listeners toggle a boolean variable, which is just a flag to say whether the mouse if currently over the element or not.

Then add another event listener on the window for key presses. On key press, if our boolean is true, then run your code, if it's not, do nothing.

var mouseOn = false;

document.getElementById('div').onmouseover = function() {
    console.log('mouseover');
    mouseOn = true;
}

document.getElementById('div').onmouseleave = function() {
    console.log('mouseleave');
    mouseOn = false;
}

window.onkeypress = function(e) {
    if(mouseOn == true) {
    console.log(e.key)
  }
}

Here's the fiddle: https://jsfiddle.net/6wpeLbx9/ (note: the window object in the fiddle is just the panel containing the red square - in order for key presses to be noticed you first have to click on the panel to focus it)

I'm sure my code can be more concise...

Hope that helps!


问:
Calling Object's constructor

Why should a class call the call the Objects default constructor of the class Objects when the class already has a parametrized constructor and a unparametrized constructor?

Example

```<code>public abstract class Foo{
    private int dim1;

    public Foo(int dim1) {
        super();
        this.dim1 = dim1;

    }
    public Foo() {

        this.dim1 = 0;

    }
}
</code>```

2. Why isn't the super() method called in the unparametrized constructor in the example above?

What could happen if I forget or I don't want to call the constructor in the Object class with super() ?

Does it matter if the class which calls the super() method (Unparametrized Object's class constructor) is abstract or not ?

答:
Why should a class call the call the Objects default constructor of the class Objects when the class already has a parametrized constructor and a unparametrized constructor?

Just because of you have it, it doesn't mean it gets called automatically. You have to call it and that is where object instantiation begins.

Why isn't the super() method called in the unparametrized constructor in the example above?

It is not a method. It is just invoking the super class default constructor. Do you know , if you didn't call it, the Java compiler automatically inserts that statement while giving you byte code.  So you need not write that super() in child constructors unless you want to call specific constructor .

What could happen if I forget or I don't want to call the constructor in the Object class with super() ?

Don't worry. As said above, compiler inserts it for you.

Does it matter if the class which calls the super() method (Unparametrized Object's class constructor) is abstract or not ?

Yes, abstract or not doesn't matter. It just calls the super class constructor.

Title: Calling Object's constructor

Body:
Why should a class call the call the Objects default constructor of the class Objects when the class already has a parametrized constructor and a unparametrized constructor?

Example

public abstract class Foo{
    private int dim1;

    public Foo(int dim1) {
        super();
        this.dim1 = dim1;

    }
    public Foo() {

        this.dim1 = 0;

    }
}

2. Why isn't the super() method called in the unparametrized constructor in the example above?

What could happen if I forget or I don't want to call the constructor in the Object class with super() ?

Does it matter if the class which calls the super() method (Unparametrized Object's class constructor) is abstract or not ?


问:
Can't resolve all parameters for AuthenticationService: ([object Object], ?, [object Object])
I faced with next error and cannot understand how to resolve it.

Can't resolve all parameters for AuthenticationService: ([object Object], ?, [object Object])

I've checked almost every topic here and have tried multiple ways to resolve it but still can't beat it already second day.

I have tried to inject first authService in appService like this but getting same error

```<code>@Inject(forwardRef(() => AuthenticationService)) public authService: AuthenticationService
</code>```

I have checked all DI and order of imports inside services and it seems to me everything is correct

So I appreciate if somebody could help me deal with it.

Angular 4.0.0

AuthService

```<code>    import { Injectable } from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';

import {AppServices} from "../../app.services";
import {Router} from "@angular/router";

@Injectable()
export class AuthenticationService {
  public token: any;

  constructor(
    private http: Http,
    private appService: AppServices,
    private router: Router
  ) {
    this.token = localStorage.getItem('token');
  }

  login(username: string, password: string): Observable<boolean> {
    let headers = new Headers();
    let body = null;
    headers.append("Authorization",("Basic " + btoa(username + ':' + password)));

    return this.http.post(this.appService.api + '/login', body, {headers: headers})
      .map((response: Response) => {
        let token = response.json() && response.json().token;
        if (token) {
          this.token = token;
          localStorage.setItem('Conform_token', token);
          return true;
        } else {
          return false;
        }
      });
  }

  logout(): void {
    this.token = null;
    localStorage.removeItem('Conform_token');
    this.router.navigate(['/login']);
  }
}
</code>```

App Services

```<code>import {Injectable} from '@angular/core';
import {Headers, Http, RequestOptions} from '@angular/http';
import {Router} from "@angular/router";
import {AuthenticationService} from "./auth/auth.service";

import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';

@Injectable()

export class AppServices {

  api = '//endpoint/';

  public options: any;
  constructor(
    private http: Http,
    private router: Router,
    public authService: AuthenticationService // doesn't work
  //  @Inject(forwardRef(() => AuthenticationService)) public authService: AuthenticationService // doesn't work either
      ) {
        let head = new Headers({
      'Authorization': 'Bearer ' + this.authService.token,
      "Content-Type": "application/json; charset=utf8"
    });
    this.options = new RequestOptions({headers: head});
  }

  // ====================
  //    data services
  // ====================

  getData(): Promise<any> {
    return this.http
      .get(this.api + "/data", this.options)
      .toPromise()
      .then(response => response.json() as Array<Object>)
      .catch((err)=>{this.handleError(err);})
  }
</code>```

App Module

```<code>import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {BaseRequestOptions, HttpModule} from '@angular/http';

import { MaterialModule} from '@angular/material';
import {FlexLayoutModule} from "@angular/flex-layout";
import 'hammerjs';

import { routing, appRoutingProviders }  from './app.routing';
import { AppServices } from './app.services';
import {AuthGuard} from "./auth/auth.guard";
import {AuthenticationService} from "./auth/auth.service";

import {AppComponent} from './app.component';
import {AuthComponent} from './auth/auth.component';
import {NotFoundComponent} from './404/not-found.component';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    AuthComponent,
    NotFoundComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    HttpModule,
    routing,
    MaterialModule,
    FlexLayoutModule
  ],
  providers: [AppServices, AuthGuard, AuthenticationService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
You have a circular dependency between AppServices and AuthenticationService - that's not possible with constructor injection like Angular uses.

To work around you can use

```<code>export class AuthenticationService {
  public token: any;
  appService: AppServices;
  constructor(
    private http: Http,
    // private appService: AppServices,
    injector:Injector;
    private router: Router
  ) {
    setTimeout(() => this.appService = injector.get(AppServices));
    this.token = localStorage.getItem('token');
  }
</code>```

See also DI with cyclic dependency with custom HTTP and ConfigService

To avoid setTimeout you can also set AuthenticationService.appService from the constructor of AppService (or the other way around)

Body:
I faced with next error and cannot understand how to resolve it.

Can't resolve all parameters for AuthenticationService: ([object Object], ?, [object Object])

I've checked almost every topic here and have tried multiple ways to resolve it but still can't beat it already second day.

I have tried to inject first authService in appService like this but getting same error

@Inject(forwardRef(() => AuthenticationService)) public authService: AuthenticationService

I have checked all DI and order of imports inside services and it seems to me everything is correct

So I appreciate if somebody could help me deal with it.

Angular 4.0.0

AuthService

    import { Injectable } from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';

import {AppServices} from "../../app.services";
import {Router} from "@angular/router";

@Injectable()
export class AuthenticationService {
  public token: any;

  constructor(
    private http: Http,
    private appService: AppServices,
    private router: Router
  ) {
    this.token = localStorage.getItem('token');
  }

  login(username: string, password: string): Observable<boolean> {
    let headers = new Headers();
    let body = null;
    headers.append("Authorization",("Basic " + btoa(username + ':' + password)));

    return this.http.post(this.appService.api + '/login', body, {headers: headers})
      .map((response: Response) => {
        let token = response.json() && response.json().token;
        if (token) {
          this.token = token;
          localStorage.setItem('Conform_token', token);
          return true;
        } else {
          return false;
        }
      });
  }

  logout(): void {
    this.token = null;
    localStorage.removeItem('Conform_token');
    this.router.navigate(['/login']);
  }
}

App Services

import {Injectable} from '@angular/core';
import {Headers, Http, RequestOptions} from '@angular/http';
import {Router} from "@angular/router";
import {AuthenticationService} from "./auth/auth.service";

import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';

@Injectable()

export class AppServices {

  api = '//endpoint/';

  public options: any;
  constructor(
    private http: Http,
    private router: Router,
    public authService: AuthenticationService // doesn't work
  //  @Inject(forwardRef(() => AuthenticationService)) public authService: AuthenticationService // doesn't work either
      ) {
        let head = new Headers({
      'Authorization': 'Bearer ' + this.authService.token,
      "Content-Type": "application/json; charset=utf8"
    });
    this.options = new RequestOptions({headers: head});
  }

  // ====================
  //    data services
  // ====================

  getData(): Promise<any> {
    return this.http
      .get(this.api + "/data", this.options)
      .toPromise()
      .then(response => response.json() as Array<Object>)
      .catch((err)=>{this.handleError(err);})
  }

App Module

import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {BaseRequestOptions, HttpModule} from '@angular/http';

import { MaterialModule} from '@angular/material';
import {FlexLayoutModule} from "@angular/flex-layout";
import 'hammerjs';

import { routing, appRoutingProviders }  from './app.routing';
import { AppServices } from './app.services';
import {AuthGuard} from "./auth/auth.guard";
import {AuthenticationService} from "./auth/auth.service";

import {AppComponent} from './app.component';
import {AuthComponent} from './auth/auth.component';
import {NotFoundComponent} from './404/not-found.component';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    AuthComponent,
    NotFoundComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    HttpModule,
    routing,
    MaterialModule,
    FlexLayoutModule
  ],
  providers: [AppServices, AuthGuard, AuthenticationService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Body:
You have a circular dependency between AppServices and AuthenticationService - that's not possible with constructor injection like Angular uses.

To work around you can use

export class AuthenticationService {
  public token: any;
  appService: AppServices;
  constructor(
    private http: Http,
    // private appService: AppServices,
    injector:Injector;
    private router: Router
  ) {
    setTimeout(() => this.appService = injector.get(AppServices));
    this.token = localStorage.getItem('token');
  }

See also DI with cyclic dependency with custom HTTP and ConfigService

To avoid setTimeout you can also set AuthenticationService.appService from the constructor of AppService (or the other way around)


问:
How can I set a layout to a tab in QTabWidget?
I have created a QTabWidget (with no tabs) using the Qt Design tool, and now I need to create tabs and add widgets dynamically.

I can create the tab and add the widget using the following code:

```<code>MyCustomWidget *myCustomWidget = new MyCustomWidget(this);
ui->myTabWidget->addTab(myCustomWidget, "New Tab");
</code>```

The problem is that the widget stays in the top left corner of my QTabWidget but I need to align it in the center (horizontally) of my QTabWidget.

How can I set a horizontal layout to this new tab created?

Note 1: My widget (MyCustomWidget) has a fixed size.

Note 2: I'm using Qt 5.3.

答: It will always be in the top left corner. You can either add another widget on top of yours and them put your widget in the middle of that widget, or make your widget the size of the tab and position its content in the middle. You can use setLayout method of QWidget to set your widget layout.

Body:
I have created a QTabWidget (with no tabs) using the Qt Design tool, and now I need to create tabs and add widgets dynamically.

I can create the tab and add the widget using the following code:

MyCustomWidget *myCustomWidget = new MyCustomWidget(this);
ui->myTabWidget->addTab(myCustomWidget, "New Tab");

The problem is that the widget stays in the top left corner of my QTabWidget but I need to align it in the center (horizontally) of my QTabWidget.

How can I set a horizontal layout to this new tab created?

Note 1: My widget (MyCustomWidget) has a fixed size.

Note 2: I'm using Qt 5.3.


问:
Performance benchmark: PHP Generated content VS. javascript and DOM over AJAX
For the following pretty straightforward task: query a list of products from a DB and present it on a webpage,
consider 2 setups:

Setup1: PHP script queries. All content is built on the server and the entire page is served back to the client.

Setup2: Static HTML "page skeleton" requesting content using AJAX. Received content is parsed on the client side using Javascript and rendered using innerHTML or similar.

Of course the second setup only makes sense when you have pages, categories and tags for the client user to choose from.

I need to compare these two, at least by means of:

time it will take content to be served

user experience (setup1 is delivered as a whole, setup2 is delivered in "two parts")

scalability - how do the setups compare when I have 100,000 queries daily

Any thoughts on the issue will be much appreciated.

答: Performance on the client has many factors. What is running at the time, what browser, what the content is, what the CSS of the page is, how full is the browser's cache, what plug-ins are installed, what is happening on the network, etc. Just remember that when you are playing with the numbers. </p>

OwnerDisplayName: gnosis


问:
Is there a way of making the following shape by CSS coding
Is there a way of making the following shape by CSS coding, without JavaScript?

答:
This can be achieved by a very simple CSS code:

div{
width:50px;
height:50px;
border-radius:50%;
border:10px solid transparent;
border-bottom-color:blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
</div></code>```

Body:
This can be achieved by a very simple CSS code:

div{
width:50px;
height:50px;
border-radius:50%;
border:10px solid transparent;
border-bottom-color:blue;
}

<div>
</div>


问:
Is there a better way to get the result im after with this while loop
I'm gonna put this into a database for example:

Enchant: enchant_id 1, 1 str, 6 dex.

That's why i'm looping through it.

I get the result i want, but is there a better way of doing this?

```<code><?php
$str = 1;
$dex = 1;
while ($dex <= 7) {
    echo "Str: $str";
    echo " - ";
    echo "Dex: $dex";
    echo "<br>";
    $dex++;
    if($dex == 8) {
        echo "<br>";
        $str = 2;
        $dex = 1;
        while ($dex <= 7) {
            echo "Str: $str";
            echo " - ";
            echo "Dex: $dex";
            echo "<br>";
            $dex++;
            if($dex == 8) {
                echo "<br>";
                $str = 3;
                $dex = 1;
                while ($dex <= 7) {
                    echo "Str: $str";
                    echo " - ";
                    echo "Dex: $dex";
                    echo "<br>";
                    $dex++;
                }
            }
         }
    }
}

?>
</code>```

This outputs:

```<code>Str: 1 - Dex: 1
Str: 1 - Dex: 2
Str: 1 - Dex: 3
Str: 1 - Dex: 4
Str: 1 - Dex: 5
Str: 1 - Dex: 6
Str: 1 - Dex: 7

Str: 2 - Dex: 1
Str: 2 - Dex: 2
Str: 2 - Dex: 3
Str: 2 - Dex: 4
Str: 2 - Dex: 5
Str: 2 - Dex: 6
Str: 2 - Dex: 7

Str: 3 - Dex: 1
Str: 3 - Dex: 2
Str: 3 - Dex: 3
Str: 3 - Dex: 4
Str: 3 - Dex: 5
Str: 3 - Dex: 6
Str: 3 - Dex: 7
</code>```

How can i simplify the code to get the same result?

答:
The sample output you show can be achieved with a simple nested for loop.  For example:

```<code>for ($str = 1; $str <= 7; $str++) {
    for ($dex = 1; $dex <= 7; $dex++) {
        echo "Str: $str - Dex: $dex<br />";
    }
    echo "<br />"; // For the extra space between sets
}
</code>```

The key here when looking at your desired output is to recognize the patterns.  You have an incrementing value on the left (STR) and an incrementing value on the right (DEX).  That's two loops.  The pattern is such that for each single increase on the left (the outer loop) there is a full set of value on the right (the inner loop).

Body:
I'm gonna put this into a database for example:

Enchant: enchant_id 1, 1 str, 6 dex.

That's why i'm looping through it.

I get the result i want, but is there a better way of doing this?

<?php
$str = 1;
$dex = 1;
while ($dex <= 7) {
    echo "Str: $str";
    echo " - ";
    echo "Dex: $dex";
    echo "
";
    $dex++;
    if($dex == 8) {
        echo "
";
        $str = 2;
        $dex = 1;
        while ($dex <= 7) {
            echo "Str: $str";
            echo " - ";
            echo "Dex: $dex";
            echo "
";
            $dex++;
            if($dex == 8) {
                echo "
";
                $str = 3;
                $dex = 1;
                while ($dex <= 7) {
                    echo "Str: $str";
                    echo " - ";
                    echo "Dex: $dex";
                    echo "
";
                    $dex++;
                }
            }
         }
    }
}

?>

This outputs:

Str: 1 - Dex: 1
Str: 1 - Dex: 2
Str: 1 - Dex: 3
Str: 1 - Dex: 4
Str: 1 - Dex: 5
Str: 1 - Dex: 6
Str: 1 - Dex: 7

Str: 2 - Dex: 1
Str: 2 - Dex: 2
Str: 2 - Dex: 3
Str: 2 - Dex: 4
Str: 2 - Dex: 5
Str: 2 - Dex: 6
Str: 2 - Dex: 7

Str: 3 - Dex: 1
Str: 3 - Dex: 2
Str: 3 - Dex: 3
Str: 3 - Dex: 4
Str: 3 - Dex: 5
Str: 3 - Dex: 6
Str: 3 - Dex: 7

How can i simplify the code to get the same result?

Body:
The sample output you show can be achieved with a simple nested for loop.  For example:

for ($str = 1; $str <= 7; $str++) {
    for ($dex = 1; $dex <= 7; $dex++) {
        echo "Str: $str - Dex: $dex<br />";
    }
    echo "<br />"; // For the extra space between sets
}

The key here when looking at your desired output is to recognize the patterns.  You have an incrementing value on the left (STR) and an incrementing value on the right (DEX).  That's two loops.  The pattern is such that for each single increase on the left (the outer loop) there is a full set of value on the right (the inner loop).


问:
ServiceProvider not found laravel 5.2
I'm creating a composer installable project inside vendor.
This is my service provider file,

```<code><?php
namespace vimuths123\gitpack;

use Illuminate\Support\ServiceProvider;

class GitpackServiceProvider extends ServiceProvider {
    public function register() {
        $this->app->bind('gitpack', function ($app) {
            return new Gitpack;
        });
    }

    public function boot() {
        // loading the routes file
        require __DIR__ . '/Http/routes.php';

        // define the path for the view files
        $this->loadViewsFrom(__DIR__ . '/../views', 'gitpack');
    }
}
</code>```

This is the structure,

```<code>vendor
      |
     vimuths123
        |-gitpack
           |-src
           |  |-GitpackServiceProvider.php
           |
           |-composer.json
</code>```

I already added my service provider in app/config.php

```<code> vimuths123\gitpack\GitpackServiceProvider::class,
</code>```

and my root composer.json I have following code.

```<code>"psr-4": {
            "App\\": "app/",
            "vimuths123\\gitpack\\" : "vendor/vimuths123/gitpack/src"
        }
</code>```

This is my package composer file,

```<code>{
    "name": "vimuths123/gitpack",
    "autoload": {
        "psr-4" : {
            "vimuths123\\gitpack\\" : "src"
         }
    },
    "require": {
        "composer/installers": "~1.2"
    }
}
</code>```

but all I'm getting is this error,

Class 'vimuths123\gitpack\GitpackServiceProvider' not found

It would be great help someone can help me on this.

答:
You should not put any files into vendor/ by hand. If you are developing a library it must be composer installable library (which once installed end up in vendor/.

Your composer.json seems wrong, especially vendor/vimuths123/gitpack/src name space in psr4. This's smells from a mile as I'd bet you not using vendor/vimuths123/gitpack/src namespace.

Finally, after adding new class you should update class loader to let it know about that:

```<code>composer dumpautoload
</code>```

which solves most of problems with "cannot find my class" issues.

EDIT

It seems your problems are in your library package, not the project using it. From comments it looks that you need to edit your package's composer.json. Assuming package is using vimuths123\gitpack namespace (note, namespace does NOT have to be the same as package name - these are two different things) and its sources sit in src subfolder (so it would be <project>/vendor/vimuths123/gitpack/src) then I'd rework autoload section to look like this:

```<code>"autoload": {
   "psr-4" : {
       "vimuths123\\gitpack\\" : "src"
    }
}
</code>```

and then composer dumpautoload.

Title: ServiceProvider not found laravel 5.2

Body:
I'm creating a composer installable project inside vendor.
This is my service provider file,

<?php
namespace vimuths123\gitpack;

use Illuminate\Support\ServiceProvider;

class GitpackServiceProvider extends ServiceProvider {
    public function register() {
        $this->app->bind('gitpack', function ($app) {
            return new Gitpack;
        });
    }

    public function boot() {
        // loading the routes file
        require __DIR__ . '/Http/routes.php';

        // define the path for the view files
        $this->loadViewsFrom(__DIR__ . '/../views', 'gitpack');
    }
}

This is the structure,

vendor
      |
     vimuths123
        |-gitpack
           |-src
           |  |-GitpackServiceProvider.php
           |
           |-composer.json

I already added my service provider in app/config.php

 vimuths123\gitpack\GitpackServiceProvider::class,

and my root composer.json I have following code.

"psr-4": {
            "App\\": "app/",
            "vimuths123\\gitpack\\" : "vendor/vimuths123/gitpack/src"
        }

This is my package composer file,

{
    "name": "vimuths123/gitpack",
    "autoload": {
        "psr-4" : {
            "vimuths123\\gitpack\\" : "src"
         }
    },
    "require": {
        "composer/installers": "~1.2"
    }
}

but all I'm getting is this error,

Class 'vimuths123\gitpack\GitpackServiceProvider' not found

It would be great help someone can help me on this.

Body:
You should not put any files into vendor/ by hand. If you are developing a library it must be composer installable library (which once installed end up in vendor/.

Your composer.json seems wrong, especially vendor/vimuths123/gitpack/src name space in psr4. This's smells from a mile as I'd bet you not using vendor/vimuths123/gitpack/src namespace.

Finally, after adding new class you should update class loader to let it know about that:

composer dumpautoload

which solves most of problems with "cannot find my class" issues.

EDIT

It seems your problems are in your library package, not the project using it. From comments it looks that you need to edit your package's composer.json. Assuming package is using vimuths123\gitpack namespace (note, namespace does NOT have to be the same as package name - these are two different things) and its sources sit in src subfolder (so it would be <project>/vendor/vimuths123/gitpack/src) then I'd rework autoload section to look like this:

"autoload": {
   "psr-4" : {
       "vimuths123\\gitpack\\" : "src"
    }
}

and then composer dumpautoload.


问:
Export an object with Spring JMX annotations
I'm trying to export some information with Spring JMX annotation driven (I have no xml :D). I have achieved to export Strings and Integer types but I haven't been able to export any object of a class I created.

This is my @Configuration class.

```<code>@Configuration
@EnableMBeanExport
@ComponentScan({"my.packages"})
public class AppManager {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(AppManager.class);
        context.refresh();

        try {
            TimeUnit.MINUTES.sleep(30);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Bean(name = "jmxExporter")
    public Exporter jmxExporter() {
        return new Exporter();
    }
}
</code>```

This is some class I have with some attributes I want to get.

```<code>public class MyClass implements Serializable {

    private int param1;
    private int param2;
    private int param3;

    public MyClass() {
        // calculate all params
    }

    public int getParam1() {
        return this.param1;
    }

    public int getParam2() {
        return this.param2;
    }

    public int getParam3() {
        return this.param3;
    }

}
</code>```

This is the class that exports it's attributes.

```<code>import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedResource;

@ManagedResource(objectName = "my.packages:type=JMX,name=Exporter")
public class Exporter {

    @ManagedAttribute
    public String getString() { //This works!
        return "Test string";
    }

    @ManagedAttribute
    public MyClass getMyClass() { //This does not work
        return new MyClass();
    }

}
</code>```

I need to create MyClass object every time because it has some real-time information that I can't export separately.

In JConsole the value of attribute is "Unavailable".

I'm pretty new to JMX and obviously missing something.

Thank you for your help!

答:
I resolved it by returning CompositeData.

```<code>@ManagedAttribute
public CompositeData getMyClass() {
    return createCompositeDataForMyClass();
}
</code>```

I built a CompositeDataSupport for that and it worked.

```<code>return new CompositeDataSupport(compositeType, itemNames, itemValues);
</code>```

Where compositeType is a CompositeType, itemNames is a String[] and itemValues is an Object[].

The CompositeType can be built with something like this

```<code>new CompositeType(typeName, typeDescription, itemNames, itemDescriptions, itemTypes);
</code>```

typeName, typeDescription are Strings. itemNames and itemDescriptions are String[]. itemTypes is an OpenType[]. SimpleType and CompositeType can be used to build OpenType.

All this objects must be imported with

```<code>import javax.management.openmbean.*;
</code>```

Body:
I'm trying to export some information with Spring JMX annotation driven (I have no xml :D). I have achieved to export Strings and Integer types but I haven't been able to export any object of a class I created.

This is my @Configuration class.

@Configuration
@EnableMBeanExport
@ComponentScan({"my.packages"})
public class AppManager {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(AppManager.class);
        context.refresh();

        try {
            TimeUnit.MINUTES.sleep(30);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Bean(name = "jmxExporter")
    public Exporter jmxExporter() {
        return new Exporter();
    }
}

This is some class I have with some attributes I want to get.

public class MyClass implements Serializable {

    private int param1;
    private int param2;
    private int param3;

    public MyClass() {
        // calculate all params
    }

    public int getParam1() {
        return this.param1;
    }

    public int getParam2() {
        return this.param2;
    }

    public int getParam3() {
        return this.param3;
    }

}

This is the class that exports it's attributes.

import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedResource;

@ManagedResource(objectName = "my.packages:type=JMX,name=Exporter")
public class Exporter {

    @ManagedAttribute
    public String getString() { //This works!
        return "Test string";
    }

    @ManagedAttribute
    public MyClass getMyClass() { //This does not work
        return new MyClass();
    }

}

I need to create MyClass object every time because it has some real-time information that I can't export separately.

In JConsole the value of attribute is "Unavailable".

I'm pretty new to JMX and obviously missing something.

Thank you for your help!

Body:
I resolved it by returning CompositeData.

@ManagedAttribute
public CompositeData getMyClass() {
    return createCompositeDataForMyClass();
}

I built a CompositeDataSupport for that and it worked.

return new CompositeDataSupport(compositeType, itemNames, itemValues);

Where compositeType is a CompositeType, itemNames is a String[] and itemValues is an Object[].

The CompositeType can be built with something like this

new CompositeType(typeName, typeDescription, itemNames, itemDescriptions, itemTypes);

typeName, typeDescription are Strings. itemNames and itemDescriptions are String[]. itemTypes is an OpenType[]. SimpleType and CompositeType can be used to build OpenType.

All this objects must be imported with

import javax.management.openmbean.*;


问:
Failed to read auto-increment value from storage engine, Error Number: 1467
When inserting data in mysql i get this error:

Error Number: 1467
   Failed to read auto-increment value from storage engine

I don't now how to solve this issue please any help will be appreciated.

答:
```<code>ps aux | grep mysql
sudo kill (your pid)
/etc/init.d/mysql restart
</code>```


问:
How to create a quartz (cron) in Codeigniter 2 (php)?
I ask you how to create a quartz (cron) in with the framework of Codeigniter 2 (php), I need to send an email at 2:00 pm every day.
I await your kind support.
Regards,</p>

答:
To do so, you need to add a make a php file that will send email. Suppose your file name is send_email.php. Now test that file is working or not by executing php send_email.php in the directory of your file. If this file sends mail successfully, then you know that this command will send email every time you execute it.

Now, you need to add this command in your Operating System's cronjob list. If you are in Linux, then open your terminal and execute the command crontab -e. Then select edit option to edit your cronjob. Add following line at the bottom:

0 14 * * * php full_path_of_the_file/send_mail.php

The first 0 means zero minute. Second number 14 means 2PM then rest three starts are for all week, months and year. then our old php command to execute php file. Then path to our created php file. Here, only the file won't work. You need to provide full path of your php file that send mail.
Save the file and exit. Now, your operating system will send email every day at 2:00PM.


问:
What is the best testing framework to use with Node.js?
I have looked at the rather long list of testing frameworks at https://github.com/ry/node/wiki/modules#testing. What is the experience with these frameworks?

Obviously the ability to run in the browser would be a big bonus, but I'm mainly interested in Node.js. Something with a heavily asynchronous slant would be great.

答:
Update:

Mocha is the best in my opinion.

What is the experience with these frameworks?

I played with expresso which is pretty cool testing framework which also has test-coverage. It has been created by TJ Holowaychuk who is also the creator of Express.js (insanely fast (and small) server-side JavaScript web development framework built on Node.js and Connect). I recently saw that he also has a cool library called should.js which can be used together with Expresso for a even better testing experience.

Obviously, the ability to run in the
  browser would be a big bonus

I don't believe it can run in the browser, but I also don't get why you would want to run it inside the browser?

but I'm mainly interested in Node.js.
  Something with a heavily asynchronous
  slant would be great.

Quote from the expresso:

The argument passed to each callback
  is beforeExit, which is typically used
  to assert that callbacks have been
  invoked.

You can use beforeExit to test asynchronous functions.

TIP: Follow TJ Holowaychuk on GitHub, because he creates very good open-source code.

ContentLicense: CC BY-SA 4.0


问:
Removing empty lines from csv file using Python
I am creating a code that will calculate means of the first 5 rows. However, I cannot think of the way to remove a row if it initially was left empty. Here is the sketch of my code. Sorry if it is primitive,I am still a novice.Thanks!</p>

```<code>import csv
import statistics
with open('Test.csv') as file:
 data=csv.reader(file,delimiter=',')

 sample1=[]
 sample2=[]
 sample3=[]
 sample4=[]
 sample5=[]
 #I was trying to do something like that but then
 #I receive error message that states that statistics.mean requires at least
 #one value.
 #(for row in data:
    #if row:
        #some=row[1])
 for row in data:

    sp1=row[0]
    sample1.append(sp1)
    sample1=[int(x) for x in sample1]
    sp2=row[1]
    sample2.append(sp2)
    sample2=[int(x) for x in sample2]
    sp3=row[2]
    sample3.append(sp3)
    sample3=[int(x) for x in sample3]
    sp4=row[3]
    sample4.append(sp4)
    sample4=[int(x) for x in sample4]
    sp5=row[4]
    sample5.append(sp5)
    sample5=[int(x) for x in sample5]

 mean1=statistics.mean(sample1)
 mean2=statistics.mean(sample2)
 mean3=statistics.mean(sample3)
 mean4=statistics.mean(sample4)
 mean5=statistics.mean(sample5)
 print(mean1)
 print(mean2)
 print(mean3)
 print(mean4)
 print(mean5)
</code>```

答:
Here's a cleaner way of doing it:

```<code>import csv
import statistics

fromFile = []
with open('sample.csv','r') as fi:
    data=csv.reader(fi,delimiter=',')
    first = True
    for row in data:
        if first:
            first = False
            continue
        if not filter(lambda a: a != '', row):
            continue
        fromFile.append(row)
print statistics.mean([int(item[1]) for item in fromFile])
</code>```

Sample CSV file:

```<code>name, age
bob,9
rachel,90

,,,,
joe,5
</code>```

Body:
I am creating a code that will calculate means of the first 5 rows. However, I cannot think of the way to remove a row if it initially was left empty. Here is the sketch of my code. Sorry if it is primitive,I am still a novice.Thanks!

import csv
import statistics
with open('Test.csv') as file:
 data=csv.reader(file,delimiter=',')

 sample1=[]
 sample2=[]
 sample3=[]
 sample4=[]
 sample5=[]
 #I was trying to do something like that but then
 #I receive error message that states that statistics.mean requires at least
 #one value.
 #(for row in data:
    #if row:
        #some=row[1])
 for row in data:

    sp1=row[0]
    sample1.append(sp1)
    sample1=[int(x) for x in sample1]
    sp2=row[1]
    sample2.append(sp2)
    sample2=[int(x) for x in sample2]
    sp3=row[2]
    sample3.append(sp3)
    sample3=[int(x) for x in sample3]
    sp4=row[3]
    sample4.append(sp4)
    sample4=[int(x) for x in sample4]
    sp5=row[4]
    sample5.append(sp5)
    sample5=[int(x) for x in sample5]

 mean1=statistics.mean(sample1)
 mean2=statistics.mean(sample2)
 mean3=statistics.mean(sample3)
 mean4=statistics.mean(sample4)
 mean5=statistics.mean(sample5)
 print(mean1)
 print(mean2)
 print(mean3)
 print(mean4)
 print(mean5)

Body:
Here's a cleaner way of doing it:

import csv
import statistics

fromFile = []
with open('sample.csv','r') as fi:
    data=csv.reader(fi,delimiter=',')
    first = True
    for row in data:
        if first:
            first = False
            continue
        if not filter(lambda a: a != '', row):
            continue
        fromFile.append(row)
print statistics.mean([int(item[1]) for item in fromFile])

Sample CSV file:

name, age
bob,9
rachel,90

,,,,
joe,5


答:
1) You probably shouldn't. It is unnecessary. It is an extra line of code which doesn't do anything.

2) Because explicitly calling super() is entirely unnecessary if your object does not extend a class other than Object (as all classes do). You could remove it from the first constructor and nothing would change. The code would compile identically.

3) Nothing. You're not required to do it.

4) This makes no difference.

Title: Calling Object's constructor


问:
Where to do JWT expiration with Node.js and jsonwebtoken?
I am creating a web application based on MEAN and I have the following question:

Where is it better to put a token (JWT) expiration? Right now what I am doing is to create a token without expiration and in the client, I created a cookie with that token and 10 minutes of expiration.

In that cookie, I add 10 minutes in every request I make. If the user is inactive for 10 minutes that cookie expires and the request is made without a token.

答:
In Chrome:

F12 ➡ Application tab ➡ Cookies ➡ Copy and paste token into a REST client like Postman

Whoops, I just got an everlasting token for your API!

In other words, as you suspected, this isn't a good way of doing things. The expiration should be in the token's payload - that way, you can verify nobody has altered it, as it'll be signed with your server secret value.

The Node JWT library actually has this functionality built-in:

```<code>jwt.sign({
  // 1 hour expiration
  exp: Math.floor(Date.now() / 1000) + (60 * 60),
  data: 'foobar'
}, 'secret');
</code>```

This isn't to say that you can't/shouldn't also use cookie expiration with your tokens, but relying on it alone isn't secure.

Body:
In Chrome:

F12 ➡ Application tab ➡ Cookies ➡ Copy and paste token into a REST client like Postman

Whoops, I just got an everlasting token for your API!

In other words, as you suspected, this isn't a good way of doing things. The expiration should be in the token's payload - that way, you can verify nobody has altered it, as it'll be signed with your server secret value.

The Node JWT library actually has this functionality built-in:

jwt.sign({
  // 1 hour expiration
  exp: Math.floor(Date.now() / 1000) + (60 * 60),
  data: 'foobar'
}, 'secret');

This isn't to say that you can't/shouldn't also use cookie expiration with your tokens, but relying on it alone isn't secure.