问:
PySide/PyQt4: adding a checkbox to QTableWidget Horizontal (column) Header
I am trying to put a checkbox in the horizontal (column) header of my tablewidget. Based on the other post here (because the base object type is the same), I have tried this:

```<code>item = QtGui.QTableWidgetItem()
item.setCheckState(QtCore.Qt.Checked)
self.tableWidget.setHorizontalHeaderItem(1, item)
</code>```

and I have also tried this:

```<code>self.tableWidget.horizontalHeaderItem(1).setCheckState(QtCore.Qt.Checked)
</code>```

Neither of these produce a checkbox in the horizontal header. Suggestions are appreciated.

答:
Adapted from the qt-blog http://blog.qt.io/blog/2014/04/11/qt-weekly-5-widgets-on-a-qheaderview/

This can also be used to place arbitrary widgets into the header

```<code># coding=utf-8
from PySide.QtCore import Qt
from PySide.QtGui import QHeaderView, QCheckBox
from qtpy import QtCore

class CustomHeaderView(QHeaderView):
    def __init__(self, parent=None):
        QHeaderView.__init__(self, Qt.Horizontal, parent)
        self.setMovable(True)
        self.boxes = []

        self.sectionResized.connect(self.handleSectionResized)
        self.sectionMoved.connect(self.handleSectionMoved)

    def scrollContentsBy(self, dx, dy):
        super().scrollContentsBy(dx, dy)
        if dx != 0:
            self.fixComboPositions()

    def fixComboPositions(self):
        for i in range(self.count() + 1):
            self.boxes[i].setGeometry(self.sectionViewportPosition(i), 0,
                                      self.sectionSize(i) - 5, self.height())

    @QtCore.Slot()
    def showEvent(self, e):
        for i in range(self.count() + 1):
            if len(self.boxes) <= i:
                self.boxes.append(QCheckBox(self))
            self.boxes[i].setGeometry(self.sectionViewportPosition(i), 0,
                                      self.sectionSize(i) - 5, self.height())
            self.boxes[i].show()

        super().showEvent(e)

    @QtCore.Slot()
    def handleSectionMoved(self, logical, oldVisualIndex, newVisualIndex):
        for i in range(min(oldVisualIndex, newVisualIndex),self.count()):
            logical = self.logicalIndex(i)
            self.boxes[logical].setGeometry(self.sectionViewportPosition(logical), 0,
                                            self.sectionSize(logical) - 5, self.height())

    @QtCore.Slot()
    def handleSectionResized(self, i):
        for j in range(self.visualIndex(i),self.count()):
            logical = self.logicalIndex(j)
            self.boxes[logical].setGeometry(self.sectionViewportPosition(logical), 0,
                                            self.sectionSize(logical) - 5, self.height())
            self.boxes[logical].updateGeometry()
</code>```

Body:
I am trying to put a checkbox in the horizontal (column) header of my tablewidget. Based on the other post here (because the base object type is the same), I have tried this:

item = QtGui.QTableWidgetItem()
item.setCheckState(QtCore.Qt.Checked)
self.tableWidget.setHorizontalHeaderItem(1, item)

and I have also tried this:

self.tableWidget.horizontalHeaderItem(1).setCheckState(QtCore.Qt.Checked)

Neither of these produce a checkbox in the horizontal header. Suggestions are appreciated.

Body:
Adapted from the qt-blog http://blog.qt.io/blog/2014/04/11/qt-weekly-5-widgets-on-a-qheaderview/

This can also be used to place arbitrary widgets into the header

# coding=utf-8
from PySide.QtCore import Qt
from PySide.QtGui import QHeaderView, QCheckBox
from qtpy import QtCore

class CustomHeaderView(QHeaderView):
    def __init__(self, parent=None):
        QHeaderView.__init__(self, Qt.Horizontal, parent)
        self.setMovable(True)
        self.boxes = []

        self.sectionResized.connect(self.handleSectionResized)
        self.sectionMoved.connect(self.handleSectionMoved)

    def scrollContentsBy(self, dx, dy):
        super().scrollContentsBy(dx, dy)
        if dx != 0:
            self.fixComboPositions()

    def fixComboPositions(self):
        for i in range(self.count() + 1):
            self.boxes[i].setGeometry(self.sectionViewportPosition(i), 0,
                                      self.sectionSize(i) - 5, self.height())

    @QtCore.Slot()
    def showEvent(self, e):
        for i in range(self.count() + 1):
            if len(self.boxes) <= i:
                self.boxes.append(QCheckBox(self))
            self.boxes[i].setGeometry(self.sectionViewportPosition(i), 0,
                                      self.sectionSize(i) - 5, self.height())
            self.boxes[i].show()

        super().showEvent(e)

    @QtCore.Slot()
    def handleSectionMoved(self, logical, oldVisualIndex, newVisualIndex):
        for i in range(min(oldVisualIndex, newVisualIndex),self.count()):
            logical = self.logicalIndex(i)
            self.boxes[logical].setGeometry(self.sectionViewportPosition(logical), 0,
                                            self.sectionSize(logical) - 5, self.height())

    @QtCore.Slot()
    def handleSectionResized(self, i):
        for j in range(self.visualIndex(i),self.count()):
            logical = self.logicalIndex(j)
            self.boxes[logical].setGeometry(self.sectionViewportPosition(logical), 0,
                                            self.sectionSize(logical) - 5, self.height())
            self.boxes[logical].updateGeometry()


来源: stackexchange

问:
NameError: name '' is not defined
I want to have a view in which I could add new contacts in the model "contacts" that I created.
Here are some lines of code that are concerned

views.py:

```<code>def contact(request):
form = ContactForm(request.POST or None)
if form.is_valid():
    sujet = form.cleaned_data['sujet']
    message = form.cleaned_data['message']
    envoyeur = form.cleaned_data['envoyeur']
    renvoi = form.cleaned_data['renvoi']
    envoi = True
return render(request, 'blog/contact.html', locals())

def nouveau_contact(request):
sauvegarde = False
form = NouveauContactForm(request.POST or None, request.FILES)
if form.is_valid():
    contact = Contact()
    contact.nom = form.cleaned_data["nom"]
    contact.adresse = form.cleaned_data["adresse"]
    contact.photo = form.cleaned_data["photo"]
    contact.save()
    sauvegarde = True
return render(request, 'blog/newcontact.html', {
    'form': form,
    'sauvegarde': sauvegarde
})
</code>```

forms.py:

```<code>class ContactForm(forms.Form):
   sujet = forms.CharField(max_length=100)
   message = forms.CharField(widget=forms.Textarea)
   envoyeur = forms.EmailField(label="Votre adresse mail")

class NouveauContactForm(forms.Form):
   nom = forms.CharField()
   adresse = forms.CharField(widget=forms.Textarea)
   photo = forms.ImageField()

class Contact(models.Model):
   nom = models.CharField(max_length=255)
   adresse = models.TextField()
   photo = models.ImageField(upload_to="photos/")

   def __str__(self):
      return self.nom
</code>```

The error message tells me that "" NewContactForm "" is not defined
this is the ERROR_MESSAGE

答:
Add in the views at the top,

```<code>from .forms import NouveauContactForm
</code>```

You forgot to import the form.

ContentLicense: CC BY-SA 3.0

Title: NameError: name '' is not defined

Body:
I want to have a view in which I could add new contacts in the model "contacts" that I created.
Here are some lines of code that are concerned

views.py:

def contact(request):
form = ContactForm(request.POST or None)
if form.is_valid():
    sujet = form.cleaned_data['sujet']
    message = form.cleaned_data['message']
    envoyeur = form.cleaned_data['envoyeur']
    renvoi = form.cleaned_data['renvoi']
    envoi = True
return render(request, 'blog/contact.html', locals())

def nouveau_contact(request):
sauvegarde = False
form = NouveauContactForm(request.POST or None, request.FILES)
if form.is_valid():
    contact = Contact()
    contact.nom = form.cleaned_data["nom"]
    contact.adresse = form.cleaned_data["adresse"]
    contact.photo = form.cleaned_data["photo"]
    contact.save()
    sauvegarde = True
return render(request, 'blog/newcontact.html', {
    'form': form,
    'sauvegarde': sauvegarde
})

forms.py:

class ContactForm(forms.Form):
   sujet = forms.CharField(max_length=100)
   message = forms.CharField(widget=forms.Textarea)
   envoyeur = forms.EmailField(label="Votre adresse mail")

class NouveauContactForm(forms.Form):
   nom = forms.CharField()
   adresse = forms.CharField(widget=forms.Textarea)
   photo = forms.ImageField()

class Contact(models.Model):
   nom = models.CharField(max_length=255)
   adresse = models.TextField()
   photo = models.ImageField(upload_to="photos/")

   def __str__(self):
      return self.nom

The error message tells me that "" NewContactForm "" is not defined
this is the ERROR_MESSAGE

Body:
Add in the views at the top,

from .forms import NouveauContactForm

You forgot to import the form.


问:
Is there a faster way to import data from a file to MySQL using php?
Okay, so I get around 100k-1M lines of text that I always import to a database. The code that i use is as follows:

```<code>$lines = new SplFileObject('/home/file.txt');
while(!$lines->eof()) {
    $lines->next();       //Skipping first line
    $row = explode(',',$lines);
    for($i = 0; $i<4; $i++){
        if(!isset($row[$i])){
            $row[$i] = null;
        }
    }
    $y = (float) $row[1];
    $z = (float) $row[2];
    $load_query = "INSERT IGNORE INTO new (datetime_gmt,field2,field3)
    VALUES ('".$row[0]."','".$y."','".$z."');";

    if(!$mysqli->query($load_query)){
      die("CANNOT EXECUTE".$mysqli->error."\n");
    }
}
$lines = null;
</code>```

