问:
How to remove characters in string after email
I'm using this code to list email addresses from a HTML page.

```<code>require 'nokogiri'

selector = "//a[starts-with(@href, \"mailto:\")]/@href"

doc = Nokogiri::HTML.parse File.read 'in.rb'

nodes = doc.xpath selector

addresses = nodes.collect {|n| n.value[7..-1]}

puts addresses
</code>```

This is sample code I'm parsing:

```<code><a href="mailto:joe@example.com?subject=My Business Is Dying">
</code>```

But I'm getting more than just the email address. I'm getting this in my results:

```<code>joe@example.com?subject=My Business Is Dying
</code>```

How do I drop off everything after the question mark so it's only the email address?

答:
You could always chop off anything after the ? character:

```<code>addresses.map! do |address|
  address.sub(/\?.*/, '')
end
</code>```

Body:
I'm using this code to list email addresses from a HTML page.

require 'nokogiri'

selector = "//a[starts-with(@href, \"mailto:\")]/@href"

doc = Nokogiri::HTML.parse File.read 'in.rb'

nodes = doc.xpath selector

addresses = nodes.collect {|n| n.value[7..-1]}

puts addresses

This is sample code I'm parsing:

But I'm getting more than just the email address. I'm getting this in my results:

joe@example.com?subject=My Business Is Dying

How do I drop off everything after the question mark so it's only the email address?

Body:
You could always chop off anything after the ? character:

addresses.map! do |address|
  address.sub(/\?.*/, '')
end


来源: stackexchange

问:
Which pointer value is the max for a malloc call
Fairly simple question regarding malloc. What is the max that I can set within the allocated area. For instance:</p>

```<code>char *buffer;
buffer = malloc(20);
buffer[19] = 'a'; //Is this the highest spot I can set?
buffer[20] = 'a'; //Or is this the highest spot I can set?
free(buffer);
</code>```

答:
malloc(x) will allocate x bytes.

So by accessing buffer[0] you access the first byte, by accessing buffer[1] you access the second.

e.g

```<code>char * buffer = (char *) malloc(1);
buffer[0] = 0; // legal
buffer[1] = 0; // illegal
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Fairly simple question regarding malloc. What is the max that I can set within the allocated area. For instance:

char *buffer;
buffer = malloc(20);
buffer[19] = 'a'; //Is this the highest spot I can set?
buffer[20] = 'a'; //Or is this the highest spot I can set?
free(buffer);

Body:
malloc(x) will allocate x bytes.

So by accessing buffer[0] you access the first byte, by accessing buffer[1] you access the second.

e.g

char * buffer = (char *) malloc(1);
buffer[0] = 0; // legal
buffer[1] = 0; // illegal


问:
strange text in CoordinatorLayout
I have app name show's in my CoordinatorLayout but i want to remove it , so were to find that text or view , my XML file doesn't have this text view

XML file code :

```<code> <android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<android.support.design.widget.AppBarLayout
    android:id="@+id/htab_appbar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/htab_collapse_toolbar"
        android:layout_width="match_parent"
        android:layout_height="400dp">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="100dp" />

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>
</code>```

答:
```<code>Toolbar toolbar = (Toolbar) findviewbyid(R.id.toolbar);
toolbar.setTitle(null);
</code>```

Title: strange text in CoordinatorLayout

Body:
I have app name show's in my CoordinatorLayout but i want to remove it , so were to find that text or view , my XML file doesn't have this text view

XML file code :

 <android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<android.support.design.widget.AppBarLayout
    android:id="@+id/htab_appbar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/htab_collapse_toolbar"
        android:layout_width="match_parent"
        android:layout_height="400dp">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="100dp" />

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>


问:
add id to dynamically created

I have the following JavaScript that creates a div and then appends it to the body and then inserts some dynamically generated HTML into it. cartDiv = document.createElement('div'); This div I would like to add an id and/or a class to it. If possible both Jquery and JavaScript answers would be great.

```<code>var cartHTML = '<div class="soft_add_wrapper" onmouseover="setTimer();">';
cartHTML += '<div class="soft_add_header_shadow">';
cartHTML += '<div class="soft_add_header"><span class="soft_add_span">Added to cart</span><a href="" class="close_btn" onclick="hideCart(); return false;">Close</a></div></div>'
cartHTML += '<div class="soft_add_content_shadow"><div class="soft_add_content_wrapper">';
cartHTML += '<div class="soft_add_content_area" onscroll="setTimer();"><table class="cart_table" cellpadding="0" cellspacing="0" border="0">';
if (cartLength != 0) {
    cartHTML += cartLoop(index, cartLength);
    if (index != 0) {
        cartHTML += cartLoop(0, index);
    }
    if (discountTotal != "0") {
        var discountProduct = {
        ProductName: "Discount(s)",
        ProductPrice: '<span style="color:red">' + discountTotal + '</span>'
        }
        cartHTML += getLineItemHTML(discountProduct);
    }
}
cartHTML += '</table></div><div class="soft_add_sub_total"><div class="number_of_items">' + quantity + ' items in cart</div>';
cartHTML += '<div class="sub_total">';
cartHTML += 'Subtotal: <span class="sub_total_amount">' + cartTotal + '</span>';
cartHTML += '</div>';
 cartHTML += '</div><div class="soft_add_action_area"><a href="/ShoppingCart.asp" class="check_out">Check Out</a>';
cartHTML += '<a href="" class="continue_shopping" onclick="hideCart(); return false;">Continue shopping</a></div></div></div></div>';
if (cartDiv == null) {
    cartDiv = document.createElement('div');
    document.body.appendChild(cartDiv);
}
cartDiv.innerHTML = cartHTML;
</code>```

答:
You can add the id="MyID123" at the start of the cartHTML text appends.

The first line would therefore be:

```<code>var cartHTML = '<div id="MyID123" class="soft_add_wrapper" onmouseover="setTimer();">';
</code>```

-OR-

If you want the ID to be in a variable, then something like this:

```<code>    var MyIDvariable = "MyID123";
    var cartHTML = '<div id="'+MyIDvariable+'" class="soft_add_wrapper" onmouseover="setTimer();">';
/* ... the rest of your code ... */
</code>```

ContentLicense: CC BY-SA 2.5

Title: add id to dynamically created <div>

Body:
I have the following JavaScript that creates a div and then appends it to the body and then inserts some dynamically generated HTML into it. cartDiv = document.createElement('div'); This div I would like to add an id and/or a class to it. If possible both Jquery and JavaScript answers would be great.

var cartHTML = '
';
cartHTML += '
';
cartHTML += '
Added to cartClose

'
cartHTML += '

';
cartHTML += '

';
if (cartLength != 0) {
    cartHTML += cartLoop(index, cartLength);
    if (index != 0) {
        cartHTML += cartLoop(0, index);
    }
    if (discountTotal != "0") {
        var discountProduct = {
        ProductName: "Discount(s)",
        ProductPrice: '' + discountTotal + ''
        }
        cartHTML += getLineItemHTML(discountProduct);
    }
}
cartHTML += '

' + quantity + ' items in cart
';
cartHTML += '
';
cartHTML += 'Subtotal: ' + cartTotal + '';
cartHTML += '
';
 cartHTML += '

Check Out';
cartHTML += 'Continue shopping

';
if (cartDiv == null) {
    cartDiv = document.createElement('div');
    document.body.appendChild(cartDiv);
}
cartDiv.innerHTML = cartHTML;

Body:
You can add the id="MyID123" at the start of the cartHTML text appends.

The first line would therefore be:

var cartHTML = '<div id="MyID123" class="soft_add_wrapper" onmouseover="setTimer();">';

-OR-

If you want the ID to be in a variable, then something like this:

    var MyIDvariable = "MyID123";
    var cartHTML = '<div id="'+MyIDvariable+'" class="soft_add_wrapper" onmouseover="setTimer();">';
/* ... the rest of your code ... */


问:
Android GridView hides my Buttons
I have a LinearLayout in my android application.

Worked well with just the two Buttons - but when I added the GridView, it now hides the two Buttons - regardless if I put them above or below the GridView

Can anyone help ?

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

```<code><GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="4"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"/>

<Button android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_marginTop="5px"
android:layout_width="fill_parent"
android:text="@string/week" />
<Button android:layout_weight="1"
android:layout_marginTop="5px"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="@string/day" />
</code>```

答:
I solved this - it was because the root level LinearLayout was set with an orientation of horizontal.

I changed this to 'vertical' and then wrapped the two Button elements in their own LinearLayout with 'horizontal' orientation - all works as I needed now.

Here is the resulting XML

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff">

        <Button android:layout_weight="1"
            android:layout_height="wrap_content"
            android:layout_marginTop="5px"
            android:layout_width="fill_parent"
            android:text="@string/week" />
        <Button android:layout_weight="1"
            android:layout_marginTop="5px"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:text="@string/day" />
</LinearLayout>

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:numColumns="4"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>
</code>```

Title: Android GridView hides my Buttons

Body:
I have a LinearLayout in my android application.

Worked well with just the two Buttons - but when I added the GridView, it now hides the two Buttons - regardless if I put them above or below the GridView

Can anyone help ?

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

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="4"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"/>

<Button android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_marginTop="5px"
android:layout_width="fill_parent"
android:text="@string/week" />
<Button android:layout_weight="1"
android:layout_marginTop="5px"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="@string/day" />

Body:
I solved this - it was because the root level LinearLayout was set with an orientation of horizontal.

I changed this to 'vertical' and then wrapped the two Button elements in their own LinearLayout with 'horizontal' orientation - all works as I needed now.

Here is the resulting XML

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff">

        <Button android:layout_weight="1"
            android:layout_height="wrap_content"
            android:layout_marginTop="5px"
            android:layout_width="fill_parent"
            android:text="@string/week" />
        <Button android:layout_weight="1"
            android:layout_marginTop="5px"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:text="@string/day" />
</LinearLayout>

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:numColumns="4"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>


问:
K-out-of-N constraint in Z3Py
I am using the Python bindings for the Z3 theorem prover (Z3Py).  I have N boolean variables, x1,..,xN.  I want to express the constraint that exactly K out of N of them should be true.  How can I do that, in Z3Py?  Is there any built-in support for that?  I checked the online documentation, but the Z3Py docs don't have any mention of any API for that.

For one-out-of-N constraints, I know I can separately express that at least one is true (assert Or(x1,..,xN)) and that at most one is true (assert Not(And(xi,xj)) for all i,j).  I also know of other ways to manually express the 1-out-of-N and K-out-of-N constraints.  However I have the impression that when the solver has built-in support for this constraint, it can sometimes be more efficient than expressing it manually.

