问:
SQLAlchemy equivalent of Django ORM's relationship-spanning filter
This example is from the Django documentation.

Given the (Django) database model:

```<code>class Blog(models.Model):
    name = models.CharField(max_length=100)

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
</code>```

In Django I can use:

```<code>Entry.objects.filter(blog__name__exact='Beatles Blog')
</code>```

to get all Entry objects for blogs with the specified name.

Question: What is the equivalent SQLAlchemy statement, given the model definition below?

```<code>class Blog(Base):
    __tablename__ = "blog"
    id = Column(Integer, primary_key=True)
    name = Column(Unicode(100))

class Entry(Base):
    __tablename__ = "entry"
    id = Column(Integer, primary_key=True)
    blogid = Column(Integer, ForeignKey(Blog.id))
    headline = Column(Unicode(255))
    body_text = Column(UnicodeText)

    blog = relationship(Blog, backref="entries")
</code>```

EDIT

I believe there are two ways to accomplish this:

```<code>>>> q = session.query
>>> print q(Entry).join(Blog).filter(Blog.name == u"One blog")
SELECT entry.id AS entry_id, entry.blogid AS entry_blogid, entry.headline AS entry_headline, entry.body_text AS entry_body_text
FROM entry JOIN blog ON blog.id = entry.blogid
WHERE blog.name = ?

>>> print q(Entry).filter(Entry.blog.has(Blog.name == u"One blog"))
SELECT entry.id AS entry_id, entry.blogid AS entry_blogid, entry.headline AS entry_headline, entry.body_text AS entry_body_text
FROM entry
WHERE EXISTS (SELECT 1
FROM blog
WHERE blog.id = entry.blogid AND blog.name = ?)

# ... and of course
>>> blog = q(Blog).filter(Blog.name == u"One blog")
>>> q(Entry).filter(Entry.blog == blog)
</code>```

A few more questions:

Are there other ways to accomplish this using SQLAlchemy than the ones above?

Would it not make sense if you could do session.query(Entry).filter(Entry.blog.name == u"One blog") in many-to-one relationships?

What SQL does Django's ORM produce in this case?

答:
I also always dreamed of having Django-like "magic joins". I'm familiar with
sqlalchemy-django-query it, I found that it's not powerful enough for my tasks.

That's why I created
https://github.com/absent1706/sqlalchemy-mixins#django-like-queries.