However, it takes waaayyy too long. Is there any faster way to do it, or am I stuck with this method?

PS. I don't want to use MySQL's "INSERT DATA INFILE".

答:
As written, you're running an insert statement for every line. It'll be much faster if you compile a single multi-insert statement in the format of INSERT INTO table (foo, bar) VALUES (1, 2), (3, 4), (5, 6); that is executed once at the end. Something along the lines of this, though it could be cleaned up more.

```<code>$lines = new SplFileObject('/home/file.txt');
$load_query = "INSERT IGNORE INTO new (datetime_gmt,field2,field3)
    VALUES ";
while(!$lines->eof()) {
    $lines->next();       //Skipping first line
    $row = explode(',',$lines);
    for($i = 0; $i<4; $i++){
        if(!isset($row[$i])){
            $row[$i] = null;
        }
    }
    $y = (float) $row[1];
    $z = (float) $row[2];
    $load_query .= "('".$row[0]."','".$y."','".$z."'),";
}

if(!$mysqli->query(rtrim($load_query, ','))) {
    die("CANNOT EXECUTE".$mysqli->error."\n");
}
$lines = null;
</code>```

Also keep make sure the data is trusted. If the file can come from an outside user, appending directly to the query string creates an SQL injection vector.

Body:
Okay, so I get around 100k-1M lines of text that I always import to a database. The code that i use is as follows:

$lines = new SplFileObject('/home/file.txt');
while(!$lines->eof()) {
    $lines->next();       //Skipping first line
    $row = explode(',',$lines);
    for($i = 0; $i<4; $i++){
        if(!isset($row[$i])){
            $row[$i] = null;
        }
    }
    $y = (float) $row[1];
    $z = (float) $row[2];
    $load_query = "INSERT IGNORE INTO new (datetime_gmt,field2,field3)
    VALUES ('".$row[0]."','".$y."','".$z."');";

    if(!$mysqli->query($load_query)){
      die("CANNOT EXECUTE".$mysqli->error."\n");
    }
}
$lines = null;

However, it takes waaayyy too long. Is there any faster way to do it, or am I stuck with this method?

PS. I don't want to use MySQL's "INSERT DATA INFILE".

Body:
As written, you're running an insert statement for every line. It'll be much faster if you compile a single multi-insert statement in the format of INSERT INTO table (foo, bar) VALUES (1, 2), (3, 4), (5, 6); that is executed once at the end. Something along the lines of this, though it could be cleaned up more.

$lines = new SplFileObject('/home/file.txt');
$load_query = "INSERT IGNORE INTO new (datetime_gmt,field2,field3)
    VALUES ";
while(!$lines->eof()) {
    $lines->next();       //Skipping first line
    $row = explode(',',$lines);
    for($i = 0; $i<4; $i++){
        if(!isset($row[$i])){
            $row[$i] = null;
        }
    }
    $y = (float) $row[1];
    $z = (float) $row[2];
    $load_query .= "('".$row[0]."','".$y."','".$z."'),";
}

if(!$mysqli->query(rtrim($load_query, ','))) {
    die("CANNOT EXECUTE".$mysqli->error."\n");
}
$lines = null;

Also keep make sure the data is trusted. If the file can come from an outside user, appending directly to the query string creates an SQL injection vector.


问:
How to unit test enum composed via @JsonCreator?
I am using Jackson to deserialize a JSON string into an enum.

```<code>public enum RoomType {

    SHARED("shared"),
    PRIVATE("private");

    private String value;

    RoomType(String value) {
        this.value = value;
    }

    @JsonCreator
    public static RoomType fromJson(final String jsonValue) {
        for (RoomType type : values()) {
            if (type.value.equals(jsonValue)) {
                return type;
            }
        }
        return null;
    }

    @JsonValue
    @Override
    public String toString() {
        return value;
    }

}
</code>```

I want to unit test the different edge cases:

```<code>@RunWith(JUnit4.class)
public class RoomTypeTest {

    private final ObjectMapper mapper = new ObjectMapper();

    @Test
    public void fromJsonWithShared() throws Exception {
        String json = "{\"roomType\":\"shared\"}";
        RoomType type = mapper.readValue(json, RoomType.class);
        assertThat(type).isEqualTo(RoomType.SHARED);
    }

}
</code>```

The test fails. When I debug I see that jsonValue is null when RoomType.fromJson is invoked. Seems like that Jackson does not pick up the value from the JSON string.

Related examples

EnumCreatorTest929.java

答:
I think Jackson doesn't know what value to pass to that fromJson method. Try adding @JsonProperty:

```<code>@JsonCreator
public static RoomType fromJson(@JsonProperty("roomType") final String jsonValue) {
     ....
}
</code>```

Body:
I am using Jackson to deserialize a JSON string into an enum.

public enum RoomType {

    SHARED("shared"),
    PRIVATE("private");

    private String value;

    RoomType(String value) {
        this.value = value;
    }

    @JsonCreator
    public static RoomType fromJson(final String jsonValue) {
        for (RoomType type : values()) {
            if (type.value.equals(jsonValue)) {
                return type;
            }
        }
        return null;
    }

    @JsonValue
    @Override
    public String toString() {
        return value;
    }

}

I want to unit test the different edge cases:

@RunWith(JUnit4.class)
public class RoomTypeTest {

    private final ObjectMapper mapper = new ObjectMapper();

    @Test
    public void fromJsonWithShared() throws Exception {
        String json = "{\"roomType\":\"shared\"}";
        RoomType type = mapper.readValue(json, RoomType.class);
        assertThat(type).isEqualTo(RoomType.SHARED);
    }

}

The test fails. When I debug I see that jsonValue is null when RoomType.fromJson is invoked. Seems like that Jackson does not pick up the value from the JSON string.

Related examples

EnumCreatorTest929.java

Body:
I think Jackson doesn't know what value to pass to that fromJson method. Try adding @JsonProperty:

@JsonCreator
public static RoomType fromJson(@JsonProperty("roomType") final String jsonValue) {
     ....
}


问:
How do I protect phone number from bots
I want a phone number which display on public page will be protected. Example converts phone number characters to HTML entities and bots can't grab the number in plain text. Let me know the trick.</p>

答: Sure just print the phone number using words instead of numbers...</p>

ContentLicense: CC BY-SA 2.5

Title: How do I protect phone number from bots


问:
Bound and Unbound methode Error Python
Hello Guys i try hard to fix this problem please can some one help me really i need it

when i try to print a return value from function doesn't work i get this error

```<code><unbound method Ui_MainWindow.fn_get_cell_Value>
</code>```

here is my code

```<code>def handleHeade`rMenu(self,pos):
    menu = QMenu()
    quitAction = menu.addAction("Update")
    action = menu.exec_(self.tableView.mapToGlobal(pos))
    if action == quitAction:
       dd = Ui_MainWindow
       print dd.fn_get_cell_Value

def fn_get_cell_Value(self,qmodelindex):
    i = qmodelindex.row()
    j = qmodelindex.column()
    valeur = qmodelindex.sibling(i, j).data(QtCore.Qt.DisplayRole).toString()
    return valeur
</code>```

i want to print the return value when i click update from Qmenu

thank you so much

答:
<unbound method Ui_MainWindow.fn_get_cell_Value> is not an error message.  It is the expected output from this print statement

```<code>   print dd.fn_get_cell_Value
</code>```

You need to call the method with (), but I cannot tell what arguments might be needed for the call.  Consider the following.

```<code>>>> class C:
    def meth(self): return 55

>>> print C.meth
<unbound method C.meth>
>>> print C().meth
<bound method C.meth of <__main__.C instance at 0x0000000003FAD448>>
>>> print C().meth()
55
</code>```

Title: Bound and Unbound methode Error Python

Body:
Hello Guys i try hard to fix this problem please can some one help me really i need it

when i try to print a return value from function doesn't work i get this error

<unbound method Ui_MainWindow.fn_get_cell_Value>

here is my code

def handleHeade`rMenu(self,pos):
    menu = QMenu()
    quitAction = menu.addAction("Update")
    action = menu.exec_(self.tableView.mapToGlobal(pos))
    if action == quitAction:
       dd = Ui_MainWindow
       print dd.fn_get_cell_Value

def fn_get_cell_Value(self,qmodelindex):
    i = qmodelindex.row()
    j = qmodelindex.column()
    valeur = qmodelindex.sibling(i, j).data(QtCore.Qt.DisplayRole).toString()
    return valeur

i want to print the return value when i click update from Qmenu

thank you so much

Body:
<unbound method Ui_MainWindow.fn_get_cell_Value> is not an error message.  It is the expected output from this print statement

   print dd.fn_get_cell_Value

You need to call the method with (), but I cannot tell what arguments might be needed for the call.  Consider the following.

>>> class C:
    def meth(self): return 55

>>> print C.meth
<unbound method C.meth>
>>> print C().meth
<bound method C.meth of <__main__.C instance at 0x0000000003FAD448>>
>>> print C().meth()
55


问:
Div not inline when window gets smaller?
I'm having a small issue with a couple divs. I have it set up with 5 divs all different colors, when the window size is shrunk the divs drop down under each other one by one. Is there a way I can make the space between them shrinks with it so they but up closer?

Thanks again guys

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg01" class="bg01Off">
    </div>
    <div id="bg02" class="bg02Off">
    </div>
    <div id="bg03" class="bg03Off">
    </div>
    <div id="bg04" class="bg04Off">
    </div>
    <div id="bg05" class="bg05Off">
    </div>
  </div></code>```

答:
You could put a rule in a media query that reduces the margins like in my example (last rule):

  p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}

@media screen and (max-width: 760px) {
  .bg01Off,
  .bg02Off,
  .bg03Off,
  .bg04Off,
  .bg05Off {
    margin-left: 1%;
    margin-right: 1%;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg01" class="bg01Off">
    </div>
    <div id="bg02" class="bg02Off">
    </div>
    <div id="bg03" class="bg03Off">
    </div>
    <div id="bg04" class="bg04Off">
    </div>
    <div id="bg05" class="bg05Off">
    </div>
  </div></code>```