答:
Yes, Z3Py has built-in support for this.  There is an undocumented API for this, that isn't mentioned in the Z3Py docs: use PbEq.  In particular, the expression

```<code>PbEq(((x1,1),(x2,1),..,(xN,1)),K)
</code>```

will be true if exactly K out of the N boolean variables are set to true.  There are some reports that this encoding will be faster than naive ways of manually expressing the constraint.

To express a 1-out-of-N constraint, just set K=1 and use PbEq.  To express an at-most-K-out-of-N constraint, use PbLe.  To express an at-least-K-out-of-N constraint, use PbGe.

You can express this in Python like this:

import z3

s = z3.Solver()
bvars = [z3.Bool("Var {0}".format(x)) for x in range(10)]
#Exactly 3 of the variables should be true
s.add( z3.PbEq([(x,1) for x in bvars], 3) )
s.check()
m = s.model()

s = z3.Solver()
bvars = [z3.Bool("Var {0}".format(x)) for x in range(10)]
#<=3 of the variables should be true
s.add( z3.PbLe([(x,1) for x in bvars], 3) )
s.check()
m = s.model()

s = z3.Solver()
bvars = [z3.Bool("Var {0}".format(x)) for x in range(10)]
#>=3 of the variables should be true
s.add( z3.PbGe([(x,1) for x in bvars], 3) )
s.check()
m = s.model()
```

Title: K-out-of-N constraint in Z3Py

Body:
Yes, Z3Py has built-in support for this.  There is an undocumented API for this, that isn't mentioned in the Z3Py docs: use PbEq.  In particular, the expression

PbEq(((x1,1),(x2,1),..,(xN,1)),K)

will be true if exactly K out of the N boolean variables are set to true.  There are some reports that this encoding will be faster than naive ways of manually expressing the constraint.

To express a 1-out-of-N constraint, just set K=1 and use PbEq.  To express an at-most-K-out-of-N constraint, use PbLe.  To express an at-least-K-out-of-N constraint, use PbGe.

You can express this in Python like this:

import z3

s = z3.Solver()
bvars = [z3.Bool("Var {0}".format(x)) for x in range(10)]
#Exactly 3 of the variables should be true
s.add( z3.PbEq([(x,1) for x in bvars], 3) )
s.check()
m = s.model()

s = z3.Solver()
bvars = [z3.Bool("Var {0}".format(x)) for x in range(10)]
#<=3 of the variables should be true
s.add( z3.PbLe([(x,1) for x in bvars], 3) )
s.check()
m = s.model()

s = z3.Solver()
bvars = [z3.Bool("Var {0}".format(x)) for x in range(10)]
#>=3 of the variables should be true
s.add( z3.PbGe([(x,1) for x in bvars], 3) )
s.check()
m = s.model()

ContentLicense: CC BY-SA 4.0


问:
Id of an item in QTreeWidget changed
There is something very strange about Qt.

I have a button ui->addPointButton and a QtreeWidget ui->pointListBox. When I click on the button, it adds a point to the tree. mScenePtr is a pointer to the class I put all my points.AddPoint is a class creating a window asking for some information about the point.

```<code>void AddPointsWindow::on_addPointButton_clicked(bool clicked)
{
    Q_UNUSED(clicked);

    AddPoint addPointWindow(mScenePtr->getColor_or_texture());
    int addPointWindowResult = addPointWindow.exec();

    if  (addPointWindowResult == QDialog::Accepted)
    {
        SVertex vertex = addPointWindow.getVertex();
        mScenePtr->addVertex(vertex);

        QTreeWidgetItem* itemPtr = new QTreeWidgetItem(ui->pointListBox);
        cout << "id" << ui->pointListBox->indexOfTopLevelItem(itemPtr) << endl;

        //itemPtr->setText(0,QString::number(mScenePtr->getVertexNumber()));
        //itemPtr->setText(0, QString::number(ui->pointListBox->indexOfTopLevelItem(itemPtr)));
        itemPtr->setText(0, "hjhjh");
        cout << "id" << ui->pointListBox->indexOfTopLevelItem(itemPtr) << endl;

        itemPtr->setText(1, QString::number(vertex.x));
        itemPtr->setText(2, QString::number(vertex.y));
        itemPtr->setText(3, QString::number(vertex.z));
        if (color == mScenePtr->getColor_or_texture())
        {
            itemPtr->setText(4, QString::number(vertex.r));
            itemPtr->setText(5, QString::number(vertex.g));
            itemPtr->setText(6, QString::number(vertex.b));
        }
        //ui->pointListBox->insertTopLevelItem(ui->pointListBox->topLevelItemCount(), itemPtr);

        cout << "value : " << vertex.x << endl;

    }
}
</code>```

In this exemple, I click twice on the buttons, create two points with vertex.x = 0 for the first and 1 for the second.

Look at the three lines in the middle :

```<code>            //itemPtr->setText(0,QString::number(mScenePtr->getVertexNumber()));
        //itemPtr->setText(0, QString::number(ui->pointListBox->indexOfTopLevelItem(itemPtr)));
        itemPtr->setText(0, "hjhjh");
</code>```

If there is only the third line, the result is

```<code>id0
id0
value : 0
id1
id1
value : 1
</code>```

Everythong is ok.
But if I put one of the two others lines, the result in both cases is :

```<code>id0
id0
value : 0
id1
id0
value : 1
</code>```

How is it possible ? How can the call to ui->pointListBox->indexOfTopLevelItem(itemPtr) or mScenePtr->getVertexNumber() can change the id of the item ?

Qt 5.5

答:
After using setText, the items in the tree might have sorted automatically.

So in the two commented line cases, when you add the number (using setText), the nodes are getting sorted and the earlier node has become the top level item.

That is the reason you are seeing two different IDs "before setText" and "after setText", when you are querying "top level item".

To see the results properly, Turn off the sorting for the tree. (may be in your constructor)

```<code>ui->pointListBox->setSortingEnabled(false);
</code>```

Title: Id of an item in QTreeWidget changed

Body:
There is something very strange about Qt.

I have a button ui->addPointButton and a QtreeWidget ui->pointListBox. When I click on the button, it adds a point to the tree. mScenePtr is a pointer to the class I put all my points.AddPoint is a class creating a window asking for some information about the point.

void AddPointsWindow::on_addPointButton_clicked(bool clicked)
{
    Q_UNUSED(clicked);

    AddPoint addPointWindow(mScenePtr->getColor_or_texture());
    int addPointWindowResult = addPointWindow.exec();

    if  (addPointWindowResult == QDialog::Accepted)
    {
        SVertex vertex = addPointWindow.getVertex();
        mScenePtr->addVertex(vertex);

        QTreeWidgetItem* itemPtr = new QTreeWidgetItem(ui->pointListBox);
        cout << "id" << ui->pointListBox->indexOfTopLevelItem(itemPtr) << endl;

        //itemPtr->setText(0,QString::number(mScenePtr->getVertexNumber()));
        //itemPtr->setText(0, QString::number(ui->pointListBox->indexOfTopLevelItem(itemPtr)));
        itemPtr->setText(0, "hjhjh");
        cout << "id" << ui->pointListBox->indexOfTopLevelItem(itemPtr) << endl;

        itemPtr->setText(1, QString::number(vertex.x));
        itemPtr->setText(2, QString::number(vertex.y));
        itemPtr->setText(3, QString::number(vertex.z));
        if (color == mScenePtr->getColor_or_texture())
        {
            itemPtr->setText(4, QString::number(vertex.r));
            itemPtr->setText(5, QString::number(vertex.g));
            itemPtr->setText(6, QString::number(vertex.b));
        }
        //ui->pointListBox->insertTopLevelItem(ui->pointListBox->topLevelItemCount(), itemPtr);

        cout << "value : " << vertex.x << endl;

    }
}

In this exemple, I click twice on the buttons, create two points with vertex.x = 0 for the first and 1 for the second.

Look at the three lines in the middle :

            //itemPtr->setText(0,QString::number(mScenePtr->getVertexNumber()));
        //itemPtr->setText(0, QString::number(ui->pointListBox->indexOfTopLevelItem(itemPtr)));
        itemPtr->setText(0, "hjhjh");

If there is only the third line, the result is

id0
id0
value : 0
id1
id1
value : 1

Everythong is ok.
But if I put one of the two others lines, the result in both cases is :

id0
id0
value : 0
id1
id0
value : 1

How is it possible ? How can the call to ui->pointListBox->indexOfTopLevelItem(itemPtr) or mScenePtr->getVertexNumber() can change the id of the item ?

Qt 5.5

Body:
After using setText, the items in the tree might have sorted automatically.

So in the two commented line cases, when you add the number (using setText), the nodes are getting sorted and the earlier node has become the top level item.

That is the reason you are seeing two different IDs "before setText" and "after setText", when you are querying "top level item".

To see the results properly, Turn off the sorting for the tree. (may be in your constructor)

ui->pointListBox->setSortingEnabled(false);


问:
How to bind FloatRatingView rating to variable using RxSwift
I am attempting to integrate this library with my RxSwift project, https://github.com/glenyi/FloatRatingView

I am unable to get the updated rating.
Here is how I have created the FloatRatingView in the Controller,

```<code>let starRater : FloatRatingView = {
let floatRatingView = FloatRatingView()
floatRatingView.emptyImage = UIImage(named: "EmptyStar")
return floatRatingView
}()
</code>```

The Model contains the following,

```<code>let my_rating = Variable<Float?>(nil)
</code>```

What I want to be able to do is to update the value in the my_rating variable when a user changes the rating by tapping on a star. Here is what I've written for this,

```<code>_ = starRater.rx.rating
   .asObservable()
   .bindTo(viewModel.my_rating.rx_value)