It works similar to sqlalchemy-django-query but has more additional features (here's a comparison). Also it's well tested and documented.

Body:
This example is from the Django documentation.

Given the (Django) database model:

class Blog(models.Model):
    name = models.CharField(max_length=100)

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()

In Django I can use:

Entry.objects.filter(blog__name__exact='Beatles Blog')

to get all Entry objects for blogs with the specified name.

Question: What is the equivalent SQLAlchemy statement, given the model definition below?

class Blog(Base):
    __tablename__ = "blog"
    id = Column(Integer, primary_key=True)
    name = Column(Unicode(100))

class Entry(Base):
    __tablename__ = "entry"
    id = Column(Integer, primary_key=True)
    blogid = Column(Integer, ForeignKey(Blog.id))
    headline = Column(Unicode(255))
    body_text = Column(UnicodeText)

    blog = relationship(Blog, backref="entries")

EDIT

I believe there are two ways to accomplish this:

>>> q = session.query
>>> print q(Entry).join(Blog).filter(Blog.name == u"One blog")
SELECT entry.id AS entry_id, entry.blogid AS entry_blogid, entry.headline AS entry_headline, entry.body_text AS entry_body_text
FROM entry JOIN blog ON blog.id = entry.blogid
WHERE blog.name = ?

>>> print q(Entry).filter(Entry.blog.has(Blog.name == u"One blog"))
SELECT entry.id AS entry_id, entry.blogid AS entry_blogid, entry.headline AS entry_headline, entry.body_text AS entry_body_text
FROM entry
WHERE EXISTS (SELECT 1
FROM blog
WHERE blog.id = entry.blogid AND blog.name = ?)

# ... and of course
>>> blog = q(Blog).filter(Blog.name == u"One blog")
>>> q(Entry).filter(Entry.blog == blog)

A few more questions:

Are there other ways to accomplish this using SQLAlchemy than the ones above?

Would it not make sense if you could do session.query(Entry).filter(Entry.blog.name == u"One blog") in many-to-one relationships?

What SQL does Django's ORM produce in this case?


来源: stackexchange

问:
How to find out if a cookie is already there?
So I do simple JS function like

```<code>function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

}
</code>```

how tm make sure that users_resolution is set?

答:
You could write a function like so:

```<code>  function getCookie(cName) {
    var cVal = document.cookie.match('(?:^|;) ?' + cName + '=([^;]*)(?:;|$)');
    if (!cVal) {
      return "";
    } else {
      return cVal[1];
    }
  }
</code>```

Then, after you have set the cookie, you can call getCookie() and test it's return value, if it's equal to an empty string, or "", which is false, then the cookie doesn't exist. Otherwise you've got a valid cookie value.

The above paragraph in code:

```<code>var cookie = getCookie("users_resolution");
if (!cookie) {
   // cookie doesn't exist
} else {
  // cookie exists
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
So I do simple JS function like

function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

}

how tm make sure that users_resolution is set?

Body:
You could write a function like so:

  function getCookie(cName) {
    var cVal = document.cookie.match('(?:^|;) ?' + cName + '=([^;]*)(?:;|$)');
    if (!cVal) {
      return "";
    } else {
      return cVal[1];
    }
  }

Then, after you have set the cookie, you can call getCookie() and test it's return value, if it's equal to an empty string, or "", which is false, then the cookie doesn't exist. Otherwise you've got a valid cookie value.

The above paragraph in code:

var cookie = getCookie("users_resolution");
if (!cookie) {
   // cookie doesn't exist
} else {
  // cookie exists
}


问:
Keras multi-class prediction output is limited to one class
I constructed a sequential keras model with 35000 input samples and 20 predictors, the test data output classes distribution is :

Class_0 = 5.6%

Class_1 = 7.7%

Class_2 = 35.6%

Class_3 = 45.7%

Class_4 = 5.4%

After transforming the outputs into binary class matrix utilizing (np_utils.to_categorical) the training accuracy is around 54%, when i do model fitting with test data (15000 samples), all predictions (100%) happen to be for the same class which is class_3 "highest occurrence in training output", what is the cause of this bias and not having a single prediction for other classes? how to make the model sensitive for predicting fewer classes and improve the accuracy especially if the concurrence in training data is low like  1 - 3%.

```<code>model = Sequential()
model.add(Dense(40, input_dim=20,  activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10,  activation='relu'))
model.add(Dense(5, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

model.fit(X, Y, epochs=500,  verbose=1)
</code>```

答:
One way to solve is by over sampling under represented class examples.
i.e., if you have two classes A(66.6%) and B(33.3%), then you sample B twice compared to A.
To make it further simple, you can change your dataset by duplicating B once and making the dataset something like A+2*B.

Or, you can modify your loss function such that it gives more weight when misclassifying the under represented classes.

ContentLicense: CC BY-SA 3.0

Body:
I constructed a sequential keras model with 35000 input samples and 20 predictors, the test data output classes distribution is :

Class_0 = 5.6%

Class_1 = 7.7%

Class_2 = 35.6%

Class_3 = 45.7%

Class_4 = 5.4%

After transforming the outputs into binary class matrix utilizing (np_utils.to_categorical) the training accuracy is around 54%, when i do model fitting with test data (15000 samples), all predictions (100%) happen to be for the same class which is class_3 "highest occurrence in training output", what is the cause of this bias and not having a single prediction for other classes? how to make the model sensitive for predicting fewer classes and improve the accuracy especially if the concurrence in training data is low like  1 - 3%.

model = Sequential()
model.add(Dense(40, input_dim=20,  activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10,  activation='relu'))
model.add(Dense(5, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

model.fit(X, Y, epochs=500,  verbose=1)


问:
What is the practical relationship between the streams memory bandwidth benchmark and the potential speedup from running MPI locally?
I ran the streams memory bandwidth benchmark (https://www.cs.virginia.edu/stream/) on a computer with 10 processors. The benchmark indicated that after 3 or 4 processors, the speedup plateaued at about 3x. What are the practical implications of this result for the performance of an MPI code? For simplicity, assume the program is running multiple processes locally on this multicore machine only. Does this mean that if you are running a memory access intensive program, then you will not be able to get more than 3x speedup, even if you use all the cores? If you ran a program that was not memory-access intensive, could you theoretically get the full 10x? If you simultaneously ran two or three memory access intensive programs, each using three processors, would they each be able to get 3x speedup, or would they interfere with each other and slow each other down as they all simultaneously pulled from RAM?</p>

答:
Speedup is about how much parallelism exist in the code. Moreover, any resource could also become a bottleneck depending on the type of the application. If your application is memory intensive, then you will be limited by the memory bandwidth. If its not memory intensive, and it is highly parallel (take Monte Carlo sampling as an example), then you will get close to the full speedup from your cores.

To answer your last question (multiple memory-intensive): at the end of the day we rely on memory controllers to do read/write. So it depends on the memory banks and where the physical pages are allocated from. So, any of the two situations that you mentioned could happen.


问:
Unknown type name 'namespace'
I currently work on a react-native 0.29.1 app. I updated to 0.29.1 and cannot build anymore. The error i get is the following:

```<code>Unknown type name 'namespace'
</code>```

It looks like an error in the assert.h from Facebook. When i right click on the erroneous file and open it in the Finder i get the following path:

```<code>MyApp/node_modules/react-native/ReactAndroid/src/main/jni/first-party/fb/include/fb/assert.h
</code>```

But the include tree on the left says something different.

This are my header search paths

EDIT: I think i found my error but i don't know why this happed. I cleaned up the header paths and removed everything except the 3 default paths and it works now. Can someone tell me why xcode created this paths instead of them i provided?

The problem was line 4.

答: Try to update xcode to the latest version or use for compilation objective-c++ instead objective-c.</p>

Title: Unknown type name 'namespace'

Body:
I currently work on a react-native 0.29.1 app. I updated to 0.29.1 and cannot build anymore. The error i get is the following:

Unknown type name 'namespace'

It looks like an error in the assert.h from Facebook. When i right click on the erroneous file and open it in the Finder i get the following path:

MyApp/node_modules/react-native/ReactAndroid/src/main/jni/first-party/fb/include/fb/assert.h

But the include tree on the left says something different.

This are my header search paths

EDIT: I think i found my error but i don't know why this happed. I cleaned up the header paths and removed everything except the 3 default paths and it works now. Can someone tell me why xcode created this paths instead of them i provided?

The problem was line 4.


问:
session.save() have some mistake with "unknown entity "
I'm new to hibernate and as I researched. When i want to start my JUnit, this mistake could be occur every time. I guess something wrong with my hbm.xml file. Maybe I am missing something because I'm still new to hibernate.

This is my hbm.xml file.

```<code>    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.test.UserEntity" table="user" schema="" catalog="junwa">
        <id name="id" column="id"/>
        <property name="username" column="username"/>
        <property name="gender" column="gender"/>
        <property name="birthday" column="birthday"/>
        <property name="addres" column="addres"/>
    </class>
</hibernate-mapping>
</code>```

And this is my UserEntity.java file

```<code>package com.test;
import javax.persistence.*;
import java.sql.Timestamp;

@Entity
@Table(name = "user", schema = "", catalog = "junwa")
public class UserEntity {
    private int id;
    private String username;
    private String gender;
    private Timestamp birthday;
    private String addres;

    @Id
    @Column(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "username")
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Basic
    @Column(name = "gender")
    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Basic
    @Column(name = "birthday")
    public Timestamp getBirthday() {
        return birthday;
    }

    public void setBirthday(Timestamp birthday) {
        this.birthday = birthday;
    }

    @Basic
    @Column(name = "addres")
    public String getAddres() {
        return addres;
    }

    public void setAddres(String addres) {
        this.addres = addres;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        UserEntity that = (UserEntity) o;

        if (id != that.id) return false;
        if (username != null ? !username.equals(that.username) : that.username != null) return false;
        if (gender != null ? !gender.equals(that.gender) : that.gender != null) return false;
        if (birthday != null ? !birthday.equals(that.birthday) : that.birthday != null) return false;
        if (addres != null ? !addres.equals(that.addres) : that.addres != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (username != null ? username.hashCode() : 0);
        result = 31 * result + (gender != null ? gender.hashCode() : 0);
        result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
        result = 31 * result + (addres != null ? addres.hashCode() : 0);
        return result;
    }
}
</code>```

This is my test file.

```<code>/**
 * Created by junwa on 2017/4/2.
 */
import com.test.Students;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;

public class StudentsTest {
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;
    @Before
    public void init(){
        // create a deploy object
        Configuration config = new Configuration().configure();
        // create a service licenced object
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        // create a  session factory object
        sessionFactory = config.buildSessionFactory(serviceRegistry);
        // create a sessoin object
        session = sessionFactory.openSession();
        // start transaction
        transaction = session.beginTransaction();

    }

    @After
    public void destroy(){
        // commit transaction
        transaction.commit();
        // close session
        session.close();
        // close session factory
        sessionFactory.close();

    }

    @Test
    public void testSaveStudents(){
        // create a object
        Students s = new Students(1,"junwa","male",new Date(),"Anhui");
        // save object to mysql database
        session.save(s);
        session.flush();

    }
}
</code>```

This my output
enter image description here

答: You can't use hbm.xml and annotation at the same time.</p>

Body:
I'm new to hibernate and as I researched. When i want to start my JUnit, this mistake could be occur every time. I guess something wrong with my hbm.xml file. Maybe I am missing something because I'm still new to hibernate.

This is my hbm.xml file.

    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.test.UserEntity" table="user" schema="" catalog="junwa">
        <id name="id" column="id"/>
        <property name="username" column="username"/>
        <property name="gender" column="gender"/>
        <property name="birthday" column="birthday"/>
        <property name="addres" column="addres"/>
    </class>
</hibernate-mapping>

And this is my UserEntity.java file

package com.test;
import javax.persistence.*;
import java.sql.Timestamp;

@Entity
@Table(name = "user", schema = "", catalog = "junwa")
public class UserEntity {
    private int id;
    private String username;
    private String gender;
    private Timestamp birthday;
    private String addres;

    @Id
    @Column(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "username")
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Basic
    @Column(name = "gender")
    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Basic
    @Column(name = "birthday")
    public Timestamp getBirthday() {
        return birthday;
    }

    public void setBirthday(Timestamp birthday) {
        this.birthday = birthday;
    }

    @Basic
    @Column(name = "addres")
    public String getAddres() {
        return addres;
    }

    public void setAddres(String addres) {
        this.addres = addres;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        UserEntity that = (UserEntity) o;

        if (id != that.id) return false;
        if (username != null ? !username.equals(that.username) : that.username != null) return false;
        if (gender != null ? !gender.equals(that.gender) : that.gender != null) return false;
        if (birthday != null ? !birthday.equals(that.birthday) : that.birthday != null) return false;
        if (addres != null ? !addres.equals(that.addres) : that.addres != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (username != null ? username.hashCode() : 0);
        result = 31 * result + (gender != null ? gender.hashCode() : 0);
        result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
        result = 31 * result + (addres != null ? addres.hashCode() : 0);
        return result;
    }
}

This is my test file.

/**
 * Created by junwa on 2017/4/2.
 */
import com.test.Students;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;

public class StudentsTest {
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;
    @Before
    public void init(){
        // create a deploy object
        Configuration config = new Configuration().configure();
        // create a service licenced object
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        // create a  session factory object
        sessionFactory = config.buildSessionFactory(serviceRegistry);
        // create a sessoin object
        session = sessionFactory.openSession();
        // start transaction
        transaction = session.beginTransaction();

    }

    @After
    public void destroy(){
        // commit transaction
        transaction.commit();
        // close session
        session.close();
        // close session factory
        sessionFactory.close();

    }

    @Test
    public void testSaveStudents(){
        // create a object
        Students s = new Students(1,"junwa","male",new Date(),"Anhui");
        // save object to mysql database
        session.save(s);
        session.flush();

    }
}

This my output
enter image description here


问:
How to rotate a PDF page so that *Box is set (and it doesn't just use rot=90)
Our site written in php receives PDF files from customers.  After processing, the next step is code from a vendor.  That code requires that each page is 8.5x11" in portrait.  The code also requires that the page have data like this (output from pdfinfo):

```<code>Page    1 size: 612 x 792 pts (letter)
Page    1 rot:  0
Page    1 MediaBox:     0.00     0.00   612.00   792.00
Page    1 CropBox:      0.00     0.00   612.00   792.00
Page    1 BleedBox:     0.00     0.00   612.00   792.00
Page    1 TrimBox:      0.00     0.00   612.00   792.00
Page    1 ArtBox:       0.00     0.00   612.00   792.00
</code>```

Sometimes customers give us PDFs with one or more pages in portrait.  We have code that uses FPDI to rewrite the file, rotating the pages that need it by 90 degrees:

```<code>$pdf->AddPage('L', array(215.9, 279.4), 90);
</code>```

The problem is that is just sets rot=90 and the resulting file has this (output from pdfinfo):

```<code>Page    3 size: 792 x 612 pts (letter)
Page    3 rot:  90
Page    3 MediaBox:     0.00     0.00   792.00   612.00
Page    3 CropBox:      0.00     0.00   792.00   612.00
Page    3 BleedBox:     0.00     0.00   792.00   612.00
Page    3 TrimBox:      0.00     0.00   792.00   612.00
Page    3 ArtBox:       0.00     0.00   792.00   612.00
</code>```

Our next step code does not recognize the rot=90 and sees this as a landscape page.

What can I use to change the page characteristics to be like the first set of data (the portrait image)?  In our environment ghostscript is available.   pdftk can be used (with more difficulty).

ADDED
I started with Patrick's pdfrw but ultimately shifted to staying with just FPDF.  One odd thing that I noticed: I lost the rotation fix for most files rotated to be only letter, portrait using FPDF and pdfrw when I concatenated to something else using ghostscript.  Solution: I ran the "fix rotation" code again after concatenating any files with gs.

答: You can rotate the imported page with FPDF by simply using the Rotate() function from this script before using useTemplate(). There's no need to switch to another language.</p>

Body:
Our site written in php receives PDF files from customers.  After processing, the next step is code from a vendor.  That code requires that each page is 8.5x11" in portrait.  The code also requires that the page have data like this (output from pdfinfo):

Page    1 size: 612 x 792 pts (letter)
Page    1 rot:  0
Page    1 MediaBox:     0.00     0.00   612.00   792.00
Page    1 CropBox:      0.00     0.00   612.00   792.00
Page    1 BleedBox:     0.00     0.00   612.00   792.00
Page    1 TrimBox:      0.00     0.00   612.00   792.00
Page    1 ArtBox:       0.00     0.00   612.00   792.00

Sometimes customers give us PDFs with one or more pages in portrait.  We have code that uses FPDI to rewrite the file, rotating the pages that need it by 90 degrees:

$pdf->AddPage('L', array(215.9, 279.4), 90);

The problem is that is just sets rot=90 and the resulting file has this (output from pdfinfo):

Page    3 size: 792 x 612 pts (letter)
Page    3 rot:  90
Page    3 MediaBox:     0.00     0.00   792.00   612.00
Page    3 CropBox:      0.00     0.00   792.00   612.00
Page    3 BleedBox:     0.00     0.00   792.00   612.00
Page    3 TrimBox:      0.00     0.00   792.00   612.00
Page    3 ArtBox:       0.00     0.00   792.00   612.00

Our next step code does not recognize the rot=90 and sees this as a landscape page.

What can I use to change the page characteristics to be like the first set of data (the portrait image)?  In our environment ghostscript is available.   pdftk can be used (with more difficulty).

ADDED
I started with Patrick's pdfrw but ultimately shifted to staying with just FPDF.  One odd thing that I noticed: I lost the rotation fix for most files rotated to be only letter, portrait using FPDF and pdfrw when I concatenated to something else using ghostscript.  Solution: I ran the "fix rotation" code again after concatenating any files with gs.


问:
while writing XML with stax parser if exception occurs in my own method then how to store or access previous data
In example below when we enter into writeOneMoreElement() method and Exception occurs then how to access previous data that we write on XML. Here we loose every entry if exception occurs on writeOneMoreElement() method. </p>

```<code>public class xmlSample {
  public static void main(String[] args) {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {

        XMLStreamWriter writer1 = factory.createXMLStreamWriter(new FileWriter("E:\\sampleXML.xml"));
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        XMLOutputFactory xmlOutputFactory = new WstxOutputFactory();
        XMLStreamWriter2 xtw = (XMLStreamWriter2) new WstxOutputFactory()
                .createXMLStreamWriter(byteArrayOutputStream, "UTF-8");

        xtw.writeStartDocument("UTF-8", "1.1");
        xtw.setPrefix("itm", "http://adt.cmn.xmlns.commons.platform.actiance.com/core/1.0");

        xtw.writeStartElement("document");
        xtw.writeStartElement("data1");
        xtw.writeCharacters("Sagar");
        xtw.writeEndElement();

        XMLStreamWriter2 writer2 = writeOneMoreElement(xtw);

        writer2.writeStartElement("data2");
        writer2.writeCharacters("Shubham");
        writer2.writeEndElement();

        writeOneMoreElement(writer2);

        writer2.writeEndDocument();
        writer2.close();
        xtw.flush();
        xtw.close();

        System.out.println("XML :" + new String(byteArrayOutputStream.toByteArray()));

    } catch (XMLStreamException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private static XMLStreamWriter2 writeOneMoreElement(XMLStreamWriter2 writer2)
        throws XMLStreamException, IOException {

    try {
        writer2.writeStartElement("ABC");
        writer2.writeStartElement("data2");
        writer2.writeAttribute("name2", "value2");
        writer2.writeAttribute("otherAttribute", "true");
        writer2.writeEndElement();

        writer2.writeStartElement("data3");
        writer2.writeAttribute("name3", "value3");
        writer2.writeAttribute("otherAttribute", "true");
        writer2.writeEndElement();

        writer2.writeEndElement();

        writer2.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return writer2;
 }
}
</code>```

答:
One of the rules of Exceptions is that whichever line throws an Exception, all lines after that will not be executed until you reach the catch and finally blocks. So this line System.out.println("XML :" + new String(byteArrayOutputStream.toByteArray())); is never executed, but the values are still available in byteArrayOutputStream before the program ends.

One possible solution is to run the same println() method in the catch block again. Like so:

```<code>public static void main(String[] args) {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    //Initializing the ByteArrayOutputStream outside the try block, so that it is still available after that scope.
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {

        XMLStreamWriter writer1 = factory.createXMLStreamWriter(new FileWriter("E:\\sampleXML.xml"));
        //ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        XMLOutputFactory xmlOutputFactory = new WstxOutputFactory();
        XMLStreamWriter2 xtw = (XMLStreamWriter2) new WstxOutputFactory()
                .createXMLStreamWriter(byteArrayOutputStream, "UTF-8");

        xtw.writeStartDocument("UTF-8", "1.1");
        xtw.setPrefix("itm", "http://adt.cmn.xmlns.commons.platform.actiance.com/core/1.0");

        xtw.writeStartElement("document");
        xtw.writeStartElement("data1");
        xtw.writeCharacters("Sagar");
        xtw.writeEndElement();

        XMLStreamWriter2 writer2 = writeOneMoreElement(xtw);

        writer2.writeStartElement("data2");
        writer2.writeCharacters("Shubham");
        writer2.writeEndElement();

        //Exception thrown here
        writeOneMoreElement(writer2);

        //Unexecuted code from here onwards
        writer2.writeEndDocument();
        writer2.close();
        xtw.flush();
        xtw.close();

        System.out.println("XML :" + new String(byteArrayOutputStream.toByteArray()));

    } catch (XMLStreamException e) {
        e.printStackTrace();
        /*Proof of concept. This line will print out all the values inserted into the ByteArrayOutputStream up to
        the point where the Exception was thrown.*/
        System.out.println("XML :" + new String(byteArrayOutputStream.toByteArray()));
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private static XMLStreamWriter2 writeOneMoreElement(XMLStreamWriter2 writer2)
        throws XMLStreamException/*, IOException*/ {
    //By the way, why does this method throw IOException? It's unnecessary, and you can remove it.
    try {
        writer2.writeStartElement("ABC");
        writer2.writeStartElement("data2");
        writer2.writeAttribute("name2", "value2");
        writer2.writeAttribute("otherAttribute", "true");
        writer2.writeEndElement();

        writer2.writeStartElement("data3");
        writer2.writeAttribute("name3", "value3");
        writer2.writeAttribute("otherAttribute", "true");
        writer2.writeEndElement();

        writer2.writeEndElement();

        writer2.flush();
        //I'm throwing an Exception here on purpose to trigger the catch block.
        throw new XMLStreamException();
    }
    catch (Exception e) {
        e.printStackTrace();
        // I'm rethrowing the Exception on purpose.
        throw e;
    }
    //This line won't work for now, but you can change it back.
    //return writer2;
 }
</code>```

Run the program, and you will get the expected XMLStreamException as well the incomplete data.

XML :<?xml version='1.1' encoding='UTF-8'?><document><data1>Sagar</data1><ABC><data2 name2="value2" otherAttribute="true" /><data3 name3="value3" otherAttribute="true" /></ABC>

Body:
In example below when we enter into writeOneMoreElement() method and Exception occurs then how to access previous data that we write on XML. Here we loose every entry if exception occurs on writeOneMoreElement() method.

public class xmlSample {
  public static void main(String[] args) {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {

        XMLStreamWriter writer1 = factory.createXMLStreamWriter(new FileWriter("E:\\sampleXML.xml"));
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        XMLOutputFactory xmlOutputFactory = new WstxOutputFactory();
        XMLStreamWriter2 xtw = (XMLStreamWriter2) new WstxOutputFactory()
                .createXMLStreamWriter(byteArrayOutputStream, "UTF-8");

        xtw.writeStartDocument("UTF-8", "1.1");
        xtw.setPrefix("itm", "http://adt.cmn.xmlns.commons.platform.actiance.com/core/1.0");

        xtw.writeStartElement("document");
        xtw.writeStartElement("data1");
        xtw.writeCharacters("Sagar");
        xtw.writeEndElement();

        XMLStreamWriter2 writer2 = writeOneMoreElement(xtw);

        writer2.writeStartElement("data2");
        writer2.writeCharacters("Shubham");
        writer2.writeEndElement();

        writeOneMoreElement(writer2);

        writer2.writeEndDocument();
        writer2.close();
        xtw.flush();
        xtw.close();

        System.out.println("XML :" + new String(byteArrayOutputStream.toByteArray()));

    } catch (XMLStreamException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private static XMLStreamWriter2 writeOneMoreElement(XMLStreamWriter2 writer2)
        throws XMLStreamException, IOException {

    try {
        writer2.writeStartElement("ABC");
        writer2.writeStartElement("data2");
        writer2.writeAttribute("name2", "value2");
        writer2.writeAttribute("otherAttribute", "true");
        writer2.writeEndElement();

        writer2.writeStartElement("data3");
        writer2.writeAttribute("name3", "value3");
        writer2.writeAttribute("otherAttribute", "true");
        writer2.writeEndElement();

        writer2.writeEndElement();

        writer2.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return writer2;
 }
}

Body:
One of the rules of Exceptions is that whichever line throws an Exception, all lines after that will not be executed until you reach the catch and finally blocks. So this line System.out.println("XML :" + new String(byteArrayOutputStream.toByteArray())); is never executed, but the values are still available in byteArrayOutputStream before the program ends.

One possible solution is to run the same println() method in the catch block again. Like so:

public static void main(String[] args) {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    //Initializing the ByteArrayOutputStream outside the try block, so that it is still available after that scope.
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {

        XMLStreamWriter writer1 = factory.createXMLStreamWriter(new FileWriter("E:\\sampleXML.xml"));
        //ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        XMLOutputFactory xmlOutputFactory = new WstxOutputFactory();
        XMLStreamWriter2 xtw = (XMLStreamWriter2) new WstxOutputFactory()
                .createXMLStreamWriter(byteArrayOutputStream, "UTF-8");

        xtw.writeStartDocument("UTF-8", "1.1");
        xtw.setPrefix("itm", "http://adt.cmn.xmlns.commons.platform.actiance.com/core/1.0");

        xtw.writeStartElement("document");
        xtw.writeStartElement("data1");
        xtw.writeCharacters("Sagar");
        xtw.writeEndElement();

        XMLStreamWriter2 writer2 = writeOneMoreElement(xtw);

        writer2.writeStartElement("data2");
        writer2.writeCharacters("Shubham");
        writer2.writeEndElement();

        //Exception thrown here
        writeOneMoreElement(writer2);

        //Unexecuted code from here onwards
        writer2.writeEndDocument();
        writer2.close();
        xtw.flush();
        xtw.close();

        System.out.println("XML :" + new String(byteArrayOutputStream.toByteArray()));

    } catch (XMLStreamException e) {
        e.printStackTrace();
        /*Proof of concept. This line will print out all the values inserted into the ByteArrayOutputStream up to
        the point where the Exception was thrown.*/
        System.out.println("XML :" + new String(byteArrayOutputStream.toByteArray()));
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private static XMLStreamWriter2 writeOneMoreElement(XMLStreamWriter2 writer2)
        throws XMLStreamException/*, IOException*/ {
    //By the way, why does this method throw IOException? It's unnecessary, and you can remove it.
    try {
        writer2.writeStartElement("ABC");
        writer2.writeStartElement("data2");
        writer2.writeAttribute("name2", "value2");
        writer2.writeAttribute("otherAttribute", "true");
        writer2.writeEndElement();

        writer2.writeStartElement("data3");
        writer2.writeAttribute("name3", "value3");
        writer2.writeAttribute("otherAttribute", "true");
        writer2.writeEndElement();

        writer2.writeEndElement();

        writer2.flush();
        //I'm throwing an Exception here on purpose to trigger the catch block.
        throw new XMLStreamException();
    }
    catch (Exception e) {
        e.printStackTrace();
        // I'm rethrowing the Exception on purpose.
        throw e;
    }
    //This line won't work for now, but you can change it back.
    //return writer2;
 }

Run the program, and you will get the expected XMLStreamException as well the incomplete data.

XML :<?xml version='1.1' encoding='UTF-8'?><document><data1>Sagar</data1><ABC><data2 name2="value2" otherAttribute="true" /><data3 name3="value3" otherAttribute="true" /></ABC>


问:
I am not able to get data from model in codeigniter
Model

//returns an array having different arrays inside it with keys id ,name and thumbnail taken from the database

```<code>function m_get_thumbnails($category){
    $this->db->select('id,name,thumbnail');
    $this->db->where('category',$category);
    $query=$this->db->get('food');
    if($query->num_rows()>0)
    {
        $count =0;
        $arr = array();
        foreach ($query->result() as $row)
        {

            $arr[$count++] = array(
                'id'=>$row->id,
                'name'=>$row->name,
                'thumbnail'=>$row->thumbnail
                );
        }
        return $arr;
    }
}
</code>```

function in controller

After that i place the result in an array and pass the array to my view.

```<code>function index_food()
{
    $data['cafe'] =  $this->mlocus->m_get_thumbnails('cafe');
    $this->load->view('food.php',$data);
}
</code>```

View

```<code><script>alert(<?php $cafe[1]; ?>);</script>
//this alert is coming blank.......
</code>```

答:
Controller:

```<code>function index_food()
{
   $data['cafe'] =  $this->mlocus->m_get_thumbnails('cafe');
   $this->load->view('food',$data);
}
</code>```

In Model

```<code>function m_get_thumbnails($category)
{
    $this->db->select('id,name,thumbnail');
    $this->db->where('category',$category);
    $query=$this->db->get('food');
    $result = $query->result_array();
    return $result;
}
</code>```

In your View

```<code><table>
<tr>
  <td>ID</td>
  <td>Name</td>
  <td>Thumbnail</td>
</tr>
<?php
if(!empty($cafe)) {
foreach($cafe as $c){
?>
<tr>
  <td> <?php echo $c['id']?> </td>
  <td> <?php echo $c['name']?> </td>
  <td><img src="<?php echo $c['thumbnail']?>" /></td>
</tr>
<?php } } else { ?>
<tr><td colspan="3">No record found.</td></tr>
<?php } ?>
</table>
</code>```

Body:
Model

//returns an array having different arrays inside it with keys id ,name and thumbnail taken from the database

function m_get_thumbnails($category){
    $this->db->select('id,name,thumbnail');
    $this->db->where('category',$category);
    $query=$this->db->get('food');
    if($query->num_rows()>0)
    {
        $count =0;
        $arr = array();
        foreach ($query->result() as $row)
        {

            $arr[$count++] = array(
                'id'=>$row->id,
                'name'=>$row->name,
                'thumbnail'=>$row->thumbnail
                );
        }
        return $arr;
    }
}

function in controller

After that i place the result in an array and pass the array to my view.

function index_food()
{
    $data['cafe'] =  $this->mlocus->m_get_thumbnails('cafe');
    $this->load->view('food.php',$data);
}

View

//this alert is coming blank.......

Body:
Controller:

function index_food()
{
   $data['cafe'] =  $this->mlocus->m_get_thumbnails('cafe');
   $this->load->view('food',$data);
}

In Model

function m_get_thumbnails($category)
{
    $this->db->select('id,name,thumbnail');
    $this->db->where('category',$category);
    $query=$this->db->get('food');
    $result = $query->result_array();
    return $result;
}

In your View

<table>
<tr>
  <td>ID</td>
  <td>Name</td>
  <td>Thumbnail</td>
</tr>
<?php
if(!empty($cafe)) {
foreach($cafe as $c){
?>
<tr>
  <td> <?php echo $c['id']?> </td>
  <td> <?php echo $c['name']?> </td>
  <td><img src="<?php echo $c['thumbnail']?>" /></td>
</tr>
<?php } } else { ?>
<tr><td colspan="3">No record found.</td></tr>
<?php } ?>
</table>


问:
how to create serializer for an enum field in django rest framework
i am writing an API in python django rest framework and i am stuck at creating a serializer field for an ENUM, how can i create a serializer field for an ENUM field.
my model code is:

```<code>class Queue(models.Model):
    class Meta:
        db_table = 'queues'

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
    name = models.CharField(max_length=45)
    type = EnumChoiceField(QueueTypes, default=QueueTypes.pending)
    date = models.DateTimeField(auto_now=True)
</code>```

and i am writing a serializer for this model.

```<code>class QueueSerializer(serializers.ModelSerializer):
    class Meta:
        model = Queue
        fields = ('__all__')

    id = serializers.CharField(read_only=True)
    name = serializers.CharField(max_length=45, required=True)
    type=?????# what am i supposed to do here?
    date = serializers.DateTimeField(read_only=True)
</code>```

答:
After doing a lot of searches on google i finally found the answer to the serializing issue with the EnumchoiceField the following changes did the job.

my Model.py:

```<code>from enumchoicefield import ChoiceEnum, EnumChoiceField

class QueueTypes(ChoiceEnum):
    appointment = "appointment"
    wait = "wait"
    process = "process"
    pending = "pending"

class Queue(models.Model):
    class Meta:
       db_table = 'queues'

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
    name = models.CharField(max_length=45)
    type = EnumChoiceField(enum_class=QueueTypes , default=QueueTypes.process)
    date = models.DateTimeField(auto_now=True)
    fk_department = models.ForeignKey(Department, related_name='department',null=True, on_delete=models.CASCADE)
</code>```

my Serialize.py:

```<code>from enumchoicefield import ChoiceEnum, EnumChoiceField

class QueueSerializer(serializers.ModelSerializer):
    class Meta:
        model = Queue
        fields = ('__all__')

    id = serializers.UUIDField(read_only=True)
    name = serializers.CharField(max_length=45, required=True)
    type = EnumChoiceField(enum_class=QueueTypes)
    date = serializers.DateTimeField(read_only=True)
</code>```

Body:
i am writing an API in python django rest framework and i am stuck at creating a serializer field for an ENUM, how can i create a serializer field for an ENUM field.
my model code is:

class Queue(models.Model):
    class Meta:
        db_table = 'queues'

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
    name = models.CharField(max_length=45)
    type = EnumChoiceField(QueueTypes, default=QueueTypes.pending)
    date = models.DateTimeField(auto_now=True)

and i am writing a serializer for this model.

class QueueSerializer(serializers.ModelSerializer):
    class Meta:
        model = Queue
        fields = ('__all__')

    id = serializers.CharField(read_only=True)
    name = serializers.CharField(max_length=45, required=True)
    type=?????# what am i supposed to do here?
    date = serializers.DateTimeField(read_only=True)

Body:
After doing a lot of searches on google i finally found the answer to the serializing issue with the EnumchoiceField the following changes did the job.

my Model.py:

from enumchoicefield import ChoiceEnum, EnumChoiceField

class QueueTypes(ChoiceEnum):
    appointment = "appointment"
    wait = "wait"
    process = "process"
    pending = "pending"

class Queue(models.Model):
    class Meta:
       db_table = 'queues'

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
    name = models.CharField(max_length=45)
    type = EnumChoiceField(enum_class=QueueTypes , default=QueueTypes.process)
    date = models.DateTimeField(auto_now=True)
    fk_department = models.ForeignKey(Department, related_name='department',null=True, on_delete=models.CASCADE)

my Serialize.py:

from enumchoicefield import ChoiceEnum, EnumChoiceField

class QueueSerializer(serializers.ModelSerializer):
    class Meta:
        model = Queue
        fields = ('__all__')

    id = serializers.UUIDField(read_only=True)
    name = serializers.CharField(max_length=45, required=True)
    type = EnumChoiceField(enum_class=QueueTypes)
    date = serializers.DateTimeField(read_only=True)


问:
How can I best lay out these components in Swing?
What would be the best approach / LayoutManager for a JPanel that needed to display the components shown in the image?
(Note that the fields should resize horizontally when the size of the window is changed, but not the labels).

I'm currently trying (and struggling) to do it with a GridBagLayout.  Is this the correct approach or is there a better way?  Should I be trying to divide + conquer the seperate sections maybe?

Any thoughts or advice would be gratefully appreciated.  :-)

http://img261.imageshack.us/img261/2091/layouthb6.png

PS If you read this and there's no image, please bear with me whilst I fix it!

答:
GridBagLayout, of course.

If the form is just this, then you done need more than one JPanel. (If you have buttons, you probably need one more, depending on where/how they are)

Field 0 - 4 and 9 will have gridwidth set to 4, others the default (1, but you need not set it to 1)

The 'spaces' between groups of fields can be achieved via insets.

(For this layout, at least) I would not suggest third party layout managers. GridBagLayout is not complex. It just takes (a li'l bit of) time to get used to it.

Visual Editor + Eclipse can do these for you easily. (I am not very comfortable with Netbeans and its swing development. Tried it, but never fell in love. Maybe, I am too much addicted to Eclipse)

OwnerDisplayName: cagcowboy

LastEditorDisplayName: John Topley

OwnerDisplayName: Nivas


问:
Directly accessing nested dictionary values in Objective-C
Is there a way to directly access an inner-array of an an outer array in Objective-C?  For example, a call to an external data source returns the following object:

```<code>{
bio = "this is the profile.bio data";
"first_name" = John;
"last_name" = Doe;
location =     {
    name = "Any Town, Any State";
};
metadata =    {
    pictures =    {
        picture = "https://picture.mysite.com/picture.jpeg";
    }
}
}
</code>```

I want to be able to access, for example, the location.name or the metadata.pictures.picture data.  Dot notation, however, does not seem to work.  For example:

```<code>_gfbLocation = [result objectForKey:@"location.name"];
_gfbPicture = [result objectForKey:@"metadata.pictures.picture"];
</code>```

The only way I have been able to access this data is by first setting the contents of the inner arrays to objects.  Thoughts?

答:
```<code>gfbPicture = [[[result objectForKey:@"metadata"] objectForKey:@"pictures"] objectForKey:@"picture"];
</code>```

Body:
Is there a way to directly access an inner-array of an an outer array in Objective-C?  For example, a call to an external data source returns the following object:

{
bio = "this is the profile.bio data";
"first_name" = John;
"last_name" = Doe;
location =     {
    name = "Any Town, Any State";
};
metadata =    {
    pictures =    {
        picture = "https://picture.mysite.com/picture.jpeg";
    }
}
}

I want to be able to access, for example, the location.name or the metadata.pictures.picture data.  Dot notation, however, does not seem to work.  For example:

_gfbLocation = [result objectForKey:@"location.name"];
_gfbPicture = [result objectForKey:@"metadata.pictures.picture"];

The only way I have been able to access this data is by first setting the contents of the inner arrays to objects.  Thoughts?


问:
Make an object accessible outside a function in R
I have a function  called "p". In this function, there is an object called "marginal" which I need to make recognizable and retrievable outside this function when called. Right now, when I call the object "marginal" outside the function, I get an wrror message that:

object 'marginal' not found

Question: How can I make "marginal" recognizable outside the function?

```<code>p <- function(t, N1, N2=NULL, delta) {

    efN = ifelse(is.null(N2), N1, N1*N2/(N1+N2))
    df  = ifelse(is.null(N2), N1 - 1, N1 + N2 - 2)

    prior <- function(delta) dnorm(delta, 0, 1)
    likelihood <- function(delta) dt(t, df, delta*sqrt(efN) )

    marginal <- integrate(function(x) prior(x)*likelihood(x), -Inf, Inf)[[1]]

    post <- function(x) prior(x)*likelihood(x) / marginal

    return(post(delta))

    list(marginal) ## What to use instead of list to object "marginal" recognizable
                    # outside the function?
 }

 marginal
</code>```

object 'marginal' not found

答:
To access multiple values from inside a function, make sure all the values you want to access get returned by putting them in a list. Then return the list, assign the results of the function call, and access the values you want:

```<code>multi_return = function() {
    x = 3
    y = 4
    res = list(x = x, y = y)
    return(res)
}

results = multi_return()
y = results$y
y
# Output:
## [1] 4
</code>```

This kind of approach is generally preferred over having functions make global assignments, as then calling a function can have unpredictable side effects.

Body:
I have a function  called "p". In this function, there is an object called "marginal" which I need to make recognizable and retrievable outside this function when called. Right now, when I call the object "marginal" outside the function, I get an wrror message that:

object 'marginal' not found

Question: How can I make "marginal" recognizable outside the function?

p <- function(t, N1, N2=NULL, delta) {

    efN = ifelse(is.null(N2), N1, N1*N2/(N1+N2))
    df  = ifelse(is.null(N2), N1 - 1, N1 + N2 - 2)

    prior <- function(delta) dnorm(delta, 0, 1)
    likelihood <- function(delta) dt(t, df, delta*sqrt(efN) )

    marginal <- integrate(function(x) prior(x)*likelihood(x), -Inf, Inf)[[1]]

    post <- function(x) prior(x)*likelihood(x) / marginal

    return(post(delta))

    list(marginal) ## What to use instead of list to object "marginal" recognizable
                    # outside the function?
 }

 marginal

object 'marginal' not found

Body:
To access multiple values from inside a function, make sure all the values you want to access get returned by putting them in a list. Then return the list, assign the results of the function call, and access the values you want:

multi_return = function() {
    x = 3
    y = 4
    res = list(x = x, y = y)
    return(res)
}

results = multi_return()
y = results$y
y
# Output:
## [1] 4

This kind of approach is generally preferred over having functions make global assignments, as then calling a function can have unpredictable side effects.


问:
C terminology: header vs. signature
the word header as far as I know is usually in reference to a header file while the word signature is in reference to the arguments and return type of the function. For example, in my experience this would be called a signature:

```<code>int ptInPoly(Point q, Point p[], int n)
</code>```

My professor is calling this a header in my assignments. I have found this confusing and would like to know if this different use terminology is common or something that only he does. Thanks

Here is some more context around the use of the term header:

"Your program must have a function with header: int ptInPoly(Point q, Point p[], int n) that determines if point q is in the polygon given in p"

答:
The correct term is function declaration. When the parameter types are spelled out explicitly, as in your case int ptInPoly(Point q, Point p[], int n); it can also be called a function prototype. (Non-prototype format is considered very bad practice and rarely used nowadays.) A function prototype is a function declaration.

Function declaration and function prototype are formal terms used by the C standard.

The meaning of header is indeed a header file, with .h as extension. The C standard uses the term header to describe header files.

So your professor is using the wrong terminology.

ContentLicense: CC BY-SA 4.0

Title: C terminology: header vs. signature

Body:
the word header as far as I know is usually in reference to a header file while the word signature is in reference to the arguments and return type of the function. For example, in my experience this would be called a signature:

int ptInPoly(Point q, Point p[], int n)

My professor is calling this a header in my assignments. I have found this confusing and would like to know if this different use terminology is common or something that only he does. Thanks

Here is some more context around the use of the term header:

"Your program must have a function with header: int ptInPoly(Point q, Point p[], int n) that determines if point q is in the polygon given in p"


问:
RedirectToRoute Not Working
Environment:

I am working in WebAPI. I implemented all CRUD methods.

Scenario:

In PUT method, i am excluding some properties like 'CreatedDate' to be updated. My Code like below;

```<code>[Route("")]
public async Task<IHttpActionResult> Put(MyModel myModel)
{
    //Parsing to Business Entity
    var item = TheFactory.Parse(myModel);
    bool result = await _myBL.UpdateLab(item);
    if (!result)
    {
        return BadRequest("Error in Save");
    }
    //Converting to view model and return
    return Ok(TheFactory.Create(item));
}
</code>```

Problem:

Here i am not getting CreatedDate from user. So it always min date.In DAL i specified this field as not modified so it always have the created data value. In return i am converting to viewmodel from the model user given. So CreatedDate is min date not original.

MySolution:

So to avoid that get the updated object from the Database again and return to the user. I already have get method to return the object by passing id. So i just changed my PUT method like below;

```<code>[Route("")]
public async Task<IHttpActionResult> Put(MyModel myModel)
{
    //Parsing to Business Entity
    var item = TheFactory.Parse(myModel);
    bool result = await _myBL.UpdateLab(item);
    if (!result)
    {
        return BadRequest("Error in Save");
    }
    //Redirect to getbyid method
    return RedirectToRoute("GetById", new { id = item.Id });
}
</code>```

Issue:

Here i thought i can reuse the method get method so it also returns ok(object). But after changed to this I got the following exception;

The requested resource does not support http method 'PUT'.

The response status is 405. Please help me to find the routecause

答:
You need to just call GetById(item.id)

```<code>[Route("")]
public async Task<IHttpActionResult> Put(MyModel myModel)
{
    //Parsing to Business Entity
    var item = TheFactory.Parse(myModel);
    bool result = await _myBL.UpdateLab(item);
    if (!result)
    {
        return BadRequest("Error in Save");
    }
    return GetById(item.Id);
}
</code>```

Title: RedirectToRoute Not Working

Body:
Environment:

I am working in WebAPI. I implemented all CRUD methods.

Scenario:

In PUT method, i am excluding some properties like 'CreatedDate' to be updated. My Code like below;

[Route("")]
public async Task<IHttpActionResult> Put(MyModel myModel)
{
    //Parsing to Business Entity
    var item = TheFactory.Parse(myModel);
    bool result = await _myBL.UpdateLab(item);
    if (!result)
    {
        return BadRequest("Error in Save");
    }
    //Converting to view model and return
    return Ok(TheFactory.Create(item));
}

Problem:

Here i am not getting CreatedDate from user. So it always min date.In DAL i specified this field as not modified so it always have the created data value. In return i am converting to viewmodel from the model user given. So CreatedDate is min date not original.

MySolution:

So to avoid that get the updated object from the Database again and return to the user. I already have get method to return the object by passing id. So i just changed my PUT method like below;

[Route("")]
public async Task<IHttpActionResult> Put(MyModel myModel)
{
    //Parsing to Business Entity
    var item = TheFactory.Parse(myModel);
    bool result = await _myBL.UpdateLab(item);
    if (!result)
    {
        return BadRequest("Error in Save");
    }
    //Redirect to getbyid method
    return RedirectToRoute("GetById", new { id = item.Id });
}

Issue:

Here i thought i can reuse the method get method so it also returns ok(object). But after changed to this I got the following exception;

The requested resource does not support http method 'PUT'.

The response status is 405. Please help me to find the routecause

Body:
You need to just call GetById(item.id)

[Route("")]
public async Task<IHttpActionResult> Put(MyModel myModel)
{
    //Parsing to Business Entity
    var item = TheFactory.Parse(myModel);
    bool result = await _myBL.UpdateLab(item);
    if (!result)
    {
        return BadRequest("Error in Save");
    }
    return GetById(item.Id);
}


问:
Unable to import 'Rx' to my Angular 2 application
I am pretty new at Angular2. I am trying to learn it using a dummy app.

I have recently gone through a tutorial on RxJS and got a basic hold on Observables (or atleast I assume so). Based on that, I have an idea of returning a list of users from my array in service as a stream. I intent to use interval for it and display a kind  of lazy loading effect on screen.

My intention is something like:

```<code>getUsers() {
        return Rx.Observable.from(this.users); //want to add interval too on this
    }
</code>```

However, I am stuck at importing 'Rx' in to my service. Using 'Rx' without import obviously gives me error. The rest imports for Observables and operator works fine.

I went to node_modules and found there is a rx and a rxjs module too. But somehow using any of these below commands, I can't get rid of my error on Rx.

```<code>import 'rxjs/Rx';
import  Rx from 'rxjs/Rx';
import { Rx} from 'rx/Rx';
import { Rx} from 'rx';
</code>```

I went through few links on SO those say Rx is no longer bundled with Angular. However, I am working with the latest angular official seed and I do see rx and rxjs packages. I have a 5.0.1 version mentioned in package.json. Am I assuming something wrong here ??

Please let me know How does one work with creating custom observables using Rx in Angular 2.

Note: I have no issues working Observable return by Http service, just want to create a Observable from scratch using Array

答:
If you want to add interval ,

```<code>import { Observable } from 'rxjs/Observable';

return Observable.from(this.users);
</code>```

You can do this , this way.

Body:
I am pretty new at Angular2. I am trying to learn it using a dummy app.

I have recently gone through a tutorial on RxJS and got a basic hold on Observables (or atleast I assume so). Based on that, I have an idea of returning a list of users from my array in service as a stream. I intent to use interval for it and display a kind  of lazy loading effect on screen.

My intention is something like:

getUsers() {
        return Rx.Observable.from(this.users); //want to add interval too on this
    }

However, I am stuck at importing 'Rx' in to my service. Using 'Rx' without import obviously gives me error. The rest imports for Observables and operator works fine.

I went to node_modules and found there is a rx and a rxjs module too. But somehow using any of these below commands, I can't get rid of my error on Rx.

import 'rxjs/Rx';
import  Rx from 'rxjs/Rx';
import { Rx} from 'rx/Rx';
import { Rx} from 'rx';

I went through few links on SO those say Rx is no longer bundled with Angular. However, I am working with the latest angular official seed and I do see rx and rxjs packages. I have a 5.0.1 version mentioned in package.json. Am I assuming something wrong here ??

Please let me know How does one work with creating custom observables using Rx in Angular 2.

Note: I have no issues working Observable return by Http service, just want to create a Observable from scratch using Array

Body:
If you want to add interval ,

import { Observable } from 'rxjs/Observable';

return Observable.from(this.users);

You can do this , this way.


问:
How to Search an array of object in Swift 3
I am trying to search an array of objects that I'm pulling from a Firebase database. The data is loading fine but when I try to search nothing shows. I've only been learning iOS/Swift development for about 6 weeks now. Below is code I have.

The app was crashing as soon as I clicked into the search bar.
I managed to get the search code to stop crashing but I'm getting no returns in my search. Is this because I'm search a Firebase database? I'm loading the firebase data into an array so it should be searchable right?

```<code>import UIKit
import Firebase

class ServicesTableViewController: UITableViewController, UISearchResultsUpdating {

    var services = [Service]()
    var filteredSearch = [Service]()

    var searchController: UISearchController!
    var resultsController = UITableViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Turn this back on to cache data
        FIRDatabase.database().persistenceEnabled = true

        fetchServices()

        self.resultsController.tableView.dataSource = self
        self.resultsController.tableView.delegate = self

        self.searchController = UISearchController(searchResultsController: self.resultsController)
        self.tableView.tableHeaderView = searchController.searchBar
        self.searchController.searchResultsUpdater = self

        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search services..."
        searchController.searchBar.tintColor = UIColor.white
        searchController.searchBar.barTintColor = UIColor(red: 164.0/255.0, green: 45.0/255.0, blue: 9.0/255.0, alpha: 1.0)

        navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
    }

    // MARK: - Search Controller

    func filterContent(for searchText: String) {
        filteredSearch = services.filter({ (service) -> Bool in
            if let name = service.name {
                let isMatch = name.localizedCaseInsensitiveContains(searchText)
                return isMatch
            }

            return false
        })
    }

    func updateSearchResults(for searchController: UISearchController) {
        if let searchText = searchController.searchBar.text {
            filterContent(for: searchText)
            tableView.reloadData()
        }
    }

    // MARK: Database connection and data fetch

    func fetchServices () {

        FIRDatabase.database().reference().child("services").observe(.childAdded, with: { (snapshot) in

            print(snapshot)

            if let dictionary = snapshot.value as? [String: AnyObject] {

                let service = Service()
                service.setValuesForKeys(dictionary)

                self.services.append(service)

                self.tableView.reloadData()

            }

        })

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searchController.isActive {
            return filteredSearch.count
        } else {
            return services.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ServicesTableViewCell

        // Check to see if the user is searching or not
        let service = (searchController.isActive) ? filteredSearch[indexPath.row] : services[indexPath.row]

//        let service = services[indexPath.row]
        cell.programLabel.text = service.name
        cell.programLabel.font = UIFont(name: "Avenir-Medium", size: 18.0)
        cell.programLabel.textColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
        cell.branchLabel.text = service.branch
        cell.branchLabel.font = UIFont(name: "Avenir-Medium", size: 14.0)
        cell.branchLabel.textColor = UIColor(red: 90.0/255.0, green: 86.0/255.0, blue: 92.0/255.0, alpha: 1.0)
        cell.servicesLabel.text = service.shortDesc
        cell.servicesLabel.font = UIFont(name: "Avenir-Light", size: 14.0)
        cell.servicesLabel.textColor = UIColor(red: 164.0/255.0, green: 45.0/255.0, blue: 9.0/255.0, alpha: 1.0)
        cell.thumbnailImageView.image = UIImage(named: service.imageName!)

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showServicesDetail" {
            if let indexPath = tableView.indexPathForSelectedRow {
                let destinationController = segue.destination as! ServicesDetailViewController
                destinationController.services = services[indexPath.row]
            }
        }
    }

}
</code>```

Here's my current storyboard. just two views and a nav controller,
enter image description here

答:
I assumed that you want to search by name:

```<code>filteredSearch = services.filter { (service: Service) -> Bool in

    if let name = service.name,
        let searchText = self.searchController.searchBar.text?.lowercased() {
        return name.lowercased().contains(searchText)
    } else {
        return false
    }
}
</code>```

Also, let change filteredSearch to an array of Service:

```<code>var filteredSearch = [Service]()
</code>```

Body:
I am trying to search an array of objects that I'm pulling from a Firebase database. The data is loading fine but when I try to search nothing shows. I've only been learning iOS/Swift development for about 6 weeks now. Below is code I have.

The app was crashing as soon as I clicked into the search bar.
I managed to get the search code to stop crashing but I'm getting no returns in my search. Is this because I'm search a Firebase database? I'm loading the firebase data into an array so it should be searchable right?

import UIKit
import Firebase

class ServicesTableViewController: UITableViewController, UISearchResultsUpdating {

    var services = [Service]()
    var filteredSearch = [Service]()

    var searchController: UISearchController!
    var resultsController = UITableViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Turn this back on to cache data
        FIRDatabase.database().persistenceEnabled = true

        fetchServices()

        self.resultsController.tableView.dataSource = self
        self.resultsController.tableView.delegate = self

        self.searchController = UISearchController(searchResultsController: self.resultsController)
        self.tableView.tableHeaderView = searchController.searchBar
        self.searchController.searchResultsUpdater = self

        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search services..."
        searchController.searchBar.tintColor = UIColor.white
        searchController.searchBar.barTintColor = UIColor(red: 164.0/255.0, green: 45.0/255.0, blue: 9.0/255.0, alpha: 1.0)

        navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
    }

    // MARK: - Search Controller

    func filterContent(for searchText: String) {
        filteredSearch = services.filter({ (service) -> Bool in
            if let name = service.name {
                let isMatch = name.localizedCaseInsensitiveContains(searchText)
                return isMatch
            }

            return false
        })
    }

    func updateSearchResults(for searchController: UISearchController) {
        if let searchText = searchController.searchBar.text {
            filterContent(for: searchText)
            tableView.reloadData()
        }
    }

    // MARK: Database connection and data fetch

    func fetchServices () {

        FIRDatabase.database().reference().child("services").observe(.childAdded, with: { (snapshot) in

            print(snapshot)

            if let dictionary = snapshot.value as? [String: AnyObject] {

                let service = Service()
                service.setValuesForKeys(dictionary)

                self.services.append(service)

                self.tableView.reloadData()

            }

        })

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searchController.isActive {
            return filteredSearch.count
        } else {
            return services.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ServicesTableViewCell

        // Check to see if the user is searching or not
        let service = (searchController.isActive) ? filteredSearch[indexPath.row] : services[indexPath.row]

//        let service = services[indexPath.row]
        cell.programLabel.text = service.name
        cell.programLabel.font = UIFont(name: "Avenir-Medium", size: 18.0)
        cell.programLabel.textColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
        cell.branchLabel.text = service.branch
        cell.branchLabel.font = UIFont(name: "Avenir-Medium", size: 14.0)
        cell.branchLabel.textColor = UIColor(red: 90.0/255.0, green: 86.0/255.0, blue: 92.0/255.0, alpha: 1.0)
        cell.servicesLabel.text = service.shortDesc
        cell.servicesLabel.font = UIFont(name: "Avenir-Light", size: 14.0)
        cell.servicesLabel.textColor = UIColor(red: 164.0/255.0, green: 45.0/255.0, blue: 9.0/255.0, alpha: 1.0)
        cell.thumbnailImageView.image = UIImage(named: service.imageName!)

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showServicesDetail" {
            if let indexPath = tableView.indexPathForSelectedRow {
                let destinationController = segue.destination as! ServicesDetailViewController
                destinationController.services = services[indexPath.row]
            }
        }
    }

}

Here's my current storyboard. just two views and a nav controller,
enter image description here

Body:
I assumed that you want to search by name:

filteredSearch = services.filter { (service: Service) -> Bool in

    if let name = service.name,
        let searchText = self.searchController.searchBar.text?.lowercased() {
        return name.lowercased().contains(searchText)
    } else {
        return false
    }
}

Also, let change filteredSearch to an array of Service:

var filteredSearch = [Service]()


问:
IPv6 App Store Rejection
Our update has been rejected twice today for ipv6 network connectivity issues. Our networking code has not changed between the previous release and this current release.

The app only makes https network requests to api.metooapp.io, which is correctly configured for ipv6 [0] and runs behind route53 on AWS. There are no hard-coded IP addresses in the code.

I am unable to reproduce this issue, even after following the steps to create an ipv6 network at [1] which is the link that was provided in the rejection notice. It looks like I'm not the only one experiencing this issue, either [2].

答:
This is 2nd time i have encountered this issue after 6 month. Previously it was in Objective-C project using AFNetworking and i used this solution and it worked on one go. Now same happened with Alamofire. Guys this solution is worked for me 2 times and i found this question is coming first in google so i am posting the answer.

Search in the workspace for AF_INET and change it to AF_INET6 anywhere you found. I think it must be inside the AFNetworking library or Alamofire library if you are using it. Its in the NetworkReachabilityManager class.

I found this answer from the below source.

https://stackoverflow.com/a/38196337/4030971

EDIT: - 24th June -

This helped me so many times but there is a strange solution to this problem also. In our recent project we have applied this solution but still apple rejected the application. Then we made a video which was showing that the app is running fine with connected to a NAT64 network created on a Mac from wifi sharing option. We appealed for review with the video and they approved the application. So if you are done with all your options, try this one too.

Title: IPv6 App Store Rejection


问:
What Perl module to use?
How do I choose between two (or more) Perl modules, when each of them has the method(s) I need?</p>

答:
Well, it really depends on what you are going after, for instance:

if you are going after just that one particular function, then use the slimmer/smaller module.

Check also the date when it was added, and use the newer one, as it will adhere to more current standards.

Some modules also don't support OOP whilst other do, so that might be another factor to consider.

Also consider dependencies of each module, because there is no reason to install a bloated module for one or two functions.

Check authors notes for any bugs, etc.

And you can do research on your own, consult google and perlmonks because the chances are that someone already pondered dilemma between choosing those particular modules.

Title: What Perl module to use?


问:
ion-searchbar as a tab component IONIC 2
My Ionic 2 App is having 5 tabs:-

```<code><ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="ios-blicon-home" ></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Categories" tabIcon="ios-blicon-category"></ion-tab>
  <ion-tab tabTitle="Search" tabIcon="ios-blicon-search" (click)="startsearch()"></ion-tab>
  <ion-tab [root]="tab4Root" tabTitle="Bookmark" tabIcon="ios-blicon-bookmark"></ion-tab>
  <ion-tab [root]="tab5Root" tabTitle="Me" tabIcon="ios-blicon-me"></ion-tab>
</ion-tabs>
</code>```

I have four component and one is a search tab where I want to pop a seachbar (ion-searchbar) whenever clicked and it can trigger a function on submit.

I am not sure how to do this, please suggest me.

Thank you..!!

答:
I think you need to create another page with searchbar - say SearchPage component.

And you have to give the [root] for that tab to that component.

```<code><ion-tab [root]="tab3Root" tabTitle="Search" tabIcon="ios-blicon-search"></ion-tab>
</code>```

In your tabs.ts - tab3Root = "SearchPage".

Now, whatever searching functionality you need, will be in this SearchPage component. Refer this for how to implement searchbar.

Body:
My Ionic 2 App is having 5 tabs:-

<ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="ios-blicon-home" ></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Categories" tabIcon="ios-blicon-category"></ion-tab>
  <ion-tab tabTitle="Search" tabIcon="ios-blicon-search" (click)="startsearch()"></ion-tab>
  <ion-tab [root]="tab4Root" tabTitle="Bookmark" tabIcon="ios-blicon-bookmark"></ion-tab>
  <ion-tab [root]="tab5Root" tabTitle="Me" tabIcon="ios-blicon-me"></ion-tab>
</ion-tabs>

I have four component and one is a search tab where I want to pop a seachbar (ion-searchbar) whenever clicked and it can trigger a function on submit.

I am not sure how to do this, please suggest me.

Thank you..!!

Body:
I think you need to create another page with searchbar - say SearchPage component.

And you have to give the [root] for that tab to that component.

<ion-tab [root]="tab3Root" tabTitle="Search" tabIcon="ios-blicon-search"></ion-tab>

In your tabs.ts - tab3Root = "SearchPage".

Now, whatever searching functionality you need, will be in this SearchPage component. Refer this for how to implement searchbar.


问:
Carrierwave resize existing image
I have a rails 3 application which uses the CarrierWave gem. Until now, I have uploaded my pictures in 48*48 and 100*100 but now I would like to store them in 200*200.

Is there a way to resize my already uploaded images ?

答:
If you want to crop/resize every pictures:

```<code>MyModel.where.not(picture: nil).each{|v| v.picture.resize_to_fill(150, 150)}
</code>```

/!\ It will replace the original picture.

Title: Carrierwave resize existing image

Body:
If you want to crop/resize every pictures:

MyModel.where.not(picture: nil).each{|v| v.picture.resize_to_fill(150, 150)}

/!\ It will replace the original picture.


问:
Understanding Bayes' Theorem
I'm working on an implementation of a Naive Bayes Classifier. Programming Collective Intelligence introduces this subject by describing Bayes Theorem as:

```<code>Pr(A | B) = Pr(B | A) x Pr(A)/Pr(B)
</code>```

As well as a specific example relevant to document classification:

```<code>Pr(Category | Document) = Pr(Document | Category) x Pr(Category) / Pr(Document)
</code>```

I was hoping someone could explain to me the notation used here, what do Pr(A | B) and Pr(A) mean? It looks like some sort of function but then what does the pipe ("|") mean, etc?

答:
The pipe is used to represent conditional probability.
Pr(A | B) = Probability of A given B

Example:
Let's say you are not feeling well and you surf the web for the symptoms. And the internet tells you that if you have these symptoms then you have XYZ disease.

In this case:
Pr(A | B) is what you are trying to find out, which is:
The probability of you having XYZ GIVEN THAT you have certain symptoms.

Pr(A) is the probability of having the disease XYZ

Pr(B) is the probability of having those symptoms

Pr(B | A) is what you find out from the internet, which is:
The probability of having the symptoms GIVEN THAT you have the disease.

Title: Understanding Bayes' Theorem

Body:
I'm working on an implementation of a Naive Bayes Classifier. Programming Collective Intelligence introduces this subject by describing Bayes Theorem as:

Pr(A | B) = Pr(B | A) x Pr(A)/Pr(B)

As well as a specific example relevant to document classification:

Pr(Category | Document) = Pr(Document | Category) x Pr(Category) / Pr(Document)

I was hoping someone could explain to me the notation used here, what do Pr(A | B) and Pr(A) mean? It looks like some sort of function but then what does the pipe ("|") mean, etc?


问:
Getting "This field is required" error even though I set null=True and blank=True
I have a Post model for users submitting posts. I've given the content field of Post an attribute of blank=True. But for some reason django tells me content is still required. form_post.errors prints this:

```<code><ul class="errorlist"><li>content<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
</code>```

Here's my code:

models

```<code>class Post(models.Model):
    ...
    user = models.ForeignKey(User, blank=True, null=True)
    title = models.TextField(max_length=76)
    content = models.TextField(null=True, blank=True)
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1')
</code>```

forms

```<code>class PostForm(forms.ModelForm):
    content = forms.CharField(widget=PagedownWidget)
    title = forms.TextInput(attrs={'placeholder': 'title'})

    class Meta:
        model = Post
        fields = [
            'title',
            'content',
            'category',
            'image',
            'id',
            'user'
        ]
</code>```

views

```<code>def post(request):
    allauth_login = LoginForm(request.POST or None)
    allauth_signup = SignupForm(request.POST or None)
    if request.user.is_authenticated():
        form_post = PostForm(request.POST or None, request.FILES or None)
        if form_post.is_valid():
            print('valid')
            instance = form_post.save(commit=False)
            instance.user = request.user

            category = form_post.cleaned_data['category']
            for a, b in CATEGORY_CHOICES:
                if a == category:
                    category = b
                    form_post.save()

            return HttpResponseRedirect('/%s' % category)
        else:
            print(form_post.errors)
            form_post = PostForm()

        context = {
            'allauth_login': allauth_login,
            'allauth_signup': allauth_signup,
            'form_post': form_post
        }

        return render(request, 'post.html', context)
    else:
        return HttpResponseRedirect("/accounts/signup/")
</code>```

html

```<code>...
<form method="post" action="" enctype="multipart/form-data">{% csrf_token %}
<div class="submitContainer">
    <div class="article_title_div">
     {{ form_post.title|add_class:"article_title" }}
     </div>
    <div>
    </div>
        {{ form_post.category }}
    </div>
    <div class="submitButton">
        <button class="submitArticleSubmit" type="submit">Post</button>
</div>
</form>
...
</code>```

Any idea why I'm getting this error?

答:
The reason for this, is because you're overriding the default model field. Both content and title.

Although, content can be nullable when stored in your database, it is required by your form (content = forms.CharField(widget=PagedownWidget)).

Change to content = forms.CharField(widget=PagedownWidget, required=False) to make it optional on form submission.

Body:
I have a Post model for users submitting posts. I've given the content field of Post an attribute of blank=True. But for some reason django tells me content is still required. form_post.errors prints this:

content

This field is required.

Here's my code:

models

class Post(models.Model):
    ...
    user = models.ForeignKey(User, blank=True, null=True)
    title = models.TextField(max_length=76)
    content = models.TextField(null=True, blank=True)
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1')

forms

class PostForm(forms.ModelForm):
    content = forms.CharField(widget=PagedownWidget)
    title = forms.TextInput(attrs={'placeholder': 'title'})

    class Meta:
        model = Post
        fields = [
            'title',
            'content',
            'category',
            'image',
            'id',
            'user'
        ]

views

def post(request):
    allauth_login = LoginForm(request.POST or None)
    allauth_signup = SignupForm(request.POST or None)
    if request.user.is_authenticated():
        form_post = PostForm(request.POST or None, request.FILES or None)
        if form_post.is_valid():
            print('valid')
            instance = form_post.save(commit=False)
            instance.user = request.user

            category = form_post.cleaned_data['category']
            for a, b in CATEGORY_CHOICES:
                if a == category:
                    category = b
                    form_post.save()

            return HttpResponseRedirect('/%s' % category)
        else:
            print(form_post.errors)
            form_post = PostForm()

        context = {
            'allauth_login': allauth_login,
            'allauth_signup': allauth_signup,
            'form_post': form_post
        }

        return render(request, 'post.html', context)
    else:
        return HttpResponseRedirect("/accounts/signup/")

html

...
<form method="post" action="" enctype="multipart/form-data">{% csrf_token %}

     {{ form_post.title|add_class:"article_title" }}

        {{ form_post.category }}

        <button class="submitArticleSubmit" type="submit">Post</button>

</form>
...

Any idea why I'm getting this error?


问:
Could not find handler chain file handler-chain.xml for class
I am able to invoke client application using run.bat file.
Please find below is run.bat file content.

lcp.bat file content

```<code> SET LCP=%LCP%;%*
</code>```

 run.bat file content

```<code>   @ECHO OFF
    SET LCP=.
    FOR /R lib %%i IN ("*.jar") DO CALL lcp.bat %%i
    echo "target/classes;%LCP%"
        echo
        echo "test validation..."
        java -cp "target\\classes;%LCP%" com.tfp.ipr.soap.Client  "https://webservice.ibancomplete.com/ibanws/services/IBANService?wsdl" validate "ME25525440003582070092"
        pause
</code>```

Invoking client application using bat file is working as expected. This bat file i am invoking from the windows command prompt.

Additional information This client application uses below jars.

```<code>commons-logging-1.1.1.jar
cxf-2.7.3.jar
httpasyncclient-4.0-beta3.jar
httpclient-4.2.1.jar
httpcore-4.2.2.jar
httpcore-nio-4.2.2.jar
neethi-3.0.2.jar
openws-1.4.2-1.jar
spring-aop-3.0.7.RELEASE.jar
spring-asm-3.0.7.RELEASE.jar
spring-beans-3.0.7.RELEASE.jar
spring-context-3.0.7.RELEASE.jar
spring-core-3.0.7.RELEASE.jar
169,749 spring-expression-3.0.7.RELEASE.jar
spring-jms-3.0.7.RELEASE.jar
spring-tx-3.0.7.RELEASE.jar
spring-web-3.0.7.RELEASE.jar
wsdl4j-1.6.2.jar
wss4j-1.6.9.jar
xmlschema-core-2.0.2.jar
xmlsec-1.5.2.jar
</code>```

Problem: what i did is , i bundled all contents of classes folder as single jar (IbanWs-Client.jar).  i have executed using below command. Please refer below screenshot and advise solution.

答: First solution : Move all the jars in jre lib directory and so that these jars will be loaded at the time jvm initialization. You can able to run the program.</p>

Body:
I am able to invoke client application using run.bat file.
Please find below is run.bat file content.

lcp.bat file content

 SET LCP=%LCP%;%*

 run.bat file content

   @ECHO OFF
    SET LCP=.
    FOR /R lib %%i IN ("*.jar") DO CALL lcp.bat %%i
    echo "target/classes;%LCP%"
        echo
        echo "test validation..."
        java -cp "target\\classes;%LCP%" com.tfp.ipr.soap.Client  "https://webservice.ibancomplete.com/ibanws/services/IBANService?wsdl" validate "ME25525440003582070092"
        pause

Invoking client application using bat file is working as expected. This bat file i am invoking from the windows command prompt.

Additional information This client application uses below jars.

commons-logging-1.1.1.jar
cxf-2.7.3.jar
httpasyncclient-4.0-beta3.jar
httpclient-4.2.1.jar
httpcore-4.2.2.jar
httpcore-nio-4.2.2.jar
neethi-3.0.2.jar
openws-1.4.2-1.jar
spring-aop-3.0.7.RELEASE.jar
spring-asm-3.0.7.RELEASE.jar
spring-beans-3.0.7.RELEASE.jar
spring-context-3.0.7.RELEASE.jar
spring-core-3.0.7.RELEASE.jar
169,749 spring-expression-3.0.7.RELEASE.jar
spring-jms-3.0.7.RELEASE.jar
spring-tx-3.0.7.RELEASE.jar
spring-web-3.0.7.RELEASE.jar
wsdl4j-1.6.2.jar
wss4j-1.6.9.jar
xmlschema-core-2.0.2.jar
xmlsec-1.5.2.jar

Problem: what i did is , i bundled all contents of classes folder as single jar (IbanWs-Client.jar).  i have executed using below command. Please refer below screenshot and advise solution.


问:
In bash, how to store a return value in a variable?
I know some very basic commands in Linux and am trying to write some scripts. I have written a function which evaluates the sum of last 2-digits in a 5-digit number. The function should concatenate this resultant sum in between the last 2-digits and return it. The reason I want to return this value is because I will be using this value in the other function.

Ex: if I have 12345, then my function will calculate 4+5 and return 495.

```<code>#!/bin/bash

set -x
echo "enter: "
        read input

function password_formula
{
        length=${#input}
        last_two=${input:length-2:length}
        first=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $2}'`
        second=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $1}'`
        let sum=$first+$second
        sum_len=${#sum}
        echo $second
        echo $sum

        if [ $sum -gt 9 ]
        then
               sum=${sum:1}
        fi

        value=$second$sum$first
        return $value
}
result=$(password_formula)
echo $result
</code>```

I am trying to echo and see the result but I am getting the output as shown below.

```<code>-bash-3.2$ ./file2.sh
+++ password_formula
+++ echo 'enter: '
+++ read input
12385
+++ length=8
+++ last_two=85
++++ echo 85
++++ sed -e 's/\(.\)/\1 /g'
++++ awk '{print $2}'
+++ first=5
++++ echo 85
++++ sed -e 's/\(.\)/\1 /g'
++++ awk '{print $1}'
+++ second=8
+++ let sum=5+8
+++ sum_len=2
+++ echo 5
+++ echo 8
+++ echo 13
+++ '[' 13 -gt 9 ']'
+++ sum=3
+++ value=835
+++ return 835
++ result='enter:
5
8
13'
++ echo enter: 5 8 13
enter: 5 8 13
</code>```

I also tried to print the result as:

```<code>password_formula
RESULT=$?
echo $RESULT
</code>```

But that is giving some unknown value:

```<code>++ RESULT=67
++ echo 67
67
</code>```

How can I properly store the correct value and print (to double check) on the screen?

答:
Use the special bash variable "$?" like so:</p>
```<code>function_output=$(my_function)
function_return_value=$?
</code>```

Body:
I know some very basic commands in Linux and am trying to write some scripts. I have written a function which evaluates the sum of last 2-digits in a 5-digit number. The function should concatenate this resultant sum in between the last 2-digits and return it. The reason I want to return this value is because I will be using this value in the other function.

Ex: if I have 12345, then my function will calculate 4+5 and return 495.

#!/bin/bash

set -x
echo "enter: "
        read input

function password_formula
{
        length=${#input}
        last_two=${input:length-2:length}
        first=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $2}'`
        second=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $1}'`
        let sum=$first+$second
        sum_len=${#sum}
        echo $second
        echo $sum

        if [ $sum -gt 9 ]
        then
               sum=${sum:1}
        fi

        value=$second$sum$first
        return $value
}
result=$(password_formula)
echo $result

I am trying to echo and see the result but I am getting the output as shown below.

-bash-3.2$ ./file2.sh
+++ password_formula
+++ echo 'enter: '
+++ read input
12385
+++ length=8
+++ last_two=85
++++ echo 85
++++ sed -e 's/\(.\)/\1 /g'
++++ awk '{print $2}'
+++ first=5
++++ echo 85
++++ sed -e 's/\(.\)/\1 /g'
++++ awk '{print $1}'
+++ second=8
+++ let sum=5+8
+++ sum_len=2
+++ echo 5
+++ echo 8
+++ echo 13
+++ '[' 13 -gt 9 ']'
+++ sum=3
+++ value=835
+++ return 835
++ result='enter:
5
8
13'
++ echo enter: 5 8 13
enter: 5 8 13

I also tried to print the result as:

password_formula
RESULT=$?
echo $RESULT

But that is giving some unknown value:

++ RESULT=67
++ echo 67
67

How can I properly store the correct value and print (to double check) on the screen?

Body:
Use the special bash variable "$?" like so:

function_output=$(my_function)
function_return_value=$?


问:
How to define begin() and end() for a template class backed by an array?
I have a class whose contain is a 1D double array, and I wish to provide the begin() and end() methods for the iterators without writing additional classes. However, I am not sure what the return type of begin() and end() would be. My intuition tells me that I can simply return a type of double *, since it is an address to a double array, but do I have to implement it through std::iterator to be compliant with the STL?</p>

```<code>template <size_t size>
double * ContainerClass<size>::end(){
    return std::end(mContainer);
}
</code>```

答:
Use std::array<double, size>, either instead of reinventing the wheel or internally to store your data.

If you really want to write your own version of std::array, keep an internal data pointer to a statically-allocated array, make your iterator type a T*, and make begin() and end() return pointers to the first element and one-past-the-end of the private member array, respectively.

Body:
I have a class whose contain is a 1D double array, and I wish to provide the begin() and end() methods for the iterators without writing additional classes. However, I am not sure what the return type of begin() and end() would be. My intuition tells me that I can simply return a type of double *, since it is an address to a double array, but do I have to implement it through std::iterator to be compliant with the STL?

template <size_t size>
double * ContainerClass<size>::end(){
    return std::end(mContainer);
}


问:
bash: /home/XXX/.rvm/scripts/rvm: No such file or directory
I just walk-through with the installation of Ruby on Rails on Ubuntu using RVM.

First I have logged in as the root user.

Then I started with the following commands.

\curl -sSL https://get.rvm.io | bash -s stable --rails

It has been installed without any error.

source ~/.rvm/scripts/rvm

When I run this command. It showing the error as bash: /home/XXX/.rvm/scripts/rvm: No such file or directory

I added the [[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" command in my .bashr file.

答: just create ~/.rvm/scripts/rvm directories, then try to install rvm but make sure you are not logged in as root.</p>


问:
PHP (7.1) inheritance issue
I have the following structure:

```<code>class AffiliateRepository extends GenericRepository implements IAffiliateRepository {

}

abstract class GenericRepository  {
    public function save(BaseModel $model) : int{
        $model->save();
        return $model->getId();
    }

}

interface IAffiliateRepository  {

    public function save(Affiliate $affiliate) : int;
}

public class Affiliate extends BaseModel{}

$affiliateRepository  = new AffiliateRepository();
$affiliateRepository->save(new Affiliate());
</code>```

I am expecting GenericRepository to take care on the save action.

but I'm getting the following error:

Declaration of App\Services\AffiliateRepository::save(App\Models\Affiliate $affiliate): int
should be compatible with
App\Services\GenericRepository::save(App\Models\BaseModel $model): int

Why is that? Affiliate inherits from BaseModel.

Whats the best way to overcome that and let GenericRepository handle the save function call.

thanks

答:
Look at methods:

```<code>// GenericRepository
public function save(BaseModel $model)

// IAffiliateRepository
public function save(Affiliate $affiliate) : int;
</code>```

Both classes have to expect the same type. If you implement IAffiliateRepository into GenericRepository class, it will be correct. You may also need to change variable names to be the same.

Title: PHP (7.1) inheritance issue

Body:
I have the following structure:

class AffiliateRepository extends GenericRepository implements IAffiliateRepository {

}

abstract class GenericRepository  {
    public function save(BaseModel $model) : int{
        $model->save();
        return $model->getId();
    }

}

interface IAffiliateRepository  {

    public function save(Affiliate $affiliate) : int;
}

public class Affiliate extends BaseModel{}

$affiliateRepository  = new AffiliateRepository();
$affiliateRepository->save(new Affiliate());

I am expecting GenericRepository to take care on the save action.

but I'm getting the following error:

Declaration of App\Services\AffiliateRepository::save(App\Models\Affiliate $affiliate): int
should be compatible with
App\Services\GenericRepository::save(App\Models\BaseModel $model): int

Why is that? Affiliate inherits from BaseModel.

Whats the best way to overcome that and let GenericRepository handle the save function call.

thanks

Body:
Look at methods:

// GenericRepository
public function save(BaseModel $model)

// IAffiliateRepository
public function save(Affiliate $affiliate) : int;

Both classes have to expect the same type. If you implement IAffiliateRepository into GenericRepository class, it will be correct. You may also need to change variable names to be the same.


问:
trimmingCharacters not work on iOS 10.3 Xcode8.3
Please help me, I use Xcode 8.3(swift 3.1), the function trimmingCharacters not work. My code as below:

```<code>    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if var searchStr = textField.text{
       let _searchStr = searchStr.trimmingCharacters(in: .whitespaces)
       print("After trimming:\(_searchStr)")
   }
}
</code>```

The input in textfield is 409 huỳnh and the print result is 409 huỳnh not as expected: 409huỳnh .

答:
From the documentation:

A new string made by removing from both ends of the receiver characters contained in set.

It does not remove characters within the string.

You can replace whitespaces – corresponding to the .whitespaces character set –  in the string with regular expression:

```<code>let _searchStr = searchStr.replacingOccurrences(of: "\\s", with: "", options: .regularExpression)
</code>```

Body:
Please help me, I use Xcode 8.3(swift 3.1), the function trimmingCharacters not work. My code as below:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if var searchStr = textField.text{
       let _searchStr = searchStr.trimmingCharacters(in: .whitespaces)
       print("After trimming:\(_searchStr)")
   }
}

The input in textfield is 409 huỳnh and the print result is 409 huỳnh not as expected: 409huỳnh .

Body:
From the documentation:

A new string made by removing from both ends of the receiver characters contained in set.

It does not remove characters within the string.

You can replace whitespaces – corresponding to the .whitespaces character set –  in the string with regular expression:

let _searchStr = searchStr.replacingOccurrences(of: "\\s", with: "", options: .regularExpression)