Body:
I'm having a small issue with a couple divs. I have it set up with 5 divs all different colors, when the window size is shrunk the divs drop down under each other one by one. Is there a way I can make the space between them shrinks with it so they but up closer?

Thanks again guys

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}

Colour

Body:
You could put a rule in a media query that reduces the margins like in my example (last rule):

  p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}

@media screen and (max-width: 760px) {
  .bg01Off,
  .bg02Off,
  .bg03Off,
  .bg04Off,
  .bg05Off {
    margin-left: 1%;
    margin-right: 1%;
  }

<div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg01" class="bg01Off">
    </div>
    <div id="bg02" class="bg02Off">
    </div>
    <div id="bg03" class="bg03Off">
    </div>
    <div id="bg04" class="bg04Off">
    </div>
    <div id="bg05" class="bg05Off">
    </div>
  </div>


问:
SQL minimum date value after today's date Now()
I am writing a query and am having trouble filtering data as I would like.  In the table, there is a date field and an ItemCode field. I would like to return one record per ItemCode with the earliest date that is after today.

If today is 6/6/2017 and my data looks like:

```<code>ItemCode     Date
1            6/1/2017
1            6/7/2017
1            6/10/2017
2            6/2/2017
2            6/8/2017
2            6/15/2017
</code>```

I would want the result to be

```<code>ItemCode     Date
1            6/7/2017
2            6/8/2017
</code>```

My query so far is:

```<code>SELECT PO_PurchaseOrderDetail.ItemCode, Min(PO_PurchaseOrderDetail.RequiredDate) AS NextPO
FROM PO_PurchaseOrderDetail
GROUP BY PO_PurchaseOrderDetail.ItemCode
HAVING (((Min(PO_PurchaseOrderDetail.RequiredDate))>=Now()));
</code>```

The problem is that the Min function fires first and grabs the earliest dates per ItemCode, which are before today.  Then the >=Now() is evaluated and because the min dates are before today, the query returns nothing.

I've tried putting the >=Now() inside the min function in the HAVING part of the query but it does not change the result.

My structure is wrong and I would appreciate any advice. Thanks!

答:
I would approach like this for standard SQL, Access approach may vary</p>

```<code>select PO_PurchaseOrderDetail.ItemCode,
       min(PO_PurchaseOrderDetail.RequiredDate) as NextPO

from PO_PurchaseOrderDetail
where PO_PurchaseOrderDetail.RequiredDate >= Now()
group by PO_PurchaseOrderDetail.ItemCode;
</code>```

Body:
I am writing a query and am having trouble filtering data as I would like.  In the table, there is a date field and an ItemCode field. I would like to return one record per ItemCode with the earliest date that is after today.

If today is 6/6/2017 and my data looks like:

ItemCode     Date
1            6/1/2017
1            6/7/2017
1            6/10/2017
2            6/2/2017
2            6/8/2017
2            6/15/2017

I would want the result to be

ItemCode     Date
1            6/7/2017
2            6/8/2017

My query so far is:

SELECT PO_PurchaseOrderDetail.ItemCode, Min(PO_PurchaseOrderDetail.RequiredDate) AS NextPO
FROM PO_PurchaseOrderDetail
GROUP BY PO_PurchaseOrderDetail.ItemCode
HAVING (((Min(PO_PurchaseOrderDetail.RequiredDate))>=Now()));

The problem is that the Min function fires first and grabs the earliest dates per ItemCode, which are before today.  Then the >=Now() is evaluated and because the min dates are before today, the query returns nothing.

I've tried putting the >=Now() inside the min function in the HAVING part of the query but it does not change the result.

My structure is wrong and I would appreciate any advice. Thanks!

Body:
I would approach like this for standard SQL, Access approach may vary

select PO_PurchaseOrderDetail.ItemCode,
       min(PO_PurchaseOrderDetail.RequiredDate) as NextPO

from PO_PurchaseOrderDetail
where PO_PurchaseOrderDetail.RequiredDate >= Now()
group by PO_PurchaseOrderDetail.ItemCode;


问:
EndPointReference method
I am strugglying with a problem that is to access the reference of the end point of a pipe curve to then create a dimension in the model, by the method doc.Create.Dimension().I already tried to use the Curve.EndPointReference(int index) method but it returns only null value. Can anyone help how to access this information ?</p>

答:
I think you should try something like

```<code>yourPipe.Location.Curve.GetEndPoint(1)
</code>```

This will give you the XYZ object of the end point of your curve.

Regards,
Arnaud.

Title: EndPointReference method

Body:
I think you should try something like

yourPipe.Location.Curve.GetEndPoint(1)

This will give you the XYZ object of the end point of your curve.

Regards,
Arnaud.


问:
How can I easily get access to form data in Express js?
I have a POST request with very simple and small amount of form data. How can I most easily access it?

Many tutorials/posts etc talk about bodyParser, but this is no longer bundled with Express. Other places (blogs etc) recommend using urlencoded directly, but now this is not available either.

Trying to find accurate information on these frameworks or technologies is doing my head in.

Can someone please tell me the recommended (up to date) way to get POSTed form data in Express?

答:
From the README of body-parser:

This does not handle multipart bodies, due to their complex and
  typically large nature.

The above is going to work with x-www-form-urlencoded and json but it will NOT work with any multipart. form-data is also multipart with the header multipart/form-data.

In case of form-data, your best solution would be to use express-formidable.

ContentLicense: CC BY-SA 4.0


问:
Angular Pipe: Cannot replace /n
I have been trying to make a pipe to replace certain characters in a message, this is the code for the pipe:

```<code>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
  transform(value: string): string {
    console.log(value);
    let newValue = value.replace(/\n/g, '<br>');
    console.log(newValue);
    return `${newValue}`;
  }
}
</code>```

I am using it on the page like this:

```<code>  <ion-card-content [innerHtml]="message | linky | replace"></ion-card-content>
</code>```

The Issue: It works when the replace statement is something is like this:

```<code>let newValue = value.replace('bit', '<br>');
</code>```

But is doesn't do anything when it looks like this:(I need to get it working for this)

```<code>let newValue = value.replace(/\n/g, '<br>');
</code>```

I can't seem to figure out where am I going wrong.

答:
When you say it doesn't work does that mean that the console.log(newValue) outputs as "something \n something" and not "something
 something"? Is there an error message of any sort?

I just took your exact code and tested it here and it worked.

```<code>var value = "asd \n more stuff";
console.log(value)
let newValue = value.replace(/\n/g, '<br>');
console.log(newValue)
</code>```

Title: Angular Pipe: Cannot replace /n

Body:
I have been trying to make a pipe to replace certain characters in a message, this is the code for the pipe:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
  transform(value: string): string {
    console.log(value);
    let newValue = value.replace(/\n/g, '
');
    console.log(newValue);
    return `${newValue}`;
  }
}

I am using it on the page like this:

  <ion-card-content [innerHtml]="message | linky | replace"></ion-card-content>

The Issue: It works when the replace statement is something is like this:

let newValue = value.replace('bit', '
');

But is doesn't do anything when it looks like this:(I need to get it working for this)

let newValue = value.replace(/\n/g, '
');

I can't seem to figure out where am I going wrong.

Body:
When you say it doesn't work does that mean that the console.log(newValue) outputs as "something \n something" and not "something
 something"? Is there an error message of any sort?

I just took your exact code and tested it here and it worked.

var value = "asd \n more stuff";
console.log(value)
let newValue = value.replace(/\n/g, '<br>');
console.log(newValue)


问:
when I use use pipe when the command is stored in a string, the pipe will be recognized as '|', why?
I excute bash shell like this

```<code>cmd="cat tmp1.list tmp2.list | sort > tmp3.list"
$cmd
</code>```

the result is

```<code>sdas
qqq
cat: |: No such file or directory
cat: sort: No such file or directory
cat: >: No such file or directory
cat: tmp3.list: No such file or directory
enter code here
</code>```

I konw 'eval' can work
but I want to know why it can't

答:
See BashFAQ #50 discussing alternatives to storing code inside strings. In terms of why this is a problem -- to summarize from The Bash Parser, the parsing steps are:

Read data to execute.

Process quotes.

Split the read data into commands. This is where ;, &, etc. are given semantic meaning.

Parse special operators. This is where |, >, etc. are given special meaning.

Perform expansions. This is where $cmd is replaced with the variable's value.

Split the command into a command name and arguments. This is where the value is split into words.

Execute the command.

In summary, | and > are processed in steps 3 and 4, whereas the value of $cmd is only substituted in step 5 (and prepared in step 6).

Body:
I excute bash shell like this

cmd="cat tmp1.list tmp2.list | sort > tmp3.list"
$cmd

the result is

sdas
qqq
cat: |: No such file or directory
cat: sort: No such file or directory
cat: >: No such file or directory
cat: tmp3.list: No such file or directory
enter code here

I konw 'eval' can work
but I want to know why it can't


问:
How to convert "923007501" to a hh:mm:ss format?
I'm currently trying to convert a subtitle-file from one format to another, but I'm struggling at bit with the timecode-fomat used in the original subtitle-file. For example, "923007501" is supposed to be roughly 00:01:30 (hh:mm:ss) but I don't really know how to convert that number to a hh:mm:ss format.

For some subtitle-files I can simply use something like TimeSpan ts = TimeSpan.FromMilliseconds(timecode);, but that doesn't seem work for the previous example.

答:
Try this one:</p>

```<code>        DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(923007501).ToLocalTime();
        String.Format("{0:HH:mm:ss}", dt); // here is your formatted datetime
</code>```

Body:
Try this one:

        DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(923007501).ToLocalTime();
        String.Format("{0:HH:mm:ss}", dt); // here is your formatted datetime


问:
Easy way to store and retrieve objects in Java without using a relational DB?
Do you know of an "easy" way to store and retrieve objects in Java without using a relational DB / ORM like Hibernate?

[Note that I am not considering serialization as-is for this purpose, as it won't allow to retrieve arbitrary objects in the middle of an object graph. Neither am I considering DB4O because of its restrictive license. Thanks.]

"Easy" meaning: not having to handle low-level details such as key/value pairs to rebuild an object graph (as with BerkeleyDB or traditional caches). The same applies for rebuilding objects from a document- or column-oriented DB (CouchDB, HBase, ..., even Lucene).

Perhaps there are interesting projects out there that provide a layer of integration between the mentioned storage systems and the object model (like ORM would be for RDBMSs) that I am not aware of.

Anyone successfully using those in production, or experimenting with persistence strategies other than relational DBs? How about RDF stores?

Update: I came across a very interesting article: A list of distributed key-value stores

答:
I still think you should consider paying for db4o.

If you want something else, add "with an MIT-style license" to the title.

OwnerDisplayName: orip


问:
How does this reinterpret_cast work? (Porting C++ to Java)
I have some C++ code I'm trying to port to Java, that looks like this:

```<code>struct foostruct {
    unsigned char aa : 3;
    bool ab : 1;
    unsigned char ba : 3;
    bool bb : 1;
};

static void foo(const unsigned char* buffer, int length)
{

    const unsigned char *end = buffer + length;

    while (buffer < end)
    {
        const foostruct bar = *(reinterpret_cast<const foostruct*>(buffer++));
        //read some values from struct and act accordingly
    }

}
</code>```

What is the reinterpret_cast doing?

答:
its basically saying the 8 bits represented at the current pointer should be interpreted as a "foostruct".

In my opinion it would be better written as follows:

```<code>const unsigned char aa = *buffer & 0x07;
const bool ab          = (*buffer & 0x08) != 0;
const unsigned char ba = (*buffer & 0x70) >> 4;
const bool bb          = (*buffer & 0x80) != 0;
</code>```

I think it is far more obvious what is being done then.  I think you may well find it easier to port to Java this way too ...

Body:
I have some C++ code I'm trying to port to Java, that looks like this:

struct foostruct {
    unsigned char aa : 3;
    bool ab : 1;
    unsigned char ba : 3;
    bool bb : 1;
};

static void foo(const unsigned char* buffer, int length)
{

    const unsigned char *end = buffer + length;

    while (buffer < end)
    {
        const foostruct bar = *(reinterpret_cast<const foostruct*>(buffer++));
        //read some values from struct and act accordingly
    }

}

What is the reinterpret_cast doing?

Body:
its basically saying the 8 bits represented at the current pointer should be interpreted as a "foostruct".

In my opinion it would be better written as follows:

const unsigned char aa = *buffer & 0x07;
const bool ab          = (*buffer & 0x08) != 0;
const unsigned char ba = (*buffer & 0x70) >> 4;
const bool bb          = (*buffer & 0x80) != 0;

I think it is far more obvious what is being done then.  I think you may well find it easier to port to Java this way too ...


问:
Is it possible to override a method in a 3rd party library?
I am using the 3rd party library Google VR in Unity.
Within one C#-source file of that lib, I add a static method call to a class LibClass like this:

```<code>void onPrerender() {
    MyOwnClass.staticMethod();
    (continue with original method call...)
}
</code>```

But every time I update the library, the call to MyOwnClass.staticMethod() is lost and I have to re-add it manually.
I can not subclass LibClass, because the library would always call LibClass and not LibSubClass.
Is there a way to programmatically add the call to staticMethod() to LibClass? Or any other way?

Edit:
I've been asked to describe the problem better:

OnPreRender is a method of the MonoBehaviour class of Unity.
This method is called before the image of the camera is rendered.
My problem is I need Google VR, which handles 2 separate cameras for each eye, to draw one of the camera images slightly different than the other.
Since OnPreRender is called for each of the cameras, I used this as an entry point for calling a static method in my own class (static only because that way I don't have to instantiate my own class in Google VRs class).

This works fine for many months now, but the Google VR lib is constantly updated and each time I do that, the method call to my own class is lost.

So I was wondering wether it is possible to kind of programmatically say "You there, OnPreRender() in that external class, when you are called by the library, jump over here and do some extra work."
Does that make sense?

答:
You can try using extension methods. Bare in mind this work only for the static calls to object functions.

You can find more:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

Body:
I am using the 3rd party library Google VR in Unity.
Within one C#-source file of that lib, I add a static method call to a class LibClass like this:

void onPrerender() {
    MyOwnClass.staticMethod();
    (continue with original method call...)
}

But every time I update the library, the call to MyOwnClass.staticMethod() is lost and I have to re-add it manually.
I can not subclass LibClass, because the library would always call LibClass and not LibSubClass.
Is there a way to programmatically add the call to staticMethod() to LibClass? Or any other way?

Edit:
I've been asked to describe the problem better:

OnPreRender is a method of the MonoBehaviour class of Unity.
This method is called before the image of the camera is rendered.
My problem is I need Google VR, which handles 2 separate cameras for each eye, to draw one of the camera images slightly different than the other.
Since OnPreRender is called for each of the cameras, I used this as an entry point for calling a static method in my own class (static only because that way I don't have to instantiate my own class in Google VRs class).

This works fine for many months now, but the Google VR lib is constantly updated and each time I do that, the method call to my own class is lost.

So I was wondering wether it is possible to kind of programmatically say "You there, OnPreRender() in that external class, when you are called by the library, jump over here and do some extra work."
Does that make sense?


问:
Query ajax with parameter only works in IE when the IE debugger is open
I just created an Ajax method.
It works if I don't pass any data to the controller.
If I want to pass some data to the controller.
It works only if I open the IE degguer.
I tried to add the cache option to false.
But it does not work.
Here is some of my code :

```<code>function ReportIdLoad(reportId) {
   $.ajax({
        type: 'POST',
        cache: false,
        url: 'WebReportGeneratorView.aspx/ReportIdLoad',
        contentType: 'application/json',
        data: JSON.stringify(reportId),
        dataType: 'json'
    })
}

[WebMethod]
public static void ReloadReportWorkbookContext(string reportId)
{
   //My code
}
</code>```

Thanks in advance for your help.

答:
@Roamer-1888 :

Thanks for the track.

Indeed,
It sounds like this problem.

I add the option :

```<code>async: false
</code>```

And I get to my break point.

Body:
I just created an Ajax method.
It works if I don't pass any data to the controller.
If I want to pass some data to the controller.
It works only if I open the IE degguer.
I tried to add the cache option to false.
But it does not work.
Here is some of my code :

function ReportIdLoad(reportId) {
   $.ajax({
        type: 'POST',
        cache: false,
        url: 'WebReportGeneratorView.aspx/ReportIdLoad',
        contentType: 'application/json',
        data: JSON.stringify(reportId),
        dataType: 'json'
    })
}

[WebMethod]
public static void ReloadReportWorkbookContext(string reportId)
{
   //My code
}

Thanks in advance for your help.

Body:
@Roamer-1888 :

Thanks for the track.

Indeed,
It sounds like this problem.

I add the option :

async: false

And I get to my break point.


问:
Using Angular to post to a APi
First week using Angular and I am now trying to post to a third party API.

I would like some help getting this form posting the data correctly, for extra points some comments and expectation on what line is doing what.

I am getting this error

```<code> ReferenceError: formData is not defined
    at h.$scope.processForm (controller.js:116)
    at angular.js:10567
    at angular.js:18627
    at h.$eval (angular.js:12412)
    at h.$apply (angular.js:12510)
    at HTMLFormElement.<anonymous> (angular.js:18626)
    at angular.js:2780
    at q (angular.js:330)
    at HTMLFormElement.c (angular.js:2779)
</code>```

The API I am posting to requires user_key 0000 and api_key 0000to be sent, although theses are not dynamic like the form fields so are always the same.

My current form

```<code><form name="myForm" id="signup-form" class="col-sm-8 col-sm-offset-2" ng-click="postdata(Fname, Lname, email)">
    <div class="form-group">
        <label for="first-name">First Name*</label>
        <input type="text" class="form-control col-sm-12" name="Fname" placeholder="Enter first name"
               ng-model="formData.Fname"
               ng-required="true">
        <span ng-if="!myForm.Fname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
    </div>

    <div class="form-group">
        <label for="first-name">Last Name*</label>
        <input type="text" class="form-control col-sm-12" name="Lname" placeholder="Enter last name"
               ng-model="formData.Lname"
               ng-required="true">
        <span ng-if="!myForm.Lname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
    </div>

    <div class="form-group">
        <label for="first-name">Email*</label>
        <input type="email" class="form-control col-sm-12" name="email" placeholder="Enter valid E-mail"
               ng-model="formData.email"
               ng-required="true">
        <span ng-if="!myForm.email.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
    </div>

    <div class="form-group row">
        <div class="col-xs-6 col-xs-offset-3">
            <button ui-sref="form.select" class="btn btn-block btn-info"
                    ng-disabled="!myForm.$valid">
                Next Section <span class="glyphicon glyphicon-circle-arrow-right"></span>
            </button>
        </div>
    </div>
 </form>
</code>```

My controller

```<code>// submit button controller POST
// =============================================================================
    .controller('formController', function ($scope, $http) {
        $scope.Fname = null;
        $scope.Lname = null;
        $scope.email = null;
        $scope.lblMsg = null;
        $scope.processForm = function (Fname, Lname, email) {
            var data = {
                Fname: formData.Fname,
                Lname: formData.Lname,
                email: formData.email,
                api_key: 0000,
                user_key: 0000
            };
//Call the services
            $http.post('https://API/do/create', JSON.stringify(data)).then(function (response) {
                if (response.data)
                    $scope.msg = "Post Data Submitted Successfully!";
            }, function (response) {
                $scope.msg = "Service not Exists";
                $scope.statusval = response.status;
                $scope.statustext = response.statusText;
                $scope.headers = response.headers();
            });
        };
    });
</code>```

答:
You should have some changes in your code.

1- Declare $scope.formData = {}

2- Remove

```<code>    $scope.Fname = null;
    $scope.Lname = null;
    $scope.email = null;
    $scope.lblMsg = null;
</code>```

because you can access to them with $scope.formData object.

3- change formData.Fname to $scope.formData.Fname, and other similar to this

```<code>  $scope.formData = {};  // declare in controller

 var data = {
            Fname: $scope.formData.Fname,
            Lname: $scope.formData.Lname,
            email: $scope.formData.email,
            api_key: 0000,
            user_key: 0000
        };
</code>```

4- you can pass formData object to function or don't pass it.If passing formData to function so use following

ng-click="postdata(formData)"

```<code>    var data = {
        Fname: formData.Fname,
        Lname: formData.Lname,
        email: formData.email,
</code>```

Title: Using Angular to post to a APi

Body:
First week using Angular and I am now trying to post to a third party API.

I would like some help getting this form posting the data correctly, for extra points some comments and expectation on what line is doing what.

I am getting this error

 ReferenceError: formData is not defined
    at h.$scope.processForm (controller.js:116)
    at angular.js:10567
    at angular.js:18627
    at h.$eval (angular.js:12412)
    at h.$apply (angular.js:12510)
    at HTMLFormElement.<anonymous> (angular.js:18626)
    at angular.js:2780
    at q (angular.js:330)
    at HTMLFormElement.c (angular.js:2779)

The API I am posting to requires user_key 0000 and api_key 0000to be sent, although theses are not dynamic like the form fields so are always the same.

My current form

<form name="myForm" id="signup-form" class="col-sm-8 col-sm-offset-2" ng-click="postdata(Fname, Lname, email)">

        First Name*
        <input type="text" class="form-control col-sm-12" name="Fname" placeholder="Enter first name"
               ng-model="formData.Fname"
               ng-required="true">

        Last Name*
        <input type="text" class="form-control col-sm-12" name="Lname" placeholder="Enter last name"
               ng-model="formData.Lname"
               ng-required="true">

        Email*
        <input type="email" class="form-control col-sm-12" name="email" placeholder="Enter valid E-mail"
               ng-model="formData.email"
               ng-required="true">

            <button ui-sref="form.select" class="btn btn-block btn-info"
                    ng-disabled="!myForm.$valid">
                Next Section
            </button>

 </form>

My controller

// submit button controller POST
// =============================================================================
    .controller('formController', function ($scope, $http) {
        $scope.Fname = null;
        $scope.Lname = null;
        $scope.email = null;
        $scope.lblMsg = null;
        $scope.processForm = function (Fname, Lname, email) {
            var data = {
                Fname: formData.Fname,
                Lname: formData.Lname,
                email: formData.email,
                api_key: 0000,
                user_key: 0000
            };
//Call the services
            $http.post('https://API/do/create', JSON.stringify(data)).then(function (response) {
                if (response.data)
                    $scope.msg = "Post Data Submitted Successfully!";
            }, function (response) {
                $scope.msg = "Service not Exists";
                $scope.statusval = response.status;
                $scope.statustext = response.statusText;
                $scope.headers = response.headers();
            });
        };
    });

Body:
You should have some changes in your code.

1- Declare $scope.formData = {}

2- Remove

    $scope.Fname = null;
    $scope.Lname = null;
    $scope.email = null;
    $scope.lblMsg = null;

because you can access to them with $scope.formData object.

3- change formData.Fname to $scope.formData.Fname, and other similar to this

  $scope.formData = {};  // declare in controller

 var data = {
            Fname: $scope.formData.Fname,
            Lname: $scope.formData.Lname,
            email: $scope.formData.email,
            api_key: 0000,
            user_key: 0000
        };

4- you can pass formData object to function or don't pass it.If passing formData to function so use following

ng-click="postdata(formData)"

    var data = {
        Fname: formData.Fname,
        Lname: formData.Lname,
        email: formData.email,


问:
SoundPool won't play a passed raw from an other Activity
I have this problem I want to pass a raw from Activity 1 to be played in Activity 2

Here is my code

Activity 1

```<code>package com.ze.zeggar.tewt;

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

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        int ThePlayedSound= R.raw.waterdrop;

        Intent MyIntent= new Intent(this, MainActivity.class);
               MyIntent.putExtra("key",ThePlayedSound);
        startActivity(MyIntent);
    }
}
</code>```

Activity 2

```<code>package com.ze.zeggar.tewt;

import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button button;
    SoundPool Sound_Pool_thing;
    int Click;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent MyIntent=getIntent();
        int ThePlayedSound= MyIntent.getIntExtra("key", 0);

        Sound_Pool_thing= new SoundPool(1, AudioManager.STREAM_MUSIC,0);

        Click = Sound_Pool_thing.load(this,ThePlayedSound , 1);

        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Sound_Pool_thing.play(Click,1,1,1,0,1);

            }
        });

    }
}
</code>```

and when I try to open the app I got "Unfortunately , My_App has stopped"
The app crashes
and here's the new crash Log after suggestions:

```<code>06-06 10:49:09.069 3424-3424/com.ze.zeggar.tewt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ze.zeggar.tewt, PID: 3424
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ze.zeggar.tewt/com.ze.zeggar.tewt.MainActivity}:
 android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
 at android.content.res.Resources.getValue(Resources.java:1269)
at android.content.res.Resources.openRawResourceFd(Resources.java:1227)
at android.media.SoundPool$SoundPoolImpl.load(SoundPool.java:566)
at android.media.SoundPool.load(SoundPool.java:229)
at com.ze.zeggar.tewt.MainActivity.onCreate(MainActivity.java:28)
at android.app.Activity.performCreate(Activity.java:5977)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2258)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
</code>```

Any idea ?

答:
What about using the MediaPlayer class?

Check this code below:

MainActivity class (or whatever class you want to start the new activity from)

```<code>Intent intent = new Intent(this,Main2Activity.class);
intent.putExtra("key",R.raw.waterdrop);
startActivity(intent);
</code>```

Main2Activity (class that will play the audio)

```<code>public class Main2Activity extends AppCompatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activitiy_main2);
    int soundId = getIntent().getIntExtra("key",0);

    final MediaPlayer mPlayer =new MediaPlayer();
    mPlayer.setAudioSessionId(soundId);
    mPlayer.setLooping(true);

    Button button = (Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPlayer.start();
        }
    });
}
}
</code>```

This code worked for me.

If it says that that specific constructor doesnt work try the below one:

```<code>final MediaPlayer mPlayer =new MediaPlayer(this,soundId);
</code>```

Hope it helps you out!

Body:
I have this problem I want to pass a raw from Activity 1 to be played in Activity 2

Here is my code

Activity 1

package com.ze.zeggar.tewt;

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

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        int ThePlayedSound= R.raw.waterdrop;

        Intent MyIntent= new Intent(this, MainActivity.class);
               MyIntent.putExtra("key",ThePlayedSound);
        startActivity(MyIntent);
    }
}

Activity 2

package com.ze.zeggar.tewt;

import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button button;
    SoundPool Sound_Pool_thing;
    int Click;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent MyIntent=getIntent();
        int ThePlayedSound= MyIntent.getIntExtra("key", 0);

        Sound_Pool_thing= new SoundPool(1, AudioManager.STREAM_MUSIC,0);

        Click = Sound_Pool_thing.load(this,ThePlayedSound , 1);

        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Sound_Pool_thing.play(Click,1,1,1,0,1);

            }
        });

    }
}