</code>```

But here is the error I'm receiving.

Value of type 'Reactive FloatRatingView' has no member 'rating'

Here is how I will retrieve the value from my_rating variable,

```<code>let stars = self.my_rating.value
</code>```

Kindly help me out. Thanks.

答:
You need to add a bindable sink for the property, it would be something like this:</p>

```<code>extension Reactive where Base: FloatRatingView {

    /// Bindable sink for `rating` property
    public var progress: UIBindingObserver<Base, Float> {
        return UIBindingObserver(UIElement: self.base) { floatRatingView, rating in
            floatRatingView.rating = rating
        }
    }

}
</code>```

Body:
I am attempting to integrate this library with my RxSwift project, https://github.com/glenyi/FloatRatingView

I am unable to get the updated rating.
Here is how I have created the FloatRatingView in the Controller,

let starRater : FloatRatingView = {
let floatRatingView = FloatRatingView()
floatRatingView.emptyImage = UIImage(named: "EmptyStar")
return floatRatingView
}()

The Model contains the following,

let my_rating = Variable<Float?>(nil)

What I want to be able to do is to update the value in the my_rating variable when a user changes the rating by tapping on a star. Here is what I've written for this,

_ = starRater.rx.rating
   .asObservable()
   .bindTo(viewModel.my_rating.rx_value)

But here is the error I'm receiving.

Value of type 'Reactive FloatRatingView' has no member 'rating'

Here is how I will retrieve the value from my_rating variable,

let stars = self.my_rating.value

Kindly help me out. Thanks.

Body:
You need to add a bindable sink for the property, it would be something like this:

extension Reactive where Base: FloatRatingView {

    /// Bindable sink for `rating` property
    public var progress: UIBindingObserver<Base, Float> {
        return UIBindingObserver(UIElement: self.base) { floatRatingView, rating in
            floatRatingView.rating = rating
        }
    }

}


问:
In R, find whether two files differ
I would like a pure R way to test whether two arbitrary files are different. So, the equivalent to diff -q in Unix, but should work on Windows and without external dependencies.

I'm aware of tools::Rdiff, but it seems to only want to deal with R output files and complains loudly if I feed it something else.

Title: In R, find whether two files differ

Body: all.equal(readLines(f1), readLines(f2))


问:
Python Gensim word2vec vocabulary key
I want to make word2vec with gensim. I heard that vocabulary corpus should be unicode so I converted it to unicode.

```<code># -*- encoding:utf-8 -*-
# !/usr/bin/env python
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from gensim.models import Word2Vec
import pprint

with open('parsed_data.txt', 'r') as f:
    corpus = map(unicode, f.read().split('\n'))

model = Word2Vec(size=128, window=5, min_count=5, workers=4)
model.build_vocab(corpus,keep_raw_vocab=False)
model.train(corpus)
model.save('w2v')

pprint.pprint(model.most_similar(u'너'))
</code>```

Above is my source code. It seems like work well. However there are problem with vocabulary key. I want to make korean word2vec which use unicode. For example word 사과 which means apology in english and it's unicode is \xC0AC\xACFC If I try to find 사과 in word2vec, key error occur...

Instead of \xc0ac\xacfc \xc0ac and \xacfc stores separately.
What's the reason and how to solve it?

答:
Word2Vec requires text examples that are broken into word-tokens. It appears you are simply providing strings to Word2Vec, so when it iterates over them, it will only be seeing single-characters as words.

Does Korean use spaces to delimit words? If so, break your texts by spaces before handing the list-of-words as a text example to Word2Vec.

If not, you'll need to use some external word-tokenizer (not part of gensim) before passing your sentences to Word2Vec.

Title: Python Gensim word2vec vocabulary key

Body:
I want to make word2vec with gensim. I heard that vocabulary corpus should be unicode so I converted it to unicode.

# -*- encoding:utf-8 -*-
# !/usr/bin/env python
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from gensim.models import Word2Vec
import pprint

with open('parsed_data.txt', 'r') as f:
    corpus = map(unicode, f.read().split('\n'))

model = Word2Vec(size=128, window=5, min_count=5, workers=4)
model.build_vocab(corpus,keep_raw_vocab=False)
model.train(corpus)
model.save('w2v')

pprint.pprint(model.most_similar(u'너'))

Above is my source code. It seems like work well. However there are problem with vocabulary key. I want to make korean word2vec which use unicode. For example word 사과 which means apology in english and it's unicode is \xC0AC\xACFC If I try to find 사과 in word2vec, key error occur...

Instead of \xc0ac\xacfc \xc0ac and \xacfc stores separately.
What's the reason and how to solve it?


问:
Was javascript argument default?
Is there a way to tell the difference between this

```<code>((a=true)=>{return a})(true)
</code>```

And this?

```<code>((a=true)=>{return a})()
</code>```

They both return true - how can I tell whether that true is coming from the default value of the argument, or from the value passed in to that parameter?

Is it possible from outside the function?

Is it possible from inside the function?

答:
Is there a way to tell the difference between these two?

No. Arrow function doesn't support argument object, so there is no way to check this.

But, if you are using non-arrow functions, you can get arguments number from inside the function. For example:

```<code>(function(a=true){return arguments.length;})(); // 0
(function(a=true){return arguments.length;})(true); // 1
</code>```

You can easily figure out how to extend this to multiple arguments.

Title: Was javascript argument default?

Body:
Is there a way to tell the difference between this

((a=true)=>{return a})(true)

And this?

((a=true)=>{return a})()

They both return true - how can I tell whether that true is coming from the default value of the argument, or from the value passed in to that parameter?

Is it possible from outside the function?

Is it possible from inside the function?

Body:
Is there a way to tell the difference between these two?

No. Arrow function doesn't support argument object, so there is no way to check this.

But, if you are using non-arrow functions, you can get arguments number from inside the function. For example:

(function(a=true){return arguments.length;})(); // 0
(function(a=true){return arguments.length;})(true); // 1

You can easily figure out how to extend this to multiple arguments.


问:
Exclude port number in URL - Angular2
I want to exclude the port number for my angular2 application in the URI, so far its http://localhost:3000/ instead of just being http://localhost/. I am using angular2 with webpack2. How would I go about doing this on development in dev-server, would I use a proxy?

-G

答:
A url like http://localhost actually has a port number, it's the default http port of 80. So you could configure your Angular app to simply use port 80 instead of port 3000.

Most projects use ports other than 80 because most web developers have a system-wide webserver that's already running on port 80 (Apache, nginx, etc).

Title: Exclude port number in URL - Angular2


问:
Promise with Pouch not returning from call to inside code
I have a promise that seemed to work before but not now.

I think I have everything in place but after the .get is called, it never gets to the for loop.

It jumps to the end and out of the promise, then back to the return (inside the .get) then to the resolve and then out.

If there were an error, it should have jumped to the catch but didn't, so how does it miss the for loop?

Here is the code:

```<code>    function readAllImagesFromPouch(id, imageDisplay) {

       return new Promise(function (resolve, reject) {

          var startElement = document.getElementById(imageDisplay);
          var image = "";

          // Get all attachments for this id

          DB_TaskImages.get(id, { attachments: true }).then(function (doc) {

         for (var key in doc._attachments) {

            DB_TaskImages.getAttachment(doc._id, key).then(function (blob) {
               var img = document.createElement('img');
               blob = resizeImage(blob, "100", "60");
               var url = URL.createObjectURL(blob);
               img.src = url;
               //alert(img.outerHTML);

               //startElement.appendChild(img);
               $(startElement).append("<div class='row' style='border:1px solid black'><div class='col-xs-10'>" +
                           img.outerHTML +
                           "</div>" +
                           "<div class='col-xs-1' style='padding-top:20px'>" +
                           "<img src='../Images/delete.png' alt='Delete'  class='taskimage'>" +
                           "</div></div>"
                        );
               return;
            }).catch(function () {
               console.log("No attachment for doc._id: " + doc._id + " and key: " + key);
            })
         }
         return;
          }).then(function () {
            resolve();
          }).catch(function (err) {
         console.log("Image not there for id: " + id);
         showMsg("Image not there for id: " + id);
         reject(err);
          })
       });         // end of promise
    }
</code>```

And it is called from this code:

```<code>    readAllImagesFromPouch("006", "divImages").then(function () {
    }).catch(function (err) {
       console.log("In catch for readAllImagesFromPouch with err: " + err);
    })