and when I try to open the app I got "Unfortunately , My_App has stopped"
The app crashes
and here's the new crash Log after suggestions:

06-06 10:49:09.069 3424-3424/com.ze.zeggar.tewt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ze.zeggar.tewt, PID: 3424
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ze.zeggar.tewt/com.ze.zeggar.tewt.MainActivity}:
 android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
 at android.content.res.Resources.getValue(Resources.java:1269)
at android.content.res.Resources.openRawResourceFd(Resources.java:1227)
at android.media.SoundPool$SoundPoolImpl.load(SoundPool.java:566)
at android.media.SoundPool.load(SoundPool.java:229)
at com.ze.zeggar.tewt.MainActivity.onCreate(MainActivity.java:28)
at android.app.Activity.performCreate(Activity.java:5977)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2258)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)

Any idea ?

Body:
What about using the MediaPlayer class?

Check this code below:

MainActivity class (or whatever class you want to start the new activity from)

Intent intent = new Intent(this,Main2Activity.class);
intent.putExtra("key",R.raw.waterdrop);
startActivity(intent);

Main2Activity (class that will play the audio)

public class Main2Activity extends AppCompatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activitiy_main2);
    int soundId = getIntent().getIntExtra("key",0);

    final MediaPlayer mPlayer =new MediaPlayer();
    mPlayer.setAudioSessionId(soundId);
    mPlayer.setLooping(true);

    Button button = (Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPlayer.start();
        }
    });
}
}

This code worked for me.

If it says that that specific constructor doesnt work try the below one:

final MediaPlayer mPlayer =new MediaPlayer(this,soundId);

Hope it helps you out!


问:
How to make a smooth moving Audio-Slider in Xamarin.Forms
How can one make a smooth moving audio player in Xamarin.Forms? Thats what i tried:

Using an MediaPlayer to play Audio-Files. Media-Player is used within
a Service called "AudioPlayer".

The property "AudioPosition" is bound to the value of the slider.

There is a cancellation token used to cancel the playing.

Code looks like:

```<code>  await Task.Run(
            () =>
                {
                    while (!ct.IsCancellationRequested)
                    {
                        this.AudioPosition = this.audioPlayer.CurrentPosition;
                    }
                },
            ct);
</code>```

This works great if i play an audio file once. However, if i try to replay the file, a few times, the UI gets blocked more and more. Seems like the Task.Run() always creates a new task and doesn't "dispose" the older ones..?

I also tried to update the values in the Device.InvokeOnMainThread() if if i use that, the Slider won't get updated at all.

How can i update the audio slider while the file is playing in a smooth way?

答:
Have you tried using a Timer instead of a Task with a while loop?

I assume your app is the only one controlling playback - so you could handle the timer in your playback pause / stop event handlers / commands.