</code>```

Thanks,

Tom

答:
Firstly, avoid the promise constructor anti-pattern. As DB_TaskImages.get returns a promise, you don't need to create one

Secondly, your for...in loop kicks off a bunch of asynchronous tasks - but you don't actually wait for them to complete

A possible rewrite of your code is:

```<code>function readAllImagesFromPouch(id, imageDisplay) {

    var startElement = document.getElementById(imageDisplay);
    var image = "";

    // Get all attachments for this id

    return DB_TaskImages.get(id, {
        attachments: true
    })
    .then(function(doc) {
        // a promise to chain to - all following tasks will be performed in series, not parallel - this can be changed
        var promise = Promise.resolve();
        Object.keys(doc._attachments).forEach(function(key) {
            promise = promise.then(function() {
                return DB_TaskImages.getAttachment(doc._id, key)
                .then(function(blob) {
                    var img = document.createElement('img');
                    blob = resizeImage(blob, "100", "60");
                    var url = URL.createObjectURL(blob);
                    img.src = url;
                    //alert(img.outerHTML);

                    //startElement.appendChild(img);
                    $(startElement).append("<div class='row' style='border:1px solid black'><div class='col-xs-10'>" +
                                           img.outerHTML +
                                           "</div>" +
                                           "<div class='col-xs-1' style='padding-top:20px'>" +
                                           "<img src='../Images/delete.png' alt='Delete'  class='taskimage'>" +
                                           "</div></div>"
                                          );
                    return;
                })
                .catch(function() {
                    console.log("No attachment for doc._id: " + doc._id + " and key: " + key);
                })
            });
        });
        return promise;
    })
    .catch(function(err) {
        console.log("Image not there for id: " + id);
        showMsg("Image not there for id: " + id);
        throw err;
    })
}
</code>```

The above code will call DB_TaskImages.getAttachment(doc._id, key) in series.

If you can and want to execute DB_TaskImages.getAttachment(doc._id, key) in parallel, the code needs a little more work

```<code>function readAllImagesFromPouch(id, imageDisplay) {

    var startElement = document.getElementById(imageDisplay);
    var image = "";

    // Get all attachments for this id

    return DB_TaskImages.get(id, {
        attachments: true
    })
    .then(function(doc) {
        return Promise.all(Object.keys(doc._attachments)
            .map(function(key) {
                return DB_TaskImages.getAttachment(doc._id, key)
                // an error here should NOT reject the Promise.all, so handle the error and return undefined
                .catch(function() {
                    console.log("No attachment for doc._id: " + doc._id + " and key: " + key);
                })
            })
        );
    })
    .then(function(blobs) {
        return blobs.filter(function(blob) {
            // a failed .getAttachment results in an undefined result here, so ignore it
            return blob !== undefined;
        }).forEach(function(blob) {
            var img = document.createElement('img');
            blob = resizeImage(blob, "100", "60");
            var url = URL.createObjectURL(blob);
            img.src = url;
            $(startElement).append(
                "<div class='row' style='border:1px solid black'>" +
                    "<div class='col-xs-10'>" +
                        img.outerHTML +
                    "</div>" +
                    "<div class='col-xs-1' style='padding-top:20px'>" +
                        "<img src='../Images/delete.png' alt='Delete'  class='taskimage'>" +
                    "</div>" +
                "</div>"
            );
        });
    })
    .catch(function(err) {
        console.log("Image not there for id: " + id);
        showMsg("Image not there for id: " + id);
        throw err;
    })
}
</code>```

Body:
I have a promise that seemed to work before but not now.

I think I have everything in place but after the .get is called, it never gets to the for loop.

It jumps to the end and out of the promise, then back to the return (inside the .get) then to the resolve and then out.

If there were an error, it should have jumped to the catch but didn't, so how does it miss the for loop?

Here is the code:

    function readAllImagesFromPouch(id, imageDisplay) {

       return new Promise(function (resolve, reject) {

          var startElement = document.getElementById(imageDisplay);
          var image = "";

          // Get all attachments for this id

          DB_TaskImages.get(id, { attachments: true }).then(function (doc) {

         for (var key in doc._attachments) {

            DB_TaskImages.getAttachment(doc._id, key).then(function (blob) {
               var img = document.createElement('img');
               blob = resizeImage(blob, "100", "60");
               var url = URL.createObjectURL(blob);
               img.src = url;
               //alert(img.outerHTML);

               //startElement.appendChild(img);
               $(startElement).append("

" +
                           img.outerHTML +
                           "
" +
                           "
" +
                           "" +
                           "

"
                        );
               return;
            }).catch(function () {
               console.log("No attachment for doc._id: " + doc._id + " and key: " + key);
            })
         }
         return;
          }).then(function () {
            resolve();
          }).catch(function (err) {
         console.log("Image not there for id: " + id);
         showMsg("Image not there for id: " + id);
         reject(err);
          })
       });         // end of promise
    }

And it is called from this code:

    readAllImagesFromPouch("006", "divImages").then(function () {
    }).catch(function (err) {
       console.log("In catch for readAllImagesFromPouch with err: " + err);
    })

Thanks,

Tom

Body:
Firstly, avoid the promise constructor anti-pattern. As DB_TaskImages.get returns a promise, you don't need to create one

Secondly, your for...in loop kicks off a bunch of asynchronous tasks - but you don't actually wait for them to complete

A possible rewrite of your code is:

function readAllImagesFromPouch(id, imageDisplay) {

    var startElement = document.getElementById(imageDisplay);
    var image = "";

    // Get all attachments for this id

    return DB_TaskImages.get(id, {
        attachments: true
    })
    .then(function(doc) {
        // a promise to chain to - all following tasks will be performed in series, not parallel - this can be changed
        var promise = Promise.resolve();
        Object.keys(doc._attachments).forEach(function(key) {
            promise = promise.then(function() {
                return DB_TaskImages.getAttachment(doc._id, key)
                .then(function(blob) {
                    var img = document.createElement('img');
                    blob = resizeImage(blob, "100", "60");
                    var url = URL.createObjectURL(blob);
                    img.src = url;
                    //alert(img.outerHTML);

                    //startElement.appendChild(img);
                    $(startElement).append("<div class='row' style='border:1px solid black'><div class='col-xs-10'>" +
                                           img.outerHTML +
                                           "</div>" +
                                           "<div class='col-xs-1' style='padding-top:20px'>" +
                                           "<img src='../Images/delete.png' alt='Delete'  class='taskimage'>" +
                                           "</div></div>"
                                          );
                    return;
                })
                .catch(function() {
                    console.log("No attachment for doc._id: " + doc._id + " and key: " + key);
                })
            });
        });
        return promise;
    })
    .catch(function(err) {
        console.log("Image not there for id: " + id);
        showMsg("Image not there for id: " + id);
        throw err;
    })
}

The above code will call DB_TaskImages.getAttachment(doc._id, key) in series.

If you can and want to execute DB_TaskImages.getAttachment(doc._id, key) in parallel, the code needs a little more work

function readAllImagesFromPouch(id, imageDisplay) {

    var startElement = document.getElementById(imageDisplay);
    var image = "";

    // Get all attachments for this id

    return DB_TaskImages.get(id, {
        attachments: true
    })
    .then(function(doc) {
        return Promise.all(Object.keys(doc._attachments)
            .map(function(key) {
                return DB_TaskImages.getAttachment(doc._id, key)
                // an error here should NOT reject the Promise.all, so handle the error and return undefined
                .catch(function() {
                    console.log("No attachment for doc._id: " + doc._id + " and key: " + key);
                })
            })
        );
    })
    .then(function(blobs) {
        return blobs.filter(function(blob) {
            // a failed .getAttachment results in an undefined result here, so ignore it
            return blob !== undefined;
        }).forEach(function(blob) {
            var img = document.createElement('img');
            blob = resizeImage(blob, "100", "60");
            var url = URL.createObjectURL(blob);
            img.src = url;
            $(startElement).append(
                "<div class='row' style='border:1px solid black'>" +
                    "<div class='col-xs-10'>" +
                        img.outerHTML +
                    "</div>" +
                    "<div class='col-xs-1' style='padding-top:20px'>" +
                        "<img src='../Images/delete.png' alt='Delete'  class='taskimage'>" +
                    "</div>" +
                "</div>"
            );
        });
    })
    .catch(function(err) {
        console.log("Image not there for id: " + id);
        showMsg("Image not there for id: " + id);
        throw err;
    })
}


问:
Remove web element from the IList <IWebElement> using C# in Selenium
I'm actually trying to remove the element from IList if certain condition occurs, but seems like I'm getting the same list .Count number. Below is my code:

```<code>    [FindsBy(How = How.XPath, Using = "//button[@aria-label='delete']")]
    private IList <IWebElement> _deleteIcons;

******** SOME CODE HERE **********

    for (var i = 0; i<_deleteIcons.Count; i++)
                {
                    if (_deleteIcons[i].GetAttribute("disabled").Contains("true"))
                    {
                        _deleteIcons.RemoveAt(i);
                    }
                }
    Debug.WriteLine(_deleteIcons.Count);
</code>```

Imagine there are 6 total elements in the IList, and 2 of them contain "disabled" =="true" At the end I would like to write to debug console the variable count and see 4.  Currently once the piece of code is run, I still get the same amount of 6 elements in IList.

答:
The easiest way to do this is to use a CSS selector and just select those buttons that are not disabled. It will be faster and you won't need to filter afterwards.</p>

```<code>"button[aria-label='delete']:not([disabled])"
</code>```

Body:
I'm actually trying to remove the element from IList if certain condition occurs, but seems like I'm getting the same list .Count number. Below is my code:

    [FindsBy(How = How.XPath, Using = "//button[@aria-label='delete']")]
    private IList <IWebElement> _deleteIcons;

******** SOME CODE HERE **********

    for (var i = 0; i<_deleteIcons.Count; i++)
                {
                    if (_deleteIcons[i].GetAttribute("disabled").Contains("true"))
                    {
                        _deleteIcons.RemoveAt(i);
                    }
                }
    Debug.WriteLine(_deleteIcons.Count);

Imagine there are 6 total elements in the IList, and 2 of them contain "disabled" =="true" At the end I would like to write to debug console the variable count and see 4.  Currently once the piece of code is run, I still get the same amount of 6 elements in IList.

Body:
The easiest way to do this is to use a CSS selector and just select those buttons that are not disabled. It will be faster and you won't need to filter afterwards.

"button[aria-label='delete']:not([disabled])"


问:
Disappear horizontal scroll
I've a problem with my layout. It seems like a horizontal scroll appears on the screen and I don't want that. I already tried to find the problem but I can't see it.
You can see the whole code in codepen.
click to open codepen

```<code>.header{
   background:rgb(230, 94, 94);
   width:8vw;
   height:100%;
   position: fixed;
   left:0px;
   bottom:0px;
 }
</code>```

Maybe the problem is the above code, but I recommend you that enter to codepen link to see all CSS and html.
You should change the view to editor view.
I hope somebody can find the problem because I can't see it,  by the wa, I'm new in HTML & CSS that means maybe it's a fool problem.
Thanks and good luck!

答:
If you reduce that viewport width set on your div main-content a little you might get what you want.
example set width to 99vw;

```<code>.main-content{
    width:100vw;
    background:white;
    padding-left:8vw;
  width:99vw;
}
</code>```

codepen here

Title: Disappear horizontal scroll

Body:
I've a problem with my layout. It seems like a horizontal scroll appears on the screen and I don't want that. I already tried to find the problem but I can't see it.
You can see the whole code in codepen.
click to open codepen

.header{
   background:rgb(230, 94, 94);
   width:8vw;
   height:100%;
   position: fixed;
   left:0px;
   bottom:0px;
 }

Maybe the problem is the above code, but I recommend you that enter to codepen link to see all CSS and html.
You should change the view to editor view.
I hope somebody can find the problem because I can't see it,  by the wa, I'm new in HTML & CSS that means maybe it's a fool problem.
Thanks and good luck!

Body:
If you reduce that viewport width set on your div main-content a little you might get what you want.
example set width to 99vw;

.main-content{
    width:100vw;
    background:white;
    padding-left:8vw;
  width:99vw;
}

codepen here


问:
Auto-injection custom ErrorHandler in spring-rabbitmq
We know that we can inject custom message converter:

```<code>@Bean
MessageConverter messageConverter(){
   return new CustomMessageConverter();
}
</code>```

However in case of ErrorHandler it doesn't work. Why ?  Can I conclude it from code in any way ?

答:
That's true. Spring Boot's RabbitAnnotationDrivenConfiguration doesn't support that injection.

You have to declare your own SimpleRabbitListenerContainerFactory @Bean and supply desired ErrorHandler injection, as well as all other required options, including MessageConverter.

Note that overriding out-of-the-box bean you should specify your own one with the rabbitListenerContainerFactory name to meet condition:

```<code>@Bean
@ConditionalOnMissingBean(name = "rabbitListenerContainerFactory")
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
</code>```

Body:
We know that we can inject custom message converter:

@Bean
MessageConverter messageConverter(){
   return new CustomMessageConverter();
}

However in case of ErrorHandler it doesn't work. Why ?  Can I conclude it from code in any way ?

Body:
That's true. Spring Boot's RabbitAnnotationDrivenConfiguration doesn't support that injection.

You have to declare your own SimpleRabbitListenerContainerFactory @Bean and supply desired ErrorHandler injection, as well as all other required options, including MessageConverter.

Note that overriding out-of-the-box bean you should specify your own one with the rabbitListenerContainerFactory name to meet condition:

@Bean
@ConditionalOnMissingBean(name = "rabbitListenerContainerFactory")
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(


问:
How to draw multiple line graph by using matplotlib in Python
I want to create a Full 12 Leads EKG graph by using matplotlib in Python 2.7, so I had already wrote down some code to represent each lead (using subplot), but it have an issue about drawing a grid on sub-graph. Then I try to find a new solution to ploy all 12 leads within the same graph like this picture below

I have the list of data like this....

```<code>x = [1,2,3,4,5,....]
lead1 = [-39,-34,-36,-38,.... ]
lead2 = [-40,-44,-86,-28,.... ]
.
.
lead12 = [-30,-27,-80,-69,.... ]
</code>```

Could you give me some example code or the direction of how to make that.

Thank you very much.

答:
Here is a simple example, where all lines are plotted in the same axes, but offset by 3 units in y direction.

```<code>import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