The amount of code you are providing isn't enough to give more advanced suggestions.

Body:
How can one make a smooth moving audio player in Xamarin.Forms? Thats what i tried:

Using an MediaPlayer to play Audio-Files. Media-Player is used within
a Service called "AudioPlayer".

The property "AudioPosition" is bound to the value of the slider.

There is a cancellation token used to cancel the playing.

Code looks like:

  await Task.Run(
            () =>
                {
                    while (!ct.IsCancellationRequested)
                    {
                        this.AudioPosition = this.audioPlayer.CurrentPosition;
                    }
                },
            ct);

This works great if i play an audio file once. However, if i try to replay the file, a few times, the UI gets blocked more and more. Seems like the Task.Run() always creates a new task and doesn't "dispose" the older ones..?

I also tried to update the values in the Device.InvokeOnMainThread() if if i use that, the Slider won't get updated at all.

How can i update the audio slider while the file is playing in a smooth way?


问:
db.find vs db.aggregation to select nested array Object
I'v tried to perform the following  query :

```<code>db.getCollection('fxh').find({"username": "user1", "pf.acc.accnbr" : 915177},{userid: true, "pf.pfid": true,  "pf.acc.accid":true})
</code>```

and my collection is the following :

```<code>{
    "_id" : ObjectId("5932fd8f381d4c0a7de21942"),
    "userid" : 1496513894,
    "username" : "user1",
    "email" : "user1@gmail.com",
    "fullname" : "User 1",
    "pf" : {
        "acc" : [
            {
                "cyc" : [
                    {
                        "det" : {
                            "status" : "New",
                            "dcycid" : 1496513941
                        },
                        "status" : "New",
                        "name" : "QPT202017_M1",
                        "cycid" : 1496513940
                    }
                ],
                "status" : "New",
                "accnbr" : 915177,
                "accid" : 1496513939
            },
            {
                "cyc" : [
                    {
                        "det" : {
                            "status" : "New",
                            "dcycid" : 1496552643
                        },
                        "status" : "New",
                        "name" : "QPT202017_S8",
                        "cycid" : 1496552642
                    }
                ],
                "status" : "New",
                "accnbr" : 73497,
                "accid" : 1496552641
            }
        ],
        "pfid" : 1496513935,
    },
    "lastupdate" : ISODate("2017-06-03T18:18:55.080Z"),
    "__v" : 0
}
</code>```

When I execute the query the result is the following :

```<code>{
    "_id" : ObjectId("5932fd8f381d4c0a7de21942"),
    "userid" : 1496513894,
    "portfolio" : {
        "acc" : [
            {
                "accid" : 1496513939
            },
            {
                "accid" : 1496552641
            }
        ],
        "pfid" : 1496513935
    }
}
</code>```

And my problem is that I need to see only the concerned accid and the result returns the all accid !.

Any idea how just to return the selected accid of accnbr ?

NB : I have also tried to add $ sign at the end of my query , it
  selects the right acc but it returns the all objects or I need just
  only ONE returned object.

On 6/5/17

I also used the aggregate command instead of find and it get result by using this :

```<code>db.getCollection('fxh').aggregate([  { $unwind : "$pf.acc"} , { $match : {"username":"adh1", "pf.acc.accbr": 915177 } }, {$project : {_id:0, accid: "$pf.acc.accid"}}])
</code>```

But could NOT get a lower level result, when I ran this :

```<code>db.getCollection('fxh').aggregate([  { $unwind : "$pf.acc.cyc"} , { $match : {"username":"adh1", "pf.acc.accbr": 915177, "pf.acc.cyc.name": "QPT202017_M1" } }, {$project : {_id:0, cycid: "$pf.acc.cyc.cycid"}}])
</code>```

Any idea ?

答:
You can try the below aggregation pipeline.

The idea is to $unwind one nested level at a time, starting from the outermost to the innermost.

For each nested level unwinding, you can apply the$match to limit the documents and continue till you have the desired shape.

You can $group it together at the end to get back to the original shape.

```<code>db.getCollection('fxh').aggregate([
{ $match : {"username":"adh1"} },
{ $unwind : "$pf.acc"} ,
{ $match : {"pf.acc.accbr": 915177 } },
{ $unwind : "$pf.acc.cyc"},
{ $match : {"pf.acc.cyc.name": "QPT202017_M1" } },
{$project : {_id:0, accid: "$pf.acc.accid", cycid: "$pf.acc.cyc.cycid"}}])
</code>```

Body:
I'v tried to perform the following  query :

db.getCollection('fxh').find({"username": "user1", "pf.acc.accnbr" : 915177},{userid: true, "pf.pfid": true,  "pf.acc.accid":true})

and my collection is the following :

{
    "_id" : ObjectId("5932fd8f381d4c0a7de21942"),
    "userid" : 1496513894,
    "username" : "user1",
    "email" : "user1@gmail.com",
    "fullname" : "User 1",
    "pf" : {
        "acc" : [
            {
                "cyc" : [
                    {
                        "det" : {
                            "status" : "New",
                            "dcycid" : 1496513941
                        },
                        "status" : "New",
                        "name" : "QPT202017_M1",
                        "cycid" : 1496513940
                    }
                ],
                "status" : "New",
                "accnbr" : 915177,
                "accid" : 1496513939
            },
            {
                "cyc" : [
                    {
                        "det" : {
                            "status" : "New",
                            "dcycid" : 1496552643
                        },
                        "status" : "New",
                        "name" : "QPT202017_S8",
                        "cycid" : 1496552642
                    }
                ],
                "status" : "New",
                "accnbr" : 73497,
                "accid" : 1496552641
            }
        ],
        "pfid" : 1496513935,
    },
    "lastupdate" : ISODate("2017-06-03T18:18:55.080Z"),
    "__v" : 0
}

When I execute the query the result is the following :

{
    "_id" : ObjectId("5932fd8f381d4c0a7de21942"),
    "userid" : 1496513894,
    "portfolio" : {
        "acc" : [
            {
                "accid" : 1496513939
            },
            {
                "accid" : 1496552641
            }
        ],
        "pfid" : 1496513935
    }
}

And my problem is that I need to see only the concerned accid and the result returns the all accid !.

Any idea how just to return the selected accid of accnbr ?

NB : I have also tried to add $ sign at the end of my query , it
  selects the right acc but it returns the all objects or I need just
  only ONE returned object.

On 6/5/17

I also used the aggregate command instead of find and it get result by using this :

db.getCollection('fxh').aggregate([  { $unwind : "$pf.acc"} , { $match : {"username":"adh1", "pf.acc.accbr": 915177 } }, {$project : {_id:0, accid: "$pf.acc.accid"}}])

But could NOT get a lower level result, when I ran this :

db.getCollection('fxh').aggregate([  { $unwind : "$pf.acc.cyc"} , { $match : {"username":"adh1", "pf.acc.accbr": 915177, "pf.acc.cyc.name": "QPT202017_M1" } }, {$project : {_id:0, cycid: "$pf.acc.cyc.cycid"}}])

Any idea ?

Body:
You can try the below aggregation pipeline.

The idea is to $unwind one nested level at a time, starting from the outermost to the innermost.

For each nested level unwinding, you can apply the$match to limit the documents and continue till you have the desired shape.

You can $group it together at the end to get back to the original shape.

db.getCollection('fxh').aggregate([
{ $match : {"username":"adh1"} },
{ $unwind : "$pf.acc"} ,
{ $match : {"pf.acc.accbr": 915177 } },
{ $unwind : "$pf.acc.cyc"},
{ $match : {"pf.acc.cyc.name": "QPT202017_M1" } },
{$project : {_id:0, accid: "$pf.acc.accid", cycid: "$pf.acc.cyc.cycid"}}])


问:
jQueryUI Tab - Selected TabText on demand
I need a function which will get the text of the currently selected tab. I can get the selected tab using events, but I need to get the text even if the selected event is not yet thrown.

Here's my event script,

```<code>    $( "#tabs" ).bind( "tabsselect", function(event, ui) {
         _textOfTab=$(ui.tab).text();
     });
</code>```

How can I just query the tabs for the currently selected one?

答:
The
 of the selected tab will have a ui-tabs-selected class on it, you can use that to find the active tab.

```<code>$("#tabs ul.ui-tabs-nav li.ui-tabs-selected").text()
</code>```

You can test it out here.

Body:
I need a function which will get the text of the currently selected tab. I can get the selected tab using events, but I need to get the text even if the selected event is not yet thrown.

Here's my event script,

    $( "#tabs" ).bind( "tabsselect", function(event, ui) {
         _textOfTab=$(ui.tab).text();
     });

How can I just query the tabs for the currently selected one?

Body:
The <li> of the selected tab will have a ui-tabs-selected class on it, you can use that to find the active tab.

$("#tabs ul.ui-tabs-nav li.ui-tabs-selected").text()

You can test it out here.


问:
Convert int MMDDYYYY into datetime MM-DD-YYYY
I would like to
convert int MMDDYYYY (e.g.-5112012) into datetime MM-DD-YYYY
and then convert datetime MM-DD-YYYY into YYYY-MM-DD
or if the above can be done in one step converting int MMDDYYYY into datetime YYYY-MM-DD?

For reference, earlier I converted int YYYYMMDD into datetime YYYY-MM-DD using the following syntax:

```<code>declare @date int;
set @date = 19900511
select CONVERT(datetime, convert(varchar(8),@date), 103)
</code>```

答:
```<code>convert( datetime,
  case when @MMDDYYYY = 0 then
    null
  else
    substring(convert( varchar(9), 800000000 + @MMDDYYYY ) , 2, 2)
               + '/' +  substring(
                   convert( varchar(9), 800000000 + @MMDDYYYY ) , 4, 2)
               + '/' + right(@MMDDYYYY,4) end ) as New_Date
</code>```

Body:
I would like to
convert int MMDDYYYY (e.g.-5112012) into datetime MM-DD-YYYY
and then convert datetime MM-DD-YYYY into YYYY-MM-DD
or if the above can be done in one step converting int MMDDYYYY into datetime YYYY-MM-DD?

For reference, earlier I converted int YYYYMMDD into datetime YYYY-MM-DD using the following syntax:

declare @date int;
set @date = 19900511
select CONVERT(datetime, convert(varchar(8),@date), 103)


问:
Apache Spark vs Apache Ignite
Currently I'm studying Apache spark and Apache ignite frameworks.

Some principle differences between them are described in this article ignite vs spark But I realized that I still don't understand their purposes.

I mean for which problems spark more preferable than ignite and vice versa?

答:
Apache Ignite is a high-performance, integrated and distributed in-memory platform for computing and transacting on large-scale data sets in real-time.Ignite is a data-source-agnostic platform and can distribute and cache data across multiple servers in RAM to deliver unprecedented processing speed and massive application scalability.

Apache Spark(cluster computing framework) is a fast, in-memory data processing engine with expressive development APIs to allow data workers to efficiently execute streaming, machine learning or SQL workloads that require fast iterative access to datasets.
By allowing user programs to load data into a cluster’s memory and query it repeatedly, Spark is well suited for high-performance computing and machine learning algorithms.

Some conceptual differences:

Spark doesn’t store data, it loads data for processing from other storages, usually disk-based, and then discards the data when the processing is finished. Ignite, on the other hand, provides a distributed in-memory key-value store (distributed cache or data grid) with ACID transactions and SQL querying capabilities.

Spark is for non-transactional, read-only data (RDDs don’t support in-place mutation), while Ignite supports both non-transactional (OLAP) payloads as well as fully ACID compliant transactions (OLTP)

Ignite fully supports pure computational payloads (HPC/MPP) that can be “dataless”. Spark is based on RDDs and works only on data-driven payloads.

Conclusion:

Ignite and Spark are both in-memory computing solutions but they target different use cases.

In many cases, they are used together to achieve superior results:

Ignite can provide shared storage, so the state can be passed from one Spark application or job to another.

Ignite can provide SQL with indexing so Spark SQL can be accelerated over 1,000x (spark doesn’t index the data)

When working with files instead of RDDs, the Apache Ignite In-Memory File System (IGFS) can also share state between Spark jobs and applications

Title: Apache Spark vs Apache Ignite


问:
Using regex in Powershell replace string in single quotation marks
considering this file

```<code>AppConfig = {
    version: '4.0.0',
    clientId: "guid",
    httpProxy: 'rest',
    restUrl: "http://url.contoso.com/v1/",

    conferences: ["lync", "hangouts", "webex"],    // "lync", "hangouts", "webex"

    dataRefreshInterval: 60 //seconds
}
</code>```

I want to replace  the string inside the single quotation marks with another string. I want to change the value of the specific property (in my case version).

```<code>$content = Get-Content $VersionFile

for($i = 0;$i -lt $content.Count; $i++)
{
    if($content[$i] -like "*version:*")
    {
        $content[$i] = $content[$i] -creplace <replaceWhat>, <replaceWith>
    }
}
</code>```

more elegant way how to find the line with version is appreciated.

答:
You can try this :</p>

```<code>$version = "x.x.x.x"
$content = Get-Content $VersionFile
$content -replace "version: '(.*)'","version: '$version'"
</code>```

Body:
considering this file

AppConfig = {
    version: '4.0.0',
    clientId: "guid",
    httpProxy: 'rest',
    restUrl: "http://url.contoso.com/v1/",

    conferences: ["lync", "hangouts", "webex"],    // "lync", "hangouts", "webex"

    dataRefreshInterval: 60 //seconds
}

I want to replace  the string inside the single quotation marks with another string. I want to change the value of the specific property (in my case version).

$content = Get-Content $VersionFile

for($i = 0;$i -lt $content.Count; $i++)
{
    if($content[$i] -like "*version:*")
    {
        $content[$i] = $content[$i] -creplace <replaceWhat>, <replaceWith>
    }
}

more elegant way how to find the line with version is appreciated.

Body:
You can try this :

$version = "x.x.x.x"
$content = Get-Content $VersionFile
$content -replace "version: '(.*)'","version: '$version'"


问:
C++ : Why it dont work?
I was trying to solve

In which you have given a array of int and you have to return its sum.

```<code>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;

int main(){
int n;
cin >> n;
int k;
vector<int> arr(n);
for(int arr_i = 0;arr_i < n;arr_i++){
   cin >> arr[arr_i];
    k = k + arr[arr_i];
    //cout << "arr = " << arr[arr_i] << " k " << k << endl;     //  [0]
    if (arr_i == (n-1))
    {
        cout << k;
    }

}
return 0;
}
</code>```

This return a afkard no. instead of sum.

But when uncomment out [0] line. code starts working as it should.

P.S. i found out the solution by changing cout to cerr.
but wanted to know why it doesn't work.

答:
As the other answers (+1) suggested, you need to initialize k. However, I think it is slightly better to assign it the first value initially and reduce the number of iterations therefore:

```<code>vector<int> arr(n);
if (n > 0) {
    int k = arr[0];
    for(int arr_i = 1;arr_i < n;arr_i++){
        //Your cycle
    }
}
</code>```

Title: C++ : Why it dont work?

Body:
I was trying to solve

In which you have given a array of int and you have to return its sum.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;

int main(){
int n;
cin >> n;
int k;
vector<int> arr(n);
for(int arr_i = 0;arr_i < n;arr_i++){
   cin >> arr[arr_i];
    k = k + arr[arr_i];
    //cout << "arr = " << arr[arr_i] << " k " << k << endl;     //  [0]
    if (arr_i == (n-1))
    {
        cout << k;
    }

}
return 0;
}

This return a afkard no. instead of sum.

But when uncomment out [0] line. code starts working as it should.

P.S. i found out the solution by changing cout to cerr.
but wanted to know why it doesn't work.

Body:
As the other answers (+1) suggested, you need to initialize k. However, I think it is slightly better to assign it the first value initially and reduce the number of iterations therefore:

vector<int> arr(n);
if (n > 0) {
    int k = arr[0];
    for(int arr_i = 1;arr_i < n;arr_i++){
        //Your cycle
    }
}


问:
Adjust OOM killer for subprocess in Docker container
Please help to find an appropriate solution.

There is a java service running in Ubuntu environment, that periodically invokes external process with params (multiple instances of the same program). Everything is packed into Docker container (memory limit is set, unprivileged, readonly except tmp and logs, cap_drop all). Sometimes the data supplied to subprocess makes it overfill the memory limit. So, in that case we'd like to kill subprocess(es) due to OOM, but leave parent (java) process running.

If speaking about non-docker system, there is a set of methods to achieve this, as: creating a custom cgroup, set memory limit and attach subprocesses to it. Another way is to adjust /proc/PID/oom_adj setting to make subprocesses having larger oom_score.

But in docker container I can't find a way to do it in a simple way, without running container in privileged mode and adding external wrappers to the main process.

Is there a native way to add memory cgroup inside container or adjust OOM killer?

Thanks in advance!

答:
The only way is to use the --oom-score-adj option to docker run or even --oom-kill-disable.

https://docs.docker.com/engine/reference/run/#runtime-constraints-on-resources


问:
grant in postgresql 9.5 specified for row
I want to add grant with where clause, not for columns, for different users. I'm using this grant update (ename), insert (empno, ename)  on emp to xyz; for catching columns but I can't do this for rows.

Is there any method ?

答:
Just follow this guide : https://www.postgresql.org/docs/9.5/static/ddl-rowsecurity.html
It's pretty straight forward and well documented.</p>


问:
MongoDB - Permission denied for socket: 127.0.0.1:27025
I am getting an erro log after the reboot of Redhat 7

```<code>listen(): bind() failed errno:13 Permission denied for socket: 127.0.0.1:27025
systemd[1]: mongod.service: main process exited, code=exited, status=100/n/a
</code>```

mongod.service

```<code>[Unit]
  Description=High-performance, schema-free document-oriented database
  After=network.target

 [Service]
   User=mongod
   Group=mongod
   Environment="OPTIONS=--quiet -f /etc/mongod1.conf"
   ExecStart=/usr/bin/mongod $OPTIONS run
   ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb
   ExecStartPre=/usr/bin/chown root:root /var/run/mongodb
   ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb
   PermissionsStartOnly=true
   PIDFile=/var/run/mongodb/mongod1.pid

 [Install]
   WantedBy=multi-user.target
</code>```

mongod1.conf