s=3
x = np.linspace(0,10,2000)
a = np.sin(np.cumsum((np.random.normal(scale=0.1, size=(len(x), 12))), axis=0))

fig, ax = plt.subplots()
for i in range(a.shape[1]):
    ax.plot(x, a[:,i]+s*i)

labels = ["PG{}".format(i) for i in range(a.shape[1])]
ax.set_yticks(np.arange(0,a.shape[1])*s)
ax.set_yticklabels(labels)
for t, l in zip(ax.get_yticklabels(), ax.lines):
    t.set_color(l.get_color())

plt.show()
</code>```

Body:
I want to create a Full 12 Leads EKG graph by using matplotlib in Python 2.7, so I had already wrote down some code to represent each lead (using subplot), but it have an issue about drawing a grid on sub-graph. Then I try to find a new solution to ploy all 12 leads within the same graph like this picture below

I have the list of data like this....

x = [1,2,3,4,5,....]
lead1 = [-39,-34,-36,-38,.... ]
lead2 = [-40,-44,-86,-28,.... ]
.
.
lead12 = [-30,-27,-80,-69,.... ]

Could you give me some example code or the direction of how to make that.

Thank you very much.

Body:
Here is a simple example, where all lines are plotted in the same axes, but offset by 3 units in y direction.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

s=3
x = np.linspace(0,10,2000)
a = np.sin(np.cumsum((np.random.normal(scale=0.1, size=(len(x), 12))), axis=0))

fig, ax = plt.subplots()
for i in range(a.shape[1]):
    ax.plot(x, a[:,i]+s*i)

labels = ["PG{}".format(i) for i in range(a.shape[1])]
ax.set_yticks(np.arange(0,a.shape[1])*s)
ax.set_yticklabels(labels)
for t, l in zip(ax.get_yticklabels(), ax.lines):
    t.set_color(l.get_color())

plt.show()


问:
How do i know if there are records stored in my mysql database?
I have 2 php files. One of them creates a table and inserts data into MySql using php. The other php selects the table in the database and outputs the data from the table. The table is outputting 0 results as in there aren't any record being stored into the table.

Need help, Thanks!

//select from table

    $sql = "SELECT * FROM post02";
                $result = mysql_query($link, $sql);
    echo 'selecting table works';

    //output from table

    if (mysql_num_rows($result) > 0) {
        while($row = mysql_fetch_assoc($result)) {

                    echo "id: " . $row["id"]. " - Name: " . $row["title"]. " " . $row["content"]. ""  . $row["date"]."
";

                    }
    } else {
        echo "0 results";
    }
   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>// create a table

 $sql="create table post02(id INT(6) unsigned auto_increment primary key , title varchar(30) not null, content varchar(255) not null, date TIMESTAMP)";

 $result = mysql_query($sql);

 if (! $result ) {

     die ( 'Cant create table : '  .  mysql_error ());

 }

  echo  'Created a table successfuly' ;

//insert to table
 echo'insert table - initializing';

 if($_POST['submit']){
 $title = $_POST['title'];
 $content = $_POST['content'];
 $date = date('l jS \of F Y h:i:s A');
 }

 $sql = "INSERT INTO post02(title, content, date) VALUES ($title, $content,$date))";

 if($title =="" || $content=="" ){
     echo "please compelete your post!";
     return;

 }
 echo'insert table completed';

     mysql_query($db ,$sql);
    header("location: viewblog.php");</code>```

答: mysql_query accepts query as first parameter & connection string as second parameter. Try interchanging in all the locations in your code. Or you can remove the link parameter</p>

Body:
I have 2 php files. One of them creates a table and inserts data into MySql using php. The other php selects the table in the database and outputs the data from the table. The table is outputting 0 results as in there aren't any record being stored into the table.

Need help, Thanks!

//select from table

    $sql = "SELECT * FROM post02";
                $result = mysql_query($link, $sql);
    echo 'selecting table works';

    //output from table

    if (mysql_num_rows($result) > 0) {
        while($row = mysql_fetch_assoc($result)) {

                    echo "id: " . $row["id"]. " - Name: " . $row["title"]. " " . $row["content"]. ""  . $row["date"]."
";

                    }
    } else {
        echo "0 results";
    }

// create a table

 $sql="create table post02(id INT(6) unsigned auto_increment primary key , title varchar(30) not null, content varchar(255) not null, date TIMESTAMP)";

 $result = mysql_query($sql);

 if (! $result ) {

     die ( 'Cant create table : '  .  mysql_error ());

 }

  echo  'Created a table successfuly' ;

//insert to table
 echo'insert table - initializing';

 if($_POST['submit']){
 $title = $_POST['title'];
 $content = $_POST['content'];
 $date = date('l jS \of F Y h:i:s A');
 }

 $sql = "INSERT INTO post02(title, content, date) VALUES ($title, $content,$date))";

 if($title =="" || $content=="" ){
     echo "please compelete your post!";
     return;

 }
 echo'insert table completed';

     mysql_query($db ,$sql);
    header("location: viewblog.php");


问:
Checked static cast on a reference
Long ago I have created a following template so that I get an assert whenever I perform a static_cast but the type is not what I assume it to be:

```<code>/// perform a static_cast asserted by a dynamic_cast
template <class Type, class SourceType>
Type static_cast_checked(SourceType item)
{
  Assert(!item || dynamic_cast<Type>(item));
  return static_cast<Type>(item);
}
</code>```

Today I wanted to create a variant which would work not only with pointers, but with references as well:

```<code>/// overload for reference
template <class Type, class SourceType>
Type &static_cast_checked(SourceType &item)
{
  Assert(dynamic_cast<Type *>(&item));
  return static_cast<Type>(item);
}
</code>```

However, the compiler does not seem to use this overload when I am casting a reference to another reference. I am afraid I do not understand template resolution rules enough to understand why, or to be able to create a variant which works.

Note: I cannot catch the bad_cast exception instead of checking dynamic_cast<Type *> for NULL, as exceptions are disabled for this project.

答:
Remove * and & from the return types:

```<code>/// perform a static_cast asserted by a dynamic_cast
template <class Type, class SourceType>
Type static_cast_checked(SourceType *item)
{
  Assert(!item || dynamic_cast<Type>(item));
  return static_cast<Type>(item);
}

template <class Type> struct make_pointer
{
    typedef Type *PointerType;
};

template <class Type> struct make_pointer<Type &>
{
    typedef Type *PointerType;
};

/// overload for reference
template <class Type, class SourceType>
Type static_cast_checked(SourceType &item)
{
  Assert(dynamic_cast<typename make_pointer<Type>::PointerType>(&item));
  return static_cast<Type>(item);
}
</code>```

Then you can use your desired syntax:

```<code>Derived *d= static_cast_checked<Derived *>(b);
Derived &d= static_cast_checked<Derived &>(b);
</code>```

EDIT: added a pointer type conversion.

Title: Checked static cast on a reference

Body:
Long ago I have created a following template so that I get an assert whenever I perform a static_cast but the type is not what I assume it to be:

/// perform a static_cast asserted by a dynamic_cast
template <class Type, class SourceType>
Type static_cast_checked(SourceType item)
{
  Assert(!item || dynamic_cast<Type>(item));
  return static_cast<Type>(item);
}

Today I wanted to create a variant which would work not only with pointers, but with references as well:

/// overload for reference
template <class Type, class SourceType>
Type &static_cast_checked(SourceType &item)
{
  Assert(dynamic_cast<Type *>(&item));
  return static_cast<Type>(item);
}

However, the compiler does not seem to use this overload when I am casting a reference to another reference. I am afraid I do not understand template resolution rules enough to understand why, or to be able to create a variant which works.

Note: I cannot catch the bad_cast exception instead of checking dynamic_cast<Type *> for NULL, as exceptions are disabled for this project.

Body:
Remove * and & from the return types:

/// perform a static_cast asserted by a dynamic_cast
template <class Type, class SourceType>
Type static_cast_checked(SourceType *item)
{
  Assert(!item || dynamic_cast<Type>(item));
  return static_cast<Type>(item);
}

template <class Type> struct make_pointer
{
    typedef Type *PointerType;
};

template <class Type> struct make_pointer<Type &>
{
    typedef Type *PointerType;
};

/// overload for reference
template <class Type, class SourceType>
Type static_cast_checked(SourceType &item)
{
  Assert(dynamic_cast<typename make_pointer<Type>::PointerType>(&item));
  return static_cast<Type>(item);
}

Then you can use your desired syntax:

Derived *d= static_cast_checked<Derived *>(b);
Derived &d= static_cast_checked<Derived &>(b);

EDIT: added a pointer type conversion.


问:
Updating table with business day and calendar day
I have a table in SQL Server 2012 that is updated manually every month to reflect what date is a file expected to come in.  The date rule already has values but the expected date column is what is updated manually.  If its expected on BD1(Business Day 1) I will update to the first non-weekend day of the month.  If its expected on CD1(Calenday Day 1) I will update to the 1st regardless if it falls on a weekday or a weekend and so forth.  Is it possible to write an update query where it would loop through the values and update automatically?  I'm having trouble figuring out to update to the correct business day.

```
date rule  | March expected date | April expected date |
--------------------------------------------------------
| BD1      | 3/1/2017            | 4/3/2017            |
| BD2      | 3/2/2017            |                     |
| BD3      | 3/3/2017            |                     |
| BD4      | 3/6/2017            |                     |
| BD5      |                     |                     |
| BD6      |                     |                     |
| CD1      | 3/1/2017            |                     |
| CD2      | 3/2/2017            |                     |
| CD3      | 3/3/2017            |                     |
| CD4      | 3/4/2017            |                     |
| CD5      | 3/5/2017            |                     |
| CD6      | 3/6/2017            |                     |

```

I was using the following code to calculate the first business day

```<code>SELECT DATEADD(DAY,
CASE
    (DATEPART(WEEKDAY, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) + @@DATEFIRST - 1) % 7
    WHEN 6 THEN 2
    WHEN 7 THEN 1
    ELSE 0
END,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
</code>```

)

but then when it would come to business day 4, it would give me 3/4/2017 which is a saturday instead of 3/6/2017 which is the following monday.  i'm getting stumped in how to tackle this.  I'm thinking a loop update query would be best

答:
A calendar/tally table would do the trick, but we can use an ad-hod tally table.

```<code>Declare @Date1 date = '2017-03-01'
Declare @Date2 date = EOMonth(@Date1)

Select *
 From (
        Select Date    = D
              ,WeekDay = DateName(WEEKDAY,D)
              ,DayCode = concat('BD',Row_Number() over(Order By D))
         From (Select Top (DateDiff(DD,@Date1,@Date2)+1) D=DateAdd(DD,-1+Row_Number() Over (Order By Number),@Date1) From  master..spt_values) A
         Where DateName(WEEKDAY,D) Not in ('Saturday','Sunday')
        Union All
        Select Date    = D
              ,WeekDay = DateName(WEEKDAY,D)
              ,DayCode = concat('CD',Row_Number() over(Order By D))
         From (Select Top (DateDiff(DD,@Date1,@Date2)+1) D=DateAdd(DD,-1+Row_Number() Over (Order By Number),@Date1) From  master..spt_values) A
      ) A
 Where substring(DayCode,3,2)<=6
</code>```

Returns

```<code>Date        WeekDay     DayCode
2017-03-01  Wednesday   BD1
2017-03-02  Thursday    BD2
2017-03-03  Friday      BD3
2017-03-06  Monday      BD4  --< Notice BD4 is Monday
2017-03-07  Tuesday     BD5
2017-03-08  Wednesday   BD6
2017-03-01  Wednesday   CD1
2017-03-02  Thursday    CD2
2017-03-03  Friday      CD3
2017-03-04  Saturday    CD4
2017-03-05  Sunday      CD5
2017-03-06  Monday      CD6
</code>```

Body:
I have a table in SQL Server 2012 that is updated manually every month to reflect what date is a file expected to come in.  The date rule already has values but the expected date column is what is updated manually.  If its expected on BD1(Business Day 1) I will update to the first non-weekend day of the month.  If its expected on CD1(Calenday Day 1) I will update to the 1st regardless if it falls on a weekday or a weekend and so forth.  Is it possible to write an update query where it would loop through the values and update automatically?  I'm having trouble figuring out to update to the correct business day.

date rule  | March expected date | April expected date |
--------------------------------------------------------
| BD1      | 3/1/2017            | 4/3/2017            |
| BD2      | 3/2/2017            |                     |
| BD3      | 3/3/2017            |                     |
| BD4      | 3/6/2017            |                     |
| BD5      |                     |                     |
| BD6      |                     |                     |
| CD1      | 3/1/2017            |                     |
| CD2      | 3/2/2017            |                     |
| CD3      | 3/3/2017            |                     |
| CD4      | 3/4/2017            |                     |
| CD5      | 3/5/2017            |                     |
| CD6      | 3/6/2017            |                     |

I was using the following code to calculate the first business day

SELECT DATEADD(DAY,
CASE
    (DATEPART(WEEKDAY, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) + @@DATEFIRST - 1) % 7
    WHEN 6 THEN 2
    WHEN 7 THEN 1
    ELSE 0
END,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)

)

but then when it would come to business day 4, it would give me 3/4/2017 which is a saturday instead of 3/6/2017 which is the following monday.  i'm getting stumped in how to tackle this.  I'm thinking a loop update query would be best

Body:
A calendar/tally table would do the trick, but we can use an ad-hod tally table.

Declare @Date1 date = '2017-03-01'
Declare @Date2 date = EOMonth(@Date1)

Select *
 From (
        Select Date    = D
              ,WeekDay = DateName(WEEKDAY,D)
              ,DayCode = concat('BD',Row_Number() over(Order By D))
         From (Select Top (DateDiff(DD,@Date1,@Date2)+1) D=DateAdd(DD,-1+Row_Number() Over (Order By Number),@Date1) From  master..spt_values) A
         Where DateName(WEEKDAY,D) Not in ('Saturday','Sunday')
        Union All
        Select Date    = D
              ,WeekDay = DateName(WEEKDAY,D)
              ,DayCode = concat('CD',Row_Number() over(Order By D))
         From (Select Top (DateDiff(DD,@Date1,@Date2)+1) D=DateAdd(DD,-1+Row_Number() Over (Order By Number),@Date1) From  master..spt_values) A
      ) A
 Where substring(DayCode,3,2)<=6

Returns

Date        WeekDay     DayCode
2017-03-01  Wednesday   BD1
2017-03-02  Thursday    BD2
2017-03-03  Friday      BD3
2017-03-06  Monday      BD4  --< Notice BD4 is Monday
2017-03-07  Tuesday     BD5
2017-03-08  Wednesday   BD6
2017-03-01  Wednesday   CD1
2017-03-02  Thursday    CD2
2017-03-03  Friday      CD3
2017-03-04  Saturday    CD4
2017-03-05  Sunday      CD5
2017-03-06  Monday      CD6


问:
NAudio Asio Unsupported sourceStream format
I read everything I can about NAudio but I can't get a solution here.

The project is a VS C# Windows form.

Testing with NAudio and ASIO4All is successful with mono and stereo wav files but trying to play a 8 ch. (44k/16bits) wav file always give an "Unsupported sourceStream format" error. Is it a NAudio limitation? Any idea?

The 8 ch. wav file tested plays perfectly in Asio capable players...

```<code>void nAudioPlay()
    {
        wave = new WaveFileReader("piano2.wav");
        output = new AsioOut("ASIO4ALL v2");
        output.Init(new WaveChannel32(wave));
        output.Play();
    }
</code>```

答:
Have you tryed to use</p>

```<code>output.Init(wave);
</code>```

Body:
I read everything I can about NAudio but I can't get a solution here.

The project is a VS C# Windows form.

Testing with NAudio and ASIO4All is successful with mono and stereo wav files but trying to play a 8 ch. (44k/16bits) wav file always give an "Unsupported sourceStream format" error. Is it a NAudio limitation? Any idea?

The 8 ch. wav file tested plays perfectly in Asio capable players...

void nAudioPlay()
    {
        wave = new WaveFileReader("piano2.wav");
        output = new AsioOut("ASIO4ALL v2");
        output.Init(new WaveChannel32(wave));
        output.Play();
    }

Body:
Have you tryed to use

output.Init(wave);


问:
Split 1 column into 3 columns in spark scala
I have a dataframe in Spark using scala that has a column that I need split.

```<code>scala> test.show
+-------------+
|columnToSplit|
+-------------+
|        a.b.c|
|        d.e.f|
+-------------+
</code>```

I need this column split out to look like this:

```<code>+--------------+
|col1|col2|col3|
|   a|   b|   c|
|   d|   e|   f|
+--------------+
</code>```

I'm using Spark 2.0.0

Thanks

答:
A solution which avoids the select part. This is helpful when you just want to append the new columns:

```<code>case class Message(others: String, text: String)

val r1 = Message("foo1", "a.b.c")
val r2 = Message("foo2", "d.e.f")

val records = Seq(r1, r2)
val df = spark.createDataFrame(records)

df.withColumn("col1", split(col("text"), "\\.").getItem(0))
  .withColumn("col2", split(col("text"), "\\.").getItem(1))
  .withColumn("col3", split(col("text"), "\\.").getItem(2))
  .show(false)

+------+-----+----+----+----+
|others|text |col1|col2|col3|
+------+-----+----+----+----+
|foo1  |a.b.c|a   |b   |c   |
|foo2  |d.e.f|d   |e   |f   |
+------+-----+----+----+----+
</code>```

Update: I highly recommend to use Psidom's implementation to avoid splitting three times.

Body:
I have a dataframe in Spark using scala that has a column that I need split.

scala> test.show
+-------------+
|columnToSplit|
+-------------+
|        a.b.c|
|        d.e.f|
+-------------+

I need this column split out to look like this:

+--------------+
|col1|col2|col3|
|   a|   b|   c|
|   d|   e|   f|
+--------------+

I'm using Spark 2.0.0

Thanks

Body:
A solution which avoids the select part. This is helpful when you just want to append the new columns:

case class Message(others: String, text: String)

val r1 = Message("foo1", "a.b.c")
val r2 = Message("foo2", "d.e.f")

val records = Seq(r1, r2)
val df = spark.createDataFrame(records)

df.withColumn("col1", split(col("text"), "\\.").getItem(0))
  .withColumn("col2", split(col("text"), "\\.").getItem(1))
  .withColumn("col3", split(col("text"), "\\.").getItem(2))
  .show(false)

+------+-----+----+----+----+
|others|text |col1|col2|col3|
+------+-----+----+----+----+
|foo1  |a.b.c|a   |b   |c   |
|foo2  |d.e.f|d   |e   |f   |
+------+-----+----+----+----+

Update: I highly recommend to use Psidom's implementation to avoid splitting three times.


答: Why are these on your code "mysql_query($db ,$sql);" and " mysql_query($link, $sql);" mysql_query takes just one parameter</p>

Title: How do i know if there are records stored in my mysql database?


问:
Spark route resolution using queryMap
I am using Spark java for my API. I have the following urls

```<code>get("/template/:id") -> controller.getById(req, res).handle(req, res)
get("/template/:name") -> controller.getByName(req, res).handle(req, res)
</code>```

Now my method getByName won't be call as the request will always map it to :id call. So is there a way I can handle this in spark-java. QueryMap might be useful I guess but I don't how to use it.

答:
Two possible solutions you can use:

Create two different routes:

get("/template/id/:id") -> controller.getById(req, res).handle(req, res);
get("/template/name/:name") -> controller.getByName(req, res).handle(req,res);

Create only one route and use params:

get("/template") -> controller.getByIdName(req, res).handle(req, res);

And then call it with the params you want, for example:
"/template?id=1234&name=Joe" and parse the params inside getByIdName using req.queryParams("id") and req.queryParams("name")

Title: Spark route resolution using queryMap

Body:
I am using Spark java for my API. I have the following urls

get("/template/:id") -> controller.getById(req, res).handle(req, res)
get("/template/:name") -> controller.getByName(req, res).handle(req, res)