```<code>#systemLog:
  destination: file
  logAppend: true
  path: /home/telenstanley/mongod1.log

# Where and how to store data.
storage:
  dbPath: /var/lib/mongo/db1
  journal:
    enabled: true
#  engine:
  mmapv1:
    smallFiles: true
#  wiredTiger:

# how the process runs
processManagement:
  fork: false  # fork and run in background
  pidFilePath: /var/run/mongodb/mongod1.pid  # location of pidfile

# network interfaces
net:
  port: 27025
  bindIp: 127.0.0.1  # Listen to local interface only, comment to listen on all interfaces.

#security:
 # authorization: enabled
#operationProfiling:

replication:
  oplogSizeMB: 1024
  replSetName: testrep
#sharding:

## Enterprise-Only Options
</code>```

I am not able to find any useful answer for my problem yet.but the mongod starts successfully by running as root user from cmd

sudo mongod -f mongod1.conf

答:
My mongod.service has

```<code>  ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb
</code>```

instead of

```<code>  ExecStartPre=/usr/bin/chown root:root /var/run/mongodb
</code>```

The owner is mongod instead of root.

Body:
I am getting an erro log after the reboot of Redhat 7

listen(): bind() failed errno:13 Permission denied for socket: 127.0.0.1:27025
systemd[1]: mongod.service: main process exited, code=exited, status=100/n/a

mongod.service

[Unit]
  Description=High-performance, schema-free document-oriented database
  After=network.target

 [Service]
   User=mongod
   Group=mongod
   Environment="OPTIONS=--quiet -f /etc/mongod1.conf"
   ExecStart=/usr/bin/mongod $OPTIONS run
   ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb
   ExecStartPre=/usr/bin/chown root:root /var/run/mongodb
   ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb
   PermissionsStartOnly=true
   PIDFile=/var/run/mongodb/mongod1.pid

 [Install]
   WantedBy=multi-user.target

mongod1.conf

#systemLog:
  destination: file
  logAppend: true
  path: /home/telenstanley/mongod1.log

# Where and how to store data.
storage:
  dbPath: /var/lib/mongo/db1
  journal:
    enabled: true
#  engine:
  mmapv1:
    smallFiles: true
#  wiredTiger:

# how the process runs
processManagement:
  fork: false  # fork and run in background
  pidFilePath: /var/run/mongodb/mongod1.pid  # location of pidfile

# network interfaces
net:
  port: 27025
  bindIp: 127.0.0.1  # Listen to local interface only, comment to listen on all interfaces.

#security:
 # authorization: enabled
#operationProfiling:

replication:
  oplogSizeMB: 1024
  replSetName: testrep
#sharding:

## Enterprise-Only Options

I am not able to find any useful answer for my problem yet.but the mongod starts successfully by running as root user from cmd

sudo mongod -f mongod1.conf

Body:
My mongod.service has

  ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb

instead of

  ExecStartPre=/usr/bin/chown root:root /var/run/mongodb

The owner is mongod instead of root.


问:
How to parse out date from non standard date string
I have a date that is returned in this string format from moment.js for a calendar app.

Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)

How can i parse this string back into '2017-06-16', using moment to backtrack specifies this is an invalid input. Using it as an instance of new Date() returns to me an incorrect date.

```<code>var check = moment('Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)', 'YYYY/MM/DD');

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

console.log(month, day, year);
//-->invalid date
</code>```

http://jsfiddle.net/t89apndd/

答:
You don't need moment.js.

Just use the native Date() constructor.

const date = new Date('Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)');
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
console.log(day, month, year);```
</div>
</div>
</p>

<p>And if you need to convert an existing moment.js date:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const momentDate = ...;//insert your moment.js date here
const date = new Date(momentDate._i);
const day = date.getDate();
const month = date.getMonth();
const year = date.getFullYear();
console.log(day, month, year);</code>```

Body:
I have a date that is returned in this string format from moment.js for a calendar app.

Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)

How can i parse this string back into '2017-06-16', using moment to backtrack specifies this is an invalid input. Using it as an instance of new Date() returns to me an incorrect date.

var check = moment('Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)', 'YYYY/MM/DD');

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

console.log(month, day, year);
//-->invalid date

http://jsfiddle.net/t89apndd/

Body:
You don't need moment.js.

Just use the native Date() constructor.

const date = new Date('Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)');
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
console.log(day, month, year);

And if you need to convert an existing moment.js date:

const momentDate = ...;//insert your moment.js date here
const date = new Date(momentDate._i);
const day = date.getDate();
const month = date.getMonth();
const year = date.getFullYear();
console.log(day, month, year);


问:
dotnet core and angular node dependency?
Having a hard time trying to figure out why my dotnet new angular application has a node dependency when running through iis?  Using Visual Studio Code and dotnet core 1.0.4, after publishing, my application still has a dependency on node.js?  Not sure why.  We are running the application through iis, but our production server does not have node installed and this results in a 500 status code.  We are using Microsoft spa package which has angular 2.

Has anyone else had any similar issue?

How can I remove the node dependency?

答:
You need to deploy the build.

you can get the build static content through.

```<code> ng build --prod --aot
</code>```

It will create a dist folder deploy that code.

Body:
You need to deploy the build.

you can get the build static content through.

 ng build --prod --aot

It will create a dist folder deploy that code.


问:
Angular Pipe: Cannot replace /n
I have been trying to make a pipe to replace certain characters in a message, this is the code for the pipe:

```<code>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
  transform(value: string): string {
    console.log(value);
    let newValue = value.replace(/\n/g, '<br>');
    console.log(newValue);
    return `${newValue}`;
  }
}
</code>```

I am using it on the page like this:

```<code>  <ion-card-content [innerHtml]="message | linky | replace"></ion-card-content>
</code>```

The Issue: It works when the replace statement is something is like this:

```<code>let newValue = value.replace('bit', '<br>');
</code>```

But is doesn't do anything when it looks like this:(I need to get it working for this)

```<code>let newValue = value.replace(/\n/g, '<br>');
</code>```

I can't seem to figure out where am I going wrong.

答:
Are you sure the \n character is in your string? It is probably there as a string. Give this a try: let newValue = value.replace(/\\n/g, '
'); The reason why you need is is because your string actuaally cointains "\n" and not the newline character. In a regex \n is a newline character and \\n is "\n" as string.

Title: Angular Pipe: Cannot replace /n

Body:
I have been trying to make a pipe to replace certain characters in a message, this is the code for the pipe:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
  transform(value: string): string {
    console.log(value);
    let newValue = value.replace(/\n/g, '
');
    console.log(newValue);
    return `${newValue}`;
  }
}

I am using it on the page like this:

  <ion-card-content [innerHtml]="message | linky | replace"></ion-card-content>

The Issue: It works when the replace statement is something is like this:

let newValue = value.replace('bit', '
');

But is doesn't do anything when it looks like this:(I need to get it working for this)

let newValue = value.replace(/\n/g, '
');

I can't seem to figure out where am I going wrong.

Body: Are you sure the \n character is in your string? It is probably there as a string. Give this a try: let newValue = value.replace(/\\n/g, '<br>'); The reason why you need is is because your string actuaally cointains "\n" and not the newline character. In a regex \n is a newline character and \\n is "\n" as string.


问:
Why MediaPlayer does not work SeekTo
Why MediaPlayer does not work SeekTo .
SeekTo More precisely, it works, but if you add SeekTo (5000) or SeekTo  (10000).

But if you do this. SeekTo (1000) or SeekTo (3563) then nothing will work.
Then MediaPlayer starts playing video from 0. Why is it so? And how to fix it.

答:
Based on this answer, this code may work:

```<code>public void forwardSong() {
if (mPlayer != null) {
    int currentPosition = mPlayer.getCurrentPosition();
    if (currentPosition + seekForwardTime <= mPlayer.getDuration()) {
        mPlayer.seekTo(currentPosition + seekForwardTime);
    } else {
        mPlayer.seekTo(mPlayer.getDuration());
    }
}
</code>```

}

Title: Why MediaPlayer does not work SeekTo

Body:
Based on this answer, this code may work:

public void forwardSong() {
if (mPlayer != null) {
    int currentPosition = mPlayer.getCurrentPosition();
    if (currentPosition + seekForwardTime <= mPlayer.getDuration()) {
        mPlayer.seekTo(currentPosition + seekForwardTime);
    } else {
        mPlayer.seekTo(mPlayer.getDuration());
    }
}

}


答:
Contrary to your dump of date, the object show me the attribute

```<code>_isValid: false
</code>```

check the fiddle and console log
https://jsfiddle.net/s6x87u1p/

Title: How to parse out date from non standard date string

Body:
Contrary to your dump of date, the object show me the attribute

_isValid: false

check the fiddle and console log
https://jsfiddle.net/s6x87u1p/


问:
How to serve an Angular 2 dist folder index.html
I'm using this angular 4 seed app: https://github.com/2sic/app-tutorial-angular4-hello-dnn

It uses webpack and works fine.

It only seems to serve the dev files and not the dist/ folder.

I want to ng serve the dist folder.

Not sure the command to do this or if I need to install a lite server or something.

I run this command to create the dist folder (which works fine):

```<code>g build --prod --aot --output-hashing=none
</code>```

Now I want to run this build in the browser.

答:
You need a server to serve your generated build.

I am using http-server. Install http-server using:

```<code>npm install -g http-server
</code>```

now go inside your dist folder and run this command

```<code>http-server
</code>```

as shown here:

Check http://localhost:8080 in your browser

Body:
I'm using this angular 4 seed app: https://github.com/2sic/app-tutorial-angular4-hello-dnn

It uses webpack and works fine.

It only seems to serve the dev files and not the dist/ folder.

I want to ng serve the dist folder.

Not sure the command to do this or if I need to install a lite server or something.

I run this command to create the dist folder (which works fine):

g build --prod --aot --output-hashing=none

Now I want to run this build in the browser.

Body:
You need a server to serve your generated build.

I am using http-server. Install http-server using:

npm install -g http-server

now go inside your dist folder and run this command

http-server

as shown here:

Check http://localhost:8080 in your browser