Now my method getByName won't be call as the request will always map it to :id call. So is there a way I can handle this in spark-java. QueryMap might be useful I guess but I don't how to use it.


问:
Android app using LipeRMI is connecting to server but not calling the method
I have an android app and a server, both using lipeRMI.
My android app successfully connects to the server. But the method it's supposed to call, is not being called.

Server Code:

```<code>public interface TestService {

public String getResponse(String data);
}

public class TestServer implements TestService {
public TestServer() {
    try {
        CallHandler callHandler = new CallHandler();
        callHandler.registerGlobal(TestService.class, this);
        Server server = new Server();
        server.bind(7777, callHandler);
        server.addServerListener(new IServerListener() {

            @Override
            public void clientDisconnected(Socket socket) {
                System.out.println("Client Disconnected: " + socket.getInetAddress());
            }

            @Override
            public void clientConnected(Socket socket) {
                System.out.println("Client Connected: " + socket.getInetAddress());
            }
        });
        System.out.println("Server Listening");
    } catch (LipeRMIException | IOException e) {
        e.printStackTrace();
    }
}

@Override
public String getResponse(String data) {
    System.out.println("getResponse called");
    return "Your data: " + data;
}

public static void main(String[] args) {
    TestServer testServer = new TestServer();
}

}
</code>```

The android code:

```<code>interface TestService {

public String getResponse(String data);
}

public class MainActivity extends Activity {

private String serverIP = "192.168.1.7";
EditText et= null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnGet = (Button) findViewById(R.id.button1);
    et= (EditText)findViewById(R.id.editText2);
    btnGet.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            new Conn().execute();
        }
    });

}
class Conn extends AsyncTask<Void, Void, MainActivity> {

    @Override
    protected MainActivity doInBackground(Void... params) {
        Looper.prepare();

        try {
            Toast.makeText(MainActivity.this, "Inside conn my nigga", Toast.LENGTH_SHORT).show();
            CallHandler callHandler = new CallHandler();
            Client client = new Client(serverIP, 7777, callHandler);
            TestService testService = (TestService) client.getGlobal(TestService.class);
            String msg = testService.getResponse("qwe");
            //Toast.makeText(MainActivity.this, testService.getResponse("abc"), Toast.LENGTH_SHORT).show();
            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Looper.loop();
        return null;
    }

}
}
</code>```

I tried using the above code also using a simple Runnable thread instead of AsyncTask(I was paranoid AsyncTask'd be causing the problem) but it went in vain.

The server gives this output:

```<code>Server Listening
Client Connected: /192.168.1.5
Client Disconnected: /192.168.1.5
</code>```

No matter how many times I click the Button1 of my android app.
Any help will be really appreciated. :)
Thank you for your time!

答:
I had this situation when packages were different. You should make sure that TestService packages are same at Android application and server.
If you use your own class in TestService interface, it should have same packages too and should implement Serializable.

Body:
I have an android app and a server, both using lipeRMI.
My android app successfully connects to the server. But the method it's supposed to call, is not being called.

Server Code:

public interface TestService {

public String getResponse(String data);
}

public class TestServer implements TestService {
public TestServer() {
    try {
        CallHandler callHandler = new CallHandler();
        callHandler.registerGlobal(TestService.class, this);
        Server server = new Server();
        server.bind(7777, callHandler);
        server.addServerListener(new IServerListener() {

            @Override
            public void clientDisconnected(Socket socket) {
                System.out.println("Client Disconnected: " + socket.getInetAddress());
            }

            @Override
            public void clientConnected(Socket socket) {
                System.out.println("Client Connected: " + socket.getInetAddress());
            }
        });
        System.out.println("Server Listening");
    } catch (LipeRMIException | IOException e) {
        e.printStackTrace();
    }
}

@Override
public String getResponse(String data) {
    System.out.println("getResponse called");
    return "Your data: " + data;
}

public static void main(String[] args) {
    TestServer testServer = new TestServer();
}

}

The android code:

interface TestService {

public String getResponse(String data);
}

public class MainActivity extends Activity {

private String serverIP = "192.168.1.7";
EditText et= null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnGet = (Button) findViewById(R.id.button1);
    et= (EditText)findViewById(R.id.editText2);
    btnGet.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            new Conn().execute();
        }
    });

}
class Conn extends AsyncTask<Void, Void, MainActivity> {

    @Override
    protected MainActivity doInBackground(Void... params) {
        Looper.prepare();

        try {
            Toast.makeText(MainActivity.this, "Inside conn my nigga", Toast.LENGTH_SHORT).show();
            CallHandler callHandler = new CallHandler();
            Client client = new Client(serverIP, 7777, callHandler);
            TestService testService = (TestService) client.getGlobal(TestService.class);
            String msg = testService.getResponse("qwe");
            //Toast.makeText(MainActivity.this, testService.getResponse("abc"), Toast.LENGTH_SHORT).show();
            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Looper.loop();
        return null;
    }

}
}

I tried using the above code also using a simple Runnable thread instead of AsyncTask(I was paranoid AsyncTask'd be causing the problem) but it went in vain.

The server gives this output:

Server Listening
Client Connected: /192.168.1.5
Client Disconnected: /192.168.1.5

No matter how many times I click the Button1 of my android app.
Any help will be really appreciated. :)
Thank you for your time!


问:
How can I set headers on an outgoing THREE.TextureLoader request?
I want my TextureLoader to use header authorization to load textures:

```<code>let loader = new THREE.TextureLoader();
loader.headers = { . . . };                    // I want this!
let myTex = loader.load('my_authorized_url');
</code>```

I want to pass custom headers into the request sent over the wire. I see the Loader#setWithCredentials() function, but I can't tell how it's used (or if that's even what I should use). Should I consider writing my own Loader?

EDIT: It looks to me like there's nowhere in the ImageLoader source where a header could be set.

答:
I eventually settled on editing the prototype method on the Loader:

```<code>Object.assign(THREE.XHRLoader.prototype, {
    load: function(a, b, c, d) {
        void 0 !== this.path && (a = this.path + a);
        var e = this
        , f = THREE.Cache.get(a);
        if (void 0 !== f)
        return e.manager.itemStart(a),
        setTimeout(function() {
            b && b(f);
            e.manager.itemEnd(a)
        }, 0),
        f;
        var g = new XMLHttpRequest;
        g.overrideMimeType("text/plain");
        g.open("GET", a, !0);
        //
        // ..............
        // NOTE THIS LINE:
        //
        g.setRequestHeader('HEADER_KEY', 'HEADER_VALUE');
        g.addEventListener("load", function(c) {
            var f = c.target.response;
            THREE.Cache.add(a, f);
            200 === this.status ? (b && b(f),
            e.manager.itemEnd(a)) : 0 === this.status ? (console.warn("THREE.XHRLoader: HTTP Status 0 received."),
            b && b(f),
            e.manager.itemEnd(a)) : (d && d(c),
            e.manager.itemError(a))
        }, !1);
        void 0 !== c && g.addEventListener("progress", function(a) {
            c(a)
        }, !1);
        g.addEventListener("error", function(b) {
            d && d(b);
            e.manager.itemError(a)
        }, !1);
        void 0 !== this.responseType && (g.responseType = this.responseType);
        void 0 !== this.withCredentials && (g.withCredentials = this.withCredentials);
        g.send(null);
        e.manager.itemStart(a);
        return g
    },
    ...
});
</code>```

Body:
I want my TextureLoader to use header authorization to load textures:

let loader = new THREE.TextureLoader();
loader.headers = { . . . };                    // I want this!
let myTex = loader.load('my_authorized_url');

I want to pass custom headers into the request sent over the wire. I see the Loader#setWithCredentials() function, but I can't tell how it's used (or if that's even what I should use). Should I consider writing my own Loader?

EDIT: It looks to me like there's nowhere in the ImageLoader source where a header could be set.

Body:
I eventually settled on editing the prototype method on the Loader:

Object.assign(THREE.XHRLoader.prototype, {
    load: function(a, b, c, d) {
        void 0 !== this.path && (a = this.path + a);
        var e = this
        , f = THREE.Cache.get(a);
        if (void 0 !== f)
        return e.manager.itemStart(a),
        setTimeout(function() {
            b && b(f);
            e.manager.itemEnd(a)
        }, 0),
        f;
        var g = new XMLHttpRequest;
        g.overrideMimeType("text/plain");
        g.open("GET", a, !0);
        //
        // ..............
        // NOTE THIS LINE:
        //
        g.setRequestHeader('HEADER_KEY', 'HEADER_VALUE');
        g.addEventListener("load", function(c) {
            var f = c.target.response;
            THREE.Cache.add(a, f);
            200 === this.status ? (b && b(f),
            e.manager.itemEnd(a)) : 0 === this.status ? (console.warn("THREE.XHRLoader: HTTP Status 0 received."),
            b && b(f),
            e.manager.itemEnd(a)) : (d && d(c),
            e.manager.itemError(a))
        }, !1);
        void 0 !== c && g.addEventListener("progress", function(a) {
            c(a)
        }, !1);
        g.addEventListener("error", function(b) {
            d && d(b);
            e.manager.itemError(a)
        }, !1);
        void 0 !== this.responseType && (g.responseType = this.responseType);
        void 0 !== this.withCredentials && (g.withCredentials = this.withCredentials);
        g.send(null);
        e.manager.itemStart(a);
        return g
    },
    ...
});


问:
Delete file with all history from svn repository
Is there any way to delete file from svn repository including all its history? This issue emerges when I want to get rid of large binary file residing in repo.

I know only one approach that might help in this situation:

Dump all repo with the help of svnadmin utility.

Filter dumped file with grep. Grep should use filename and write in to the other dump-file

Import last dump-file with svnadmin

But this is too complicated and unreliable. Maybe there is another solution?

答:
I agree with McDowell's proposal, but would like to suggest that you consider replacing the large file with a text file that simply contains the hash of the file for the removed entry.

If you have a huge number of, for example, .o files from accidentally checking in a build directory, this may not be appropriate.  But if you are removing a bunch of binary artifacts you don't want from a directory that includes a bunch of binary artifacts you DO want, you are at high risk of making an expensive mistake.  At a minimum, consider removing them from trunk and most branches, but leaving a feature branch full of placeholder text files with the hash of the original binary.  This can at least be enough to figure out what happened later, verify that a stray copy that shouldn't have been deleted is in fact the right file, and put it back under revision control.

And, obviously, back the entire repo up to something read-only, like a couple of M-Discs or something, before you even think about doing any of this stuff.


问:
How can I revert multiple Git commits?
I have a Git repository that looks like this:

```<code>A <- B <- C <- D <- HEAD
</code>```

I want the head of the branch to point to A, i.e., I want B, C, D, and HEAD to disappear and I want head to be synonymous with A.

It sounds like I can either try to rebase (doesn't apply, since I've pushed changes in between), or revert. But how do I revert multiple commits? Do I revert one at a time? Is the order important?

答:
Clean way which I found useful

```<code>git revert --no-commit HEAD~3..
git commit -m "your message regarding reverting the multiple commits"
</code>```

This command reverts last 3 commits with only one commit.

Also doesn't rewrite history, so doesn't require a force push.

The .. helps create a range. Meaning HEAD~3.. is the same as HEAD~3..HEAD

Title: How can I revert multiple Git commits?

Body:
I have a Git repository that looks like this:

A <- B <- C <- D <- HEAD

I want the head of the branch to point to A, i.e., I want B, C, D, and HEAD to disappear and I want head to be synonymous with A.

It sounds like I can either try to rebase (doesn't apply, since I've pushed changes in between), or revert. But how do I revert multiple commits? Do I revert one at a time? Is the order important?

Body:
Clean way which I found useful

git revert --no-commit HEAD~3..
git commit -m "your message regarding reverting the multiple commits"

This command reverts last 3 commits with only one commit.

Also doesn't rewrite history, so doesn't require a force push.

The .. helps create a range. Meaning HEAD~3.. is the same as HEAD~3..HEAD


问:
php-zmq is not shown on phpinfo() page
I am using Wamp Server on Windows and I installed zmq library. When I write php --info on console, I see that zmq is shown as intalled.

zmq

ZMQ extension => enabled

ZMQ extension version => 1.1.2

libzmq version => 3.2.2

But when I create a php page with phpinfo() function to show php configuration, it does not show anything about zmq. Plus, it is unable to find ZMQContext and other ZMQ classes, like ZMQSocket. I guess it's not fully installed, but I don't know what to do anymore. I have already modified both php.ini files with required info.

C:\wamp\bin\php\php5.5.12\php.ini

[ZMQ]

extension=php_zmq.dll

C:\wamp\bin\apache\apache2.4.9\bin\php.ini

[ZMQ]

extension=php_zmq.dll

Does anyone have any idea about why?

答:
I know this is old thread; however, I had the same problem and it took me time to fix the problem. The fix is to add following line in httpd.conf file</p>

```<code>LoadFile "D:/xampp/php/libzmq.dll"
</code>```

Title: php-zmq is not shown on phpinfo() page

Body:
I know this is old thread; however, I had the same problem and it took me time to fix the problem. The fix is to add following line in httpd.conf file

LoadFile "D:/xampp/php/libzmq.dll"


问:
Creating Custom Tag in PyYAML
I'm trying to use Python's PyYAML to create a custom tag that will allow me to retrieve environment variables with my YAML.

```<code>import os
import yaml

class EnvTag(yaml.YAMLObject):
    yaml_tag = u'!Env'

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

    def __repr__(self):
       return os.environ.get(self.env_var)

settings_file = open('conf/defaults.yaml', 'r')
settings = yaml.load(settings_file)
</code>```

And inside of defaults.yaml is simply:

```<code>example: !ENV foo
</code>```

The error I keep getting:

```<code>yaml.constructor.ConstructorError:
could not determine a constructor for the tag '!ENV' in
"defaults.yaml", line 1, column 10
</code>```

I plan to have more than one custom tag as well (assuming I can get this one working)

答:
I'd like to share how I resolved this as an addendum to the great answers above provided by Anthon and Fredrick Brennan. Thank you for your help.

In my opinion, the PyYAML document isn't real clear as to when you might want to add a constructor via a class (or "metaclass magic" as described in the doc), which may involve re-defining from_yaml and to_yaml, or simply adding a constructor using yaml.add_constructor.

In fact, the doc states:

You may define your own application-specific tags. The easiest way to do it is to define a subclass of yaml.YAMLObject

I would argue the opposite is true for simpler use-cases. Here's how I managed to implement my custom tag.

config/__init__.py

```<code>import yaml
import os

environment = os.environ.get('PYTHON_ENV', 'development')

def __env_constructor(loader, node):
    value = loader.construct_scalar(node)
    return os.environ.get(value)

yaml.add_constructor(u'!ENV', __env_constructor)

# Load and Parse Config
__defaults      = open('config/defaults.yaml', 'r').read()
__env_config    = open('config/%s.yaml' % environment, 'r').read()
__yaml_contents = ''.join([__defaults, __env_config])
__parsed_yaml   = yaml.safe_load(__yaml_contents)

settings = __parsed_yaml[environment]
</code>```

With this, I can now have a seperate yaml for each environment using an env PTYHON_ENV (default.yaml, development.yaml, test.yaml, production.yaml). And each can now reference ENV variables.

Example default.yaml:

```<code>defaults: &default
  app:
    host: '0.0.0.0'
    port: 500
</code>```

Example production.yaml:

```<code>production:
  <<: *defaults
  app:
    host: !ENV APP_HOST
    port: !ENV APP_PORT
</code>```

To use:

```<code>from config import settings
"""
If PYTHON_ENV == 'production', prints value of APP_PORT
If PYTHON_ENV != 'production', prints default 5000
"""
print(settings['app']['port'])
</code>```

Title: Creating Custom Tag in PyYAML

Body:
I'm trying to use Python's PyYAML to create a custom tag that will allow me to retrieve environment variables with my YAML.

import os
import yaml

class EnvTag(yaml.YAMLObject):
    yaml_tag = u'!Env'

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

    def __repr__(self):
       return os.environ.get(self.env_var)

settings_file = open('conf/defaults.yaml', 'r')
settings = yaml.load(settings_file)

And inside of defaults.yaml is simply:

example: !ENV foo

The error I keep getting:

yaml.constructor.ConstructorError:
could not determine a constructor for the tag '!ENV' in
"defaults.yaml", line 1, column 10

I plan to have more than one custom tag as well (assuming I can get this one working)

Body:
I'd like to share how I resolved this as an addendum to the great answers above provided by Anthon and Fredrick Brennan. Thank you for your help.

In my opinion, the PyYAML document isn't real clear as to when you might want to add a constructor via a class (or "metaclass magic" as described in the doc), which may involve re-defining from_yaml and to_yaml, or simply adding a constructor using yaml.add_constructor.

In fact, the doc states:

You may define your own application-specific tags. The easiest way to do it is to define a subclass of yaml.YAMLObject

I would argue the opposite is true for simpler use-cases. Here's how I managed to implement my custom tag.

config/__init__.py

import yaml
import os

environment = os.environ.get('PYTHON_ENV', 'development')

def __env_constructor(loader, node):
    value = loader.construct_scalar(node)
    return os.environ.get(value)

yaml.add_constructor(u'!ENV', __env_constructor)

# Load and Parse Config
__defaults      = open('config/defaults.yaml', 'r').read()
__env_config    = open('config/%s.yaml' % environment, 'r').read()
__yaml_contents = ''.join([__defaults, __env_config])
__parsed_yaml   = yaml.safe_load(__yaml_contents)

settings = __parsed_yaml[environment]

With this, I can now have a seperate yaml for each environment using an env PTYHON_ENV (default.yaml, development.yaml, test.yaml, production.yaml). And each can now reference ENV variables.

Example default.yaml:

defaults: &default
  app:
    host: '0.0.0.0'
    port: 500

Example production.yaml:

production:
  <<: *defaults
  app:
    host: !ENV APP_HOST
    port: !ENV APP_PORT

To use:

from config import settings
"""
If PYTHON_ENV == 'production', prints value of APP_PORT
If PYTHON_ENV != 'production', prints default 5000
"""
print(settings['app']['port'])


问:
Is it possible to display as "block" if content "line breaks" but display "inline" otherwise?
I have  code that looks a little bit like this:

```<code><div class="some-class">
    <span>NameOfThing</span>
    <div class="block-or-inline">
        <span style="white-space: nowrap">ValueOfThing1</span>
        <span style="white-space: nowrap">ValueOfThing2</span>
    </div>
</div>
</code>```

If the content inside div.block-or-inline is shorter than the width of its container (no line break) I would like all the content to render on a single line. But if the content is wider - causing a line break - I would like BOTH spans inside to break to the new line.

Is this possible?

答:
If you want render the content in a single line you can put the css attribute overflow:hidden; to the div.block-or-inline and an specific width, and if the content is wider to the div, the rest of it will disappear.
It's a way to show the content avoiding the line-break.</p>

Body:
I have  code that looks a little bit like this:

    NameOfThing

        ValueOfThing1
        ValueOfThing2

If the content inside div.block-or-inline is shorter than the width of its container (no line break) I would like all the content to render on a single line. But if the content is wider - causing a line break - I would like BOTH spans inside to break to the new line.

Is this possible?


问:
JQuery get checkbox id
I'm trying to get an id of a checkbox.
There are several checkboxes on a page that have ids like: channel_left_restream_ids_42, channel_left_restream_ids_44, etc. I need to handle an event when one of those checked and get an id of the checked.

So for checkbox with code <input type="checkbox" value="42" checked="checked" name="channel[left_restream_ids][]" id="channel_left_restream_ids_42"> and coffescript like this:

```<code>$("input[id*=channel_left_restream_ids]").change (e) =>
  alert($(this).attr("id"))
</code>```

I can't get it work. It says undefined. I've tried a lot of alternatives, none worked. Where am I doing a mistake?

JSFiddle is here

答:
I hope I am understanding your question right, but I hope this might push you in the right direction:

To know if that this specific checkbox is checked or not, you have to use its exact id.

So, in your script you are looking for this id:
      id*=channel_left_restream_ids

but the id of the checkbox is "channel_left_restream_ids_42"

I don't know the code you are working with, but it is possible that there are many "channel_left_restream_ids", or maybe that id is used on something else that is not a checkbox.

So this would be worth a try:
    [id*=channel_left_restream_ids_42]

Title: JQuery get checkbox id

Body:
I'm trying to get an id of a checkbox.
There are several checkboxes on a page that have ids like: channel_left_restream_ids_42, channel_left_restream_ids_44, etc. I need to handle an event when one of those checked and get an id of the checked.

So for checkbox with code <input type="checkbox" value="42" checked="checked" name="channel[left_restream_ids][]" id="channel_left_restream_ids_42"> and coffescript like this:

$("input[id*=channel_left_restream_ids]").change (e) =>
  alert($(this).attr("id"))

I can't get it work. It says undefined. I've tried a lot of alternatives, none worked. Where am I doing a mistake?

JSFiddle is here