问:
Conversion Error setting value for 'null Converter' - Why do I need a Converter in JSF?
I have problems understanding how to use selection in JSF 2 with POJO/entity effectively. For example, I'm trying to select a Warehouse entity via the below dropdown:

```<code><h:selectOneMenu value="#{bean.selectedWarehouse}">
    <f:selectItem itemLabel="Choose one .." itemValue="#{null}" />
    <f:selectItems value="#{bean.availableWarehouses}" />
</h:selectOneMenu>
</code>```

And the below managed bean:

```<code>@Named
@ViewScoped
public class Bean {

    private Warehouse selectedWarehouse;
    private List<SelectItem> availableWarehouses;

    // ...

    @PostConstruct
    public void init() {
        // ...

        availableWarehouses = new ArrayList<>();

        for (Warehouse warehouse : warehouseService.listAll()) {
            availableWarehouses.add(new SelectItem(warehouse, warehouse.getName()));
        }
    }

    // ...
}
</code>```

Notice that I use the whole Warehouse entity as the value of SelectItem.

When I submit the form, this fails with the following faces message:

Conversion Error setting value 'com.example.Warehouse@cafebabe' for 'null Converter'.

I was hoping that JSF could just set the correct Warehouse object to my managed bean when I wrap it in a SelectItem. Wrapping my entity inside the SelectItem was meant to skip creating a Converter for my entity.

Do I really have to use a Converter whenever I want to make use of entities in my <h:selectOneMenu>? It should for JSF be possible to just extract the selected item from the list of available items. If I really have to use a converter, what is the practical way of doing it? So far I came up to this:

Create a Converter implementation for the entity.

Overriding the getAsString(). I think I don't need this since the label property of the SelectItem will be used to display the dropdown option label.

Overriding the getAsObject(). I think this will be used to return the correct SelectItem or entity depending on the type of the selected field defined in the managed bean.

The getAsObject() confuses me. What is the efficient way to do this? Having the string value, how do I get the associated entity object? Should I query the entity object from the service object based on the string value and return the entity? Or perhaps somehow I can access the list of the entities that form the selection items, loop them to find the correct entity, and return the entity?

What is the normal approach of this?

答:
Introduction

JSF generates HTML. HTML is in Java terms basically one large String. To represent Java objects in HTML, they have to be converted to String. Also, when a HTML form is submitted, the submitted values are treated as String in the HTTP request parameters. Under the covers, JSF extracts them from the HttpServletRequest#getParameter() which returns String.

To convert between a non-standard Java object (i.e. not a String, Number or Boolean for which EL has builtin conversions, or Date/LocalDate/ZonedDateTime for which JSF provides builtin <f:convertDateTime> tag), you really have to supply a custom Converter. The SelectItem has no special purpose at all. It's just a leftover from JSF 1.x when it wasn't possible to supply e.g. List<Warehouse> directly to <f:selectItems>. It has also no special treatment as to labels and conversion.

getAsString()

You need to implement getAsString() method in such way that the desired Java object is been represented in an unique String  representation which can be used as HTTP request parameter. Normally, the technical ID (the database primary key) is used here.

```<code>public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
    if (modelValue == null) {
        return ""; // Never return null here!
    }

    if (modelValue instanceof Warehouse) {
        return String.valueOf(((Warehouse) modelValue).getId());
    } else {
        throw new ConverterException(new FacesMessage(modelValue + " is not a valid Warehouse"));
    }
}
</code>```

Note that returning an empty string in case of a null/empty model value is significant and required by the javadoc:

Returns: a zero-length String if value is null, otherwise the result of the conversion

Otherwise the generated <option> will not have a value attribute and by default send the item label back into getAsObject(). See also Using a "Please select" f:selectItem with null/empty value inside a p:selectOneMenu.

getAsObject()

You need to implement getAsObject() in such way that exactly that String representation as returned by getAsString() can be converted back to exactly the same Java object specified as modelValue in getAsString().

```<code>public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
    if (submittedValue == null || submittedValue.isEmpty()) {
        return null;
    }

    try {
        return warehouseService.find(Long.valueOf(submittedValue));
    } catch (NumberFormatException e) {
        throw new ConverterException(new FacesMessage(submittedValue + " is not a valid Warehouse ID"), e);
    }
}
</code>```

In other words, you must be technically able to pass back the returned object as modelValue argument of getAsString() and then pass back the obtained string as submittedValue argument of getAsObject() in an infinite loop.

Usage

Finally just annotate the Converter with @FacesConverter to hook on the object type in question, JSF will then automatically take care of conversion when Warehouse type ever comes into the picture:

```<code>@FacesConverter(forClass=Warehouse.class)
</code>```

That was the "canonical" JSF approach. It's after all not very effective as it could indeed also just have grabbed the item from the <f:selectItems>. But the most important point of a Converter is that it returns an unique String representation, so that the Java object could be identified by a simple String suitable for passing around in HTTP and HTML.

Generic converter based on toString()

JSF utility library OmniFaces has a SelectItemsConverter which works based on toString() outcome of the entity. This way you do not need to fiddle with getAsObject() and expensive business/database operations anymore. For some concrete use examples, see also the showcase.

To use it, just register it as below:

```<code><h:selectOneMenu ... converter="omnifaces.SelectItemsConverter">
</code>```

And make sure that the toString() of your Warehouse entity returns an unique representation of the entity. You could for instance directly return the ID:

```<code>@Override
public String toString() {
    return String.valueOf(id);
}
</code>```

Or something more readable/reusable:

```<code>@Override
public String toString() {
    return "Warehouse[id=" + id + "]";
}
</code>```

See also:

How to populate options of h:selectOneMenu from database?

Generic JSF entity converter - so that you don't need to write a converter for every entity.

Using enums in JSF selectitems - enums needs to be treated a bit differently

How to inject @EJB, @PersistenceContext, @Inject, @Autowired, etc in @FacesConverter?

Unrelated to the problem, since JSF 2.0 it's not explicitly required anymore to have a List<SelectItem> as <f:selectItem> value. Just a List<Warehouse> would also suffice.

```<code><h:selectOneMenu value="#{bean.selectedWarehouse}">
    <f:selectItem itemLabel="Choose one .." itemValue="#{null}" />
    <f:selectItems value="#{bean.availableWarehouses}" var="warehouse"
        itemLabel="#{warehouse.name}" itemValue="#{warehouse}" />
</h:selectOneMenu>
</code>```

```<code>private Warehouse selectedWarehouse;
private List<Warehouse> availableWarehouses;
</code>```

Body:
I have problems understanding how to use selection in JSF 2 with POJO/entity effectively. For example, I'm trying to select a Warehouse entity via the below dropdown:

<h:selectOneMenu value="#{bean.selectedWarehouse}">
    <f:selectItem itemLabel="Choose one .." itemValue="#{null}" />
    <f:selectItems value="#{bean.availableWarehouses}" />
</h:selectOneMenu>

And the below managed bean:

@Named
@ViewScoped
public class Bean {

    private Warehouse selectedWarehouse;
    private List<SelectItem> availableWarehouses;

    // ...

    @PostConstruct
    public void init() {
        // ...

        availableWarehouses = new ArrayList<>();

        for (Warehouse warehouse : warehouseService.listAll()) {
            availableWarehouses.add(new SelectItem(warehouse, warehouse.getName()));
        }
    }

    // ...
}

Notice that I use the whole Warehouse entity as the value of SelectItem.

When I submit the form, this fails with the following faces message:

Conversion Error setting value 'com.example.Warehouse@cafebabe' for 'null Converter'.

I was hoping that JSF could just set the correct Warehouse object to my managed bean when I wrap it in a SelectItem. Wrapping my entity inside the SelectItem was meant to skip creating a Converter for my entity.

Do I really have to use a Converter whenever I want to make use of entities in my <h:selectOneMenu>? It should for JSF be possible to just extract the selected item from the list of available items. If I really have to use a converter, what is the practical way of doing it? So far I came up to this:

Create a Converter implementation for the entity.

Overriding the getAsString(). I think I don't need this since the label property of the SelectItem will be used to display the dropdown option label.

Overriding the getAsObject(). I think this will be used to return the correct SelectItem or entity depending on the type of the selected field defined in the managed bean.

The getAsObject() confuses me. What is the efficient way to do this? Having the string value, how do I get the associated entity object? Should I query the entity object from the service object based on the string value and return the entity? Or perhaps somehow I can access the list of the entities that form the selection items, loop them to find the correct entity, and return the entity?

What is the normal approach of this?

Body:
Introduction

JSF generates HTML. HTML is in Java terms basically one large String. To represent Java objects in HTML, they have to be converted to String. Also, when a HTML form is submitted, the submitted values are treated as String in the HTTP request parameters. Under the covers, JSF extracts them from the HttpServletRequest#getParameter() which returns String.

To convert between a non-standard Java object (i.e. not a String, Number or Boolean for which EL has builtin conversions, or Date/LocalDate/ZonedDateTime for which JSF provides builtin <f:convertDateTime> tag), you really have to supply a custom Converter. The SelectItem has no special purpose at all. It's just a leftover from JSF 1.x when it wasn't possible to supply e.g. List<Warehouse> directly to <f:selectItems>. It has also no special treatment as to labels and conversion.

getAsString()

You need to implement getAsString() method in such way that the desired Java object is been represented in an unique String  representation which can be used as HTTP request parameter. Normally, the technical ID (the database primary key) is used here.

public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
    if (modelValue == null) {
        return ""; // Never return null here!
    }

    if (modelValue instanceof Warehouse) {
        return String.valueOf(((Warehouse) modelValue).getId());
    } else {
        throw new ConverterException(new FacesMessage(modelValue + " is not a valid Warehouse"));
    }
}

Note that returning an empty string in case of a null/empty model value is significant and required by the javadoc:

Returns: a zero-length String if value is null, otherwise the result of the conversion

Otherwise the generated <option> will not have a value attribute and by default send the item label back into getAsObject(). See also Using a "Please select" f:selectItem with null/empty value inside a p:selectOneMenu.

getAsObject()

You need to implement getAsObject() in such way that exactly that String representation as returned by getAsString() can be converted back to exactly the same Java object specified as modelValue in getAsString().

public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
    if (submittedValue == null || submittedValue.isEmpty()) {
        return null;
    }

    try {
        return warehouseService.find(Long.valueOf(submittedValue));
    } catch (NumberFormatException e) {
        throw new ConverterException(new FacesMessage(submittedValue + " is not a valid Warehouse ID"), e);
    }
}

In other words, you must be technically able to pass back the returned object as modelValue argument of getAsString() and then pass back the obtained string as submittedValue argument of getAsObject() in an infinite loop.

Usage

Finally just annotate the Converter with @FacesConverter to hook on the object type in question, JSF will then automatically take care of conversion when Warehouse type ever comes into the picture:

@FacesConverter(forClass=Warehouse.class)

That was the "canonical" JSF approach. It's after all not very effective as it could indeed also just have grabbed the item from the <f:selectItems>. But the most important point of a Converter is that it returns an unique String representation, so that the Java object could be identified by a simple String suitable for passing around in HTTP and HTML.

Generic converter based on toString()

JSF utility library OmniFaces has a SelectItemsConverter which works based on toString() outcome of the entity. This way you do not need to fiddle with getAsObject() and expensive business/database operations anymore. For some concrete use examples, see also the showcase.

To use it, just register it as below:

<h:selectOneMenu ... converter="omnifaces.SelectItemsConverter">

And make sure that the toString() of your Warehouse entity returns an unique representation of the entity. You could for instance directly return the ID:

@Override
public String toString() {
    return String.valueOf(id);
}

Or something more readable/reusable:

@Override
public String toString() {
    return "Warehouse[id=" + id + "]";
}

See also:

How to populate options of h:selectOneMenu from database?

Generic JSF entity converter - so that you don't need to write a converter for every entity.

Using enums in JSF selectitems - enums needs to be treated a bit differently

How to inject @EJB, @PersistenceContext, @Inject, @Autowired, etc in @FacesConverter?

Unrelated to the problem, since JSF 2.0 it's not explicitly required anymore to have a List<SelectItem> as <f:selectItem> value. Just a List<Warehouse> would also suffice.

<h:selectOneMenu value="#{bean.selectedWarehouse}">
    <f:selectItem itemLabel="Choose one .." itemValue="#{null}" />
    <f:selectItems value="#{bean.availableWarehouses}" var="warehouse"
        itemLabel="#{warehouse.name}" itemValue="#{warehouse}" />
</h:selectOneMenu>

private Warehouse selectedWarehouse;
private List<Warehouse> availableWarehouses;


来源: stackexchange

问:
How to add Images to a dynamically created JTable
I have a JTable which I create dynamically from List<String> objects. I do this probably completely wrong but it works. The only thing I can't get to work is adding Images to some of the cells.

All it does is, it adds the ImageIcon Object name as String to the cells. See my code below.

```<code>private static Image doneImage = getIconImage("doneImage");
private static Image notDoneImage = getIconImage("notDoneImage");

private DefaultTableModel model = new DefaultTableModel(){
    @Override
    public Class<?> getColumnClass(int column){
        if ((column & 1) != 0 ){
            return ImageIcon.class;
        }else{
            return String.class;
        }
    }
};

initTables();

JTable table = new JTable();
table.setModel(model);

private void initTables(){

    model.addRow(new Object[]{});

    int rowsToAdd = 0;
    int rowCount = 0;
    int columnId = 0;

    for(HouseObject aHouse : houses){
        for(RoomObject aRoom : aHouse.getRooms()){

            model.addColumn(null);
            model.addColumn(aRoom.getId());
            model.setValueAt(aRoom.getId(), 0, columnId);

            if (rowCount < aRoom.getEvents().size()){
                rowsToAdd = aRoom.getEvents().size() - model.getRowCount();
                for(int i = 0; i <= rowsToAdd; i++){
                    model.addRow(new Object[]{});
                }
                rowCount = model.getRowCount();
            }

            for(int i = 0; i < aRoom.getEvents().size(); i++){
                model.setValueAt(aRoom.getEvents().get(i).getId(), i+1, columnId);

                for(String houseDone : housesDone){
                    if(aRoom.getEvents().get(i).getId().contains(houseDone)){
                        model.setValueAt(doneImage , i+1, columnId+1); // this does not work
                    }else{
                        model.setValueAt(notDoneImage, i+1, columnId+1);
                    }
                }
            }

            columnId = columnId+2;
        }
    }
}
</code>```

答:
You need to install renderer for your table

Here is the renderer:

```<code>public class IconTableCellRenderer extends DefaultTableCellRenderer {

    @Override
    protected void setValue(Object value) {
        if (value instanceof Icon) {
            setText(null);
            setIcon((Icon) value);
        } else {
            super.setValue(value);
        }
    }
}
</code>```

And so you must install it:

```<code>JTable table = new JTable();
table.setModel(model);
table.setDefaultRenderer(ImageIcon.class, new IconTableCellRenderer());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a JTable which I create dynamically from List<String> objects. I do this probably completely wrong but it works. The only thing I can't get to work is adding Images to some of the cells.

All it does is, it adds the ImageIcon Object name as String to the cells. See my code below.

private static Image doneImage = getIconImage("doneImage");
private static Image notDoneImage = getIconImage("notDoneImage");

private DefaultTableModel model = new DefaultTableModel(){
    @Override
    public Class<?> getColumnClass(int column){
        if ((column & 1) != 0 ){
            return ImageIcon.class;
        }else{
            return String.class;
        }
    }
};

initTables();

JTable table = new JTable();
table.setModel(model);

private void initTables(){

    model.addRow(new Object[]{});

    int rowsToAdd = 0;
    int rowCount = 0;
    int columnId = 0;

    for(HouseObject aHouse : houses){
        for(RoomObject aRoom : aHouse.getRooms()){

            model.addColumn(null);
            model.addColumn(aRoom.getId());
            model.setValueAt(aRoom.getId(), 0, columnId);

            if (rowCount < aRoom.getEvents().size()){
                rowsToAdd = aRoom.getEvents().size() - model.getRowCount();
                for(int i = 0; i <= rowsToAdd; i++){
                    model.addRow(new Object[]{});
                }
                rowCount = model.getRowCount();
            }

            for(int i = 0; i < aRoom.getEvents().size(); i++){
                model.setValueAt(aRoom.getEvents().get(i).getId(), i+1, columnId);

                for(String houseDone : housesDone){
                    if(aRoom.getEvents().get(i).getId().contains(houseDone)){
                        model.setValueAt(doneImage , i+1, columnId+1); // this does not work
                    }else{
                        model.setValueAt(notDoneImage, i+1, columnId+1);
                    }
                }
            }

            columnId = columnId+2;
        }
    }
}

Body:
You need to install renderer for your table

Here is the renderer:

public class IconTableCellRenderer extends DefaultTableCellRenderer {

    @Override
    protected void setValue(Object value) {
        if (value instanceof Icon) {
            setText(null);
            setIcon((Icon) value);
        } else {
            super.setValue(value);
        }
    }
}

And so you must install it:

JTable table = new JTable();
table.setModel(model);
table.setDefaultRenderer(ImageIcon.class, new IconTableCellRenderer());


问:
Apache Drill "limit 0" query while using Spring datasource
TL;DR

I have a Spring Boot application that makes use of parquet files stored on the file system. To access them we are using Apache Drill.

Since I have multiple users that might access them, I've set up a connection pool in Spring.

When I'm using the connection pool, Drill somehow executes a "limit 0" query before executing my actual query, and this affect performances. The same "limit 0" query is NOT executed when I run my queries through a simple Statement obtained from direct Connection.

This seems to be related to the fact that Spring JdbcTemplate makes use of PreparedStatements instead of simple Statements.

Is there a way to get rid of those "limit 0" queries?

-- Details --

The connection pool in the Spring configuration class looks like this:

```<code>@Bean
@ConfigurationProperties(prefix = "datasource.parquet")
@Qualifier("parquetDataSource")
public DataSource parquetDataSource() {
    return DataSourceBuilder.create().build();
}
</code>```

And the corresponding properties in the development profile YML file are:

```<code>datasource:
  parquet:
    url: jdbc:drill:drillbit=localhost:31010
    jdbcUrl: jdbc:drill:drillbit=localhost:31010
    jndiName: jdbc/app_parquet
    driverClassName: org.apache.drill.jdbc.Driver
    maximumPoolSize: 5
    initialSize: 1
    maxIdle: 10
    maxActive: 20
    validation-query: SELECT 1 FROM sys.version
    test-on-borrow: true
</code>```

When I execute a query using the JdbcTemplate created with the mentioned Drill DataSource, 3 different queries might be executed:

the validation query SELECT 1 FROM sys.version;

a "limit 0" query that looks like SELECT * FROM (<my actual query>) LIMIT 0;

my actual query.

Here's the execution code (parquetJdbcTemplate is an instance of a class that extends org.springframework.jdbc.core.JdbcTemplate):

```<code>parquetJdbcTemplate.query(sqlQuery, namedParameters,
            resultSet -> {
                MyResultSet result = new MyResultSet();
                while (resultSet.next()) {
                    // populate the "result" object
                }
                return result;
            });
</code>```

Here's a screenshot from the Profile page of my Drill monitor:

The bottom query is the "limit 0" one, then in the middle you have the validation query and on top (even if the query is not shown) the actual query that returns the data I want.

As you can see, the "limit 0" query takes more than 1/3 of the entire execution time to run. The validation query is fine, since the execution time is negligible and it's needed to check the connection.

The fact is, when I execute the same query using a Connection through the Drill driver (thus, with no pool), I only see my actual query in the UI monitor:

```<code>public void executeQuery(String myQuery) {
    Class.forName("org.apache.drill.jdbc.Driver");
    Driver.load();
    Connection connection = DriverManager.getConnection("jdbc:drill:drillbit=localhost:31010");
    Statement st = connection.createStatement();
    ResultSet resultSet = st.executeQuery(myQuery);
    while (resultSet.next()) {
        // do stuff
    }
}
</code>```

As you can see, the total execution time improves by a lot (~14 seconds instead of ~26), just because the "limit 0" query is not executed.

As far as I know, those "limit 0" queries are executed to validate and get information about the underlying schema of the parquet files. Is there a way to disable them while using the connection pool? I ideally would like to still use PreparedStatements over simple Statements, but I could switch to simple Statements if needed, because I have full control over those queries (so, no SQL injection should be possible unless someone hacks the deployed artifacts).

答:
You are right Drill executes limit 0 prior prepared statements to get information about schema. I don't think there is a way to disable such behavior. Though I can recommend to enable planner.enable_limit0_optimization option which is false by default, this may speed limit 0 query execution. Another way to speed limit 0 queries is to indicate schema explicitly using casts through the view usage or directly in queries.

Regarding not showing query, I think this was fixed in the latest Drill version.

Body:
TL;DR

I have a Spring Boot application that makes use of parquet files stored on the file system. To access them we are using Apache Drill.

Since I have multiple users that might access them, I've set up a connection pool in Spring.

When I'm using the connection pool, Drill somehow executes a "limit 0" query before executing my actual query, and this affect performances. The same "limit 0" query is NOT executed when I run my queries through a simple Statement obtained from direct Connection.

This seems to be related to the fact that Spring JdbcTemplate makes use of PreparedStatements instead of simple Statements.

Is there a way to get rid of those "limit 0" queries?

-- Details --

The connection pool in the Spring configuration class looks like this:

@Bean
@ConfigurationProperties(prefix = "datasource.parquet")
@Qualifier("parquetDataSource")
public DataSource parquetDataSource() {
    return DataSourceBuilder.create().build();
}

And the corresponding properties in the development profile YML file are:

datasource:
  parquet:
    url: jdbc:drill:drillbit=localhost:31010
    jdbcUrl: jdbc:drill:drillbit=localhost:31010
    jndiName: jdbc/app_parquet
    driverClassName: org.apache.drill.jdbc.Driver
    maximumPoolSize: 5
    initialSize: 1
    maxIdle: 10
    maxActive: 20
    validation-query: SELECT 1 FROM sys.version
    test-on-borrow: true

When I execute a query using the JdbcTemplate created with the mentioned Drill DataSource, 3 different queries might be executed:

the validation query SELECT 1 FROM sys.version;

a "limit 0" query that looks like SELECT * FROM (<my actual query>) LIMIT 0;

my actual query.

Here's the execution code (parquetJdbcTemplate is an instance of a class that extends org.springframework.jdbc.core.JdbcTemplate):

parquetJdbcTemplate.query(sqlQuery, namedParameters,
            resultSet -> {
                MyResultSet result = new MyResultSet();
                while (resultSet.next()) {
                    // populate the "result" object
                }
                return result;
            });

Here's a screenshot from the Profile page of my Drill monitor:

The bottom query is the "limit 0" one, then in the middle you have the validation query and on top (even if the query is not shown) the actual query that returns the data I want.

As you can see, the "limit 0" query takes more than 1/3 of the entire execution time to run. The validation query is fine, since the execution time is negligible and it's needed to check the connection.

The fact is, when I execute the same query using a Connection through the Drill driver (thus, with no pool), I only see my actual query in the UI monitor:

public void executeQuery(String myQuery) {
    Class.forName("org.apache.drill.jdbc.Driver");
    Driver.load();
    Connection connection = DriverManager.getConnection("jdbc:drill:drillbit=localhost:31010");
    Statement st = connection.createStatement();
    ResultSet resultSet = st.executeQuery(myQuery);
    while (resultSet.next()) {
        // do stuff
    }
}

As you can see, the total execution time improves by a lot (~14 seconds instead of ~26), just because the "limit 0" query is not executed.

As far as I know, those "limit 0" queries are executed to validate and get information about the underlying schema of the parquet files. Is there a way to disable them while using the connection pool? I ideally would like to still use PreparedStatements over simple Statements, but I could switch to simple Statements if needed, because I have full control over those queries (so, no SQL injection should be possible unless someone hacks the deployed artifacts).


问:
Trying to regex for strings longer than 22 characters
I have a very long array of data, and I need to quickly whizz through it and make sure that none of the names are longer than 22 characters. I understand that I could truncate it on the display side, but I would rather tackle this with a proper solution, of just removing them :)

This is my sample

```<code>$profiles[257] = array('name'=>'FedupKissingFrogs', 'age'=>27, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[260] = array('name'=>'Lil_Greta_90', 'age'=>20, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[262] = array('name'=>'lOOkfOrme86', 'age'=>24, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[259] = array('name'=>'youvefoundME', 'age'=>21, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
</code>```

And here is the regex that I have come up with so far, which doesn't seem to work at all

```<code>'[A-Za-z]{20,40}'
</code>```

My plan is that I can use the regex to mark the lines and then I can delete them from within my IDE. There is no programming allowed ;)

-- Edit --

Thanks for all the replies! The idea behind this was a quick and automated way to just scan a flat PHP file containing an array to see if all the names where shorter than 22 characters, as a name longer than that will break the layout, and I've been asked to remove them. I wanted to just search in my IDE and remove the lines.

Matching the characters isn't important as such, any characters are allowable, even space, \ / ~ and * etc. I'm looking more to match length of the string but contained in the =>'$name' container.

答:
The regex would be:

```<code>/'name'=>'[^']{23,}?'/i
</code>```

This will match any line with a 'name' that is 23 characters or longer.

ContentLicense: CC BY-SA 2.5

Body:
I have a very long array of data, and I need to quickly whizz through it and make sure that none of the names are longer than 22 characters. I understand that I could truncate it on the display side, but I would rather tackle this with a proper solution, of just removing them :)

This is my sample

$profiles[257] = array('name'=>'FedupKissingFrogs', 'age'=>27, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[260] = array('name'=>'Lil_Greta_90', 'age'=>20, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[262] = array('name'=>'lOOkfOrme86', 'age'=>24, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[259] = array('name'=>'youvefoundME', 'age'=>21, 'sex'=>'F', 'location'=>'XXXXXXXXXX');

And here is the regex that I have come up with so far, which doesn't seem to work at all

'[A-Za-z]{20,40}'

My plan is that I can use the regex to mark the lines and then I can delete them from within my IDE. There is no programming allowed ;)

-- Edit --

Thanks for all the replies! The idea behind this was a quick and automated way to just scan a flat PHP file containing an array to see if all the names where shorter than 22 characters, as a name longer than that will break the layout, and I've been asked to remove them. I wanted to just search in my IDE and remove the lines.

Matching the characters isn't important as such, any characters are allowable, even space, \ / ~ and * etc. I'm looking more to match length of the string but contained in the =>'$name' container.

Body:
The regex would be:

/'name'=>'[^']{23,}?'/i

This will match any line with a 'name' that is 23 characters or longer.


问:
Check if checkbox element is checked in TypeScript
I have a checkbox on my html file.

```<code><input id="is3dCheckBox" type="checkbox" checked="checked" />
</code>```

and I want to know in the .ts file if this checkbox is checked or not.

What cast should be done after I get this element in order to check it?

答:
For documet.getElementById you can use:

```<code>let element = <HTMLInputElement> document.getElementById("is3dCheckBox");
if (element.checked) { you code }
</code>```

For documet.getElementsByName you can use:

```<code>let element = <any> document.getElementsByName("is3dCheckBox");
if (element.checked) { you code }
</code>```

Body:
I have a checkbox on my html file.

<input id="is3dCheckBox" type="checkbox" checked="checked" />

and I want to know in the .ts file if this checkbox is checked or not.

What cast should be done after I get this element in order to check it?

Body:
For documet.getElementById you can use:

let element = <HTMLInputElement> document.getElementById("is3dCheckBox");
if (element.checked) { you code }

For documet.getElementsByName you can use:

let element = <any> document.getElementsByName("is3dCheckBox");
if (element.checked) { you code }


问:
Apache Camel How do I access the Header values from an sql component
I am trying to print the number of rows selected by an sql component using the property header.CamelSqlRowCount. However the value is coming empty.
I added trace as mentioned in another post to check the header values and only breadcrumbId is getting printed. Can anyone tell me if I am doing anything wrong?

Camel Route

```<code>        <endpoint id="sqlComponent" uri="sql:${sql.pollerQuery}?dataSource=DataSource&consumer.delay=60000&consumer.useIterator=false"/>
    <route id="root">
        <from ref="sqlComponent"/>
        <log message="Received ${header.CamelSqlRowCount} records from the poller query"/>
        <log message="Message Body= ${body}"/>
    </route>
</code>```

The trace logged is below

```<code>DEBUG 2017-11-16 18:01:00 [Camel (camel-1) thread #0 - sql://SELECT%20ID%20FROM%20TABLE%20WHERE%20PUBLISHED%20=%20'N'] Executing query: SELECT ID FROM TABLE WHERE PUBLISHED = 'N'
INFO  2017-11-16 18:01:01 [Camel (camel-1) thread #0 - sql://SELECT%20ID%20FROM%20TABLE%20WHERE%20PUBLISHED%20=%20'N'] ID-MyMachine >>> (root) from(sql://SELECT%20ID%20FROM%20TABLE%20WHERE%20PUBLISHED%20=%20'N'?consumer.delay=60000&consumer.useIterator=false&dataSource=odsDataSource) --> log[Received ${header.CamelSqlRowCount} records from the poller query] <<< Pattern:InOnly, Headers:{breadcrumbId=ID-MyMachine}, BodyType:java.util.ArrayList, Body:[{ID=1}, {ID=2}, {ID=3}, {ID=4}, {ID=5}]
INFO  2017-11-16 18:01:01 [Camel (camel-1) thread #0 - sql://SELECT%20ID%20FROM%20TABLE%20WHERE%20PUBLISHED%20=%20'N'] Received  records from the poller query
INFO  2017-11-16 18:01:01 [Camel (camel-1) thread #0 - sql://SELECT%20ID%20FROM%20TABLE%20WHERE%20PUBLISHED%20=%20'N'] ID-BLRKEC381989D-52624-1510835442422-0-2 >>> (root) log[Received ${header.CamelSqlRowCount} records from the poller query] --> log[Message Body= ${body}] <<< Pattern:InOnly, Headers:{breadcrumbId=ID-MyMachine}, BodyType:java.util.ArrayList, Body:[{ID=1}, {ID=2}, {ID=3}, {ID=4}, {ID=5}]
INFO  2017-11-16 18:01:01 [Camel (camel-1) thread #0 - sql://SELECT%20ID%20FROM%20TABLE%20WHERE%20PUBLISHED%20=%20'N'] Message Body= [{ID=1}, {ID=2}, {ID=3}, {ID=4}, {ID=5}]
</code>```

Camel version - 2.15.1

答: This header is not set on the consumer, only on the producer. You have the size on the message body list size. You can log a JIRA ticket at Apache Camel to ask for this header to be included by the consumer as well.</p>

Body:
I am trying to print the number of rows selected by an sql component using the property header.CamelSqlRowCount. However the value is coming empty.
I added trace as mentioned in another post to check the header values and only breadcrumbId is getting printed. Can anyone tell me if I am doing anything wrong?

Camel Route

        <endpoint id="sqlComponent" uri="sql:${sql.pollerQuery}?dataSource=DataSource&consumer.delay=60000&consumer.useIterator=false"/>
    <route id="root">
        <from ref="sqlComponent"/>
        <log message="Received ${header.CamelSqlRowCount} records from the poller query"/>
        <log message="Message Body= ${body}"/>
    </route>

The trace logged is below

DEBUG 2017-11-16 18:01:00 [Camel (camel-1) thread #0 - sql://SELECT%20ID%20FROM%20TABLE%20WHERE%20PUBLISHED%20=%20'N'] Executing query: SELECT ID FROM TABLE WHERE PUBLISHED = 'N'
INFO  2017-11-16 18:01:01 [Camel (camel-1) thread #0 - sql://SELECT%20ID%20FROM%20TABLE%20WHERE%20PUBLISHED%20=%20'N'] ID-MyMachine >>> (root) from(sql://SELECT%20ID%20FROM%20TABLE%20WHERE%20PUBLISHED%20=%20'N'?consumer.delay=60000&consumer.useIterator=false&dataSource=odsDataSource) --> log[Received ${header.CamelSqlRowCount} records from the poller query] <<< Pattern:InOnly, Headers:{breadcrumbId=ID-MyMachine}, BodyType:java.util.ArrayList, Body:[{ID=1}, {ID=2}, {ID=3}, {ID=4}, {ID=5}]
INFO  2017-11-16 18:01:01 [Camel (camel-1) thread #0 - sql://SELECT%20ID%20FROM%20TABLE%20WHERE%20PUBLISHED%20=%20'N'] Received  records from the poller query
INFO  2017-11-16 18:01:01 [Camel (camel-1) thread #0 - sql://SELECT%20ID%20FROM%20TABLE%20WHERE%20PUBLISHED%20=%20'N'] ID-BLRKEC381989D-52624-1510835442422-0-2 >>> (root) log[Received ${header.CamelSqlRowCount} records from the poller query] --> log[Message Body= ${body}] <<< Pattern:InOnly, Headers:{breadcrumbId=ID-MyMachine}, BodyType:java.util.ArrayList, Body:[{ID=1}, {ID=2}, {ID=3}, {ID=4}, {ID=5}]
INFO  2017-11-16 18:01:01 [Camel (camel-1) thread #0 - sql://SELECT%20ID%20FROM%20TABLE%20WHERE%20PUBLISHED%20=%20'N'] Message Body= [{ID=1}, {ID=2}, {ID=3}, {ID=4}, {ID=5}]

Camel version - 2.15.1


问:
How to loop through a file based on conditions
I have a file with following contents. File name is "myXLog.txt":

```<code>IAAS Session factory creation started

X

Y

z

Communications link failure
</code>```

What I want is to read the file and if a string "IAAS Session factory creation started" is found then continue reading and if another string "Communications link failure" is found then return a message. My code only gets the first line and does not go further. Please help I checked a lot of help on internet but could not manage as I am new to shell scripting (very new).`

```<code>#!/bin/bash
filename="myXLog.txt"
while read line
do

if [[ $line == "IAAS Session factory creation started" ]] ; then
       a="YES"
       echo $a
       if a="YES"; then #HERE I WANT TO CONTINUE READING BUT NOT SURE HOW
       if [[ $line == "Communications link failure" ]] ; then
            echo "ERROR"

       else echo "ALL IS WELL"      $line
       fi
       fi
else echo "BYE"
    #fi
fi
done < $filename
</code>```

This only prints

YES

ALL IS WELL IAAS Session factory creation started

BYE

BYE

BYE

BYE

答:
You have a good start. You are checking to see if the line you are currently reading is the start to your message ("IAAS Session factory creation started") and you set a variable a to flag that you have found it! That's perfect.

You are looping here, so it will execute everything inside that if block and the while; do will LOOP to the next line and try that SAME if block again. Of course your current line isn't "IAAS Session factory creation started" anymore so it will head to your else and print "bye".

Instead you want to check if your a variable is set to YES and perform some other action in your current iteration of the file. You will do that with an elif (Else If). We can also use an elif to test if we hit the end of the message "Communications link failure"

```<code>#!/bin/bash
filename="myXLog.txt"
while read line
do
  if [[ $line == "IAAS Session factory creation started" ]] ; then
    a="YES"
    echo $a
  elif [[ $a == "YES" ]; then
    echo "ALL IS WELL" $line
  elif [[ $line == "Communications link failure" ]] ; then
    echo "ERROR"
  else
    echo "BYE"
  fi
done < $filename
</code>```

Body:
I have a file with following contents. File name is "myXLog.txt":

IAAS Session factory creation started

X

Y

z

Communications link failure

What I want is to read the file and if a string "IAAS Session factory creation started" is found then continue reading and if another string "Communications link failure" is found then return a message. My code only gets the first line and does not go further. Please help I checked a lot of help on internet but could not manage as I am new to shell scripting (very new).`

#!/bin/bash
filename="myXLog.txt"
while read line
do

if [[ $line == "IAAS Session factory creation started" ]] ; then
       a="YES"
       echo $a
       if a="YES"; then #HERE I WANT TO CONTINUE READING BUT NOT SURE HOW
       if [[ $line == "Communications link failure" ]] ; then
            echo "ERROR"

       else echo "ALL IS WELL"      $line
       fi
       fi
else echo "BYE"
    #fi
fi
done < $filename

This only prints

YES

ALL IS WELL IAAS Session factory creation started

BYE

BYE

BYE

BYE

Body:
You have a good start. You are checking to see if the line you are currently reading is the start to your message ("IAAS Session factory creation started") and you set a variable a to flag that you have found it! That's perfect.

You are looping here, so it will execute everything inside that if block and the while; do will LOOP to the next line and try that SAME if block again. Of course your current line isn't "IAAS Session factory creation started" anymore so it will head to your else and print "bye".

Instead you want to check if your a variable is set to YES and perform some other action in your current iteration of the file. You will do that with an elif (Else If). We can also use an elif to test if we hit the end of the message "Communications link failure"

#!/bin/bash
filename="myXLog.txt"
while read line
do
  if [[ $line == "IAAS Session factory creation started" ]] ; then
    a="YES"
    echo $a
  elif [[ $a == "YES" ]; then
    echo "ALL IS WELL" $line
  elif [[ $line == "Communications link failure" ]] ; then
    echo "ERROR"
  else
    echo "BYE"
  fi
done < $filename


问:
Centralized WebUI on node-red with multiple raspberry pi
I have a question regarding node-red, before jumping on it.
I find a big difficultly to get a home-automation tool such as node-red, to get working multiple raspberry pi nodes.

On the master I use django(brain)+angular(web-ui)+pigpio-library to interconnect the master pi with slaves.
Basically using pigpio I can send from the master turn-on or turn-off signals to slave without any other tool.

In my home configuration, I have 3 raspberry pi.

All 3 are connected to the same network.

1st pi is master and the other 2 are slaves.

2nd and 3rd raspberry pi are slaves, and only have pigpio service
installed

this give me centralized interface to n pi`s connected to my network

downside it that our app is not yet able to do complex things:events, tasks, etc.
So if I want to connect a PIR to my master and based on this trun on a LED on slave`s gpio, I cannot!

In node-red or home-assistant, both use mqqt to send or receive information regarding sensors or manipulate gpio`s.

Can I have with node-red a centralized interface installed ok master pi, and from there to act upon a gpio on slave pi?

thank you
George

答:
You can use the node-red-node-pi-gpiod node on a central Node-RED instance to control GPIO pins on remote pi's.

You just need to make sure that pigpiod is configured to listen on the external interface and that the firewall will not block access.


问:
Android Studio settings changed after cloning project from Github
For the first time I cloned this project from github and after that all setting of my android studio are changed. AVD Manger is Missing , Android from Project is missing , Build APK is missing and many other things It is completely changed. I am unable to fix this.  Please help me and explain how to fix this . What has happened to android studio?
This is the project link: https://github.com/HoraApps/LeafPic
I have added screenshot, please have a look:

Third Image

If possible fix this using TeamViewer.

答: Exit Android Studio and restart or open this project with Android studio or Gradle icon on it project parent directory.This means directory is Android project.You must have opened wrong directory thus no option are show.</p>

ContentLicense: CC BY-SA 4.0


问:
MySQL - Embedded selects - How to put rows into columns?
Good Morning, I am facing a odd built database and i am trying to requesting it.

My request :

```<code>use redmine_tma_ibp;
SELECT issues.id, custom_fields.name, custom_values.value FROM       redmine_tma_ibp.issues
join custom_values
    on issues.id = custom_values.customized_id
join custom_fields
    on custom_values.custom_field_id = custom_fields.id
join enumerations
    on enumerations.id=issues.priority_id
where (enumerations.type="IssuePriority" and (enumerations.position=1 or enumerations.position=2))
    and (status_id=3 or status_id=5)
    and (custom_fields.name = "Date de résolution" or custom_fields.name="Date d'ouverture")
    and str_to_date(custom_values.value, '%d/%m/%Y %H:%i') > date('2016-01-01');
</code>```

it displays the following :

```<code>13430   Date de résolution  20/01/2016 16:52:27
14336   Date de résolution  04/01/2016 16:07:06
15705   Date d'ouverture    02/01/2016 00:28:46
15705   Date de résolution  04/01/2016 11:11:04
15774   Date d'ouverture    05/01/2016 11:15:06
15774   Date de résolution  05/01/2016 15:55:43
15790   Date d'ouverture    05/01/2016 16:24:20
15790   Date de résolution  06/01/2016 10:42:28
15917   Date d'ouverture    07/01/2016 16:04:31
15917   Date de résolution  07/06/2016 11:43:08
15955   Date d'ouverture    11/01/2016 02:21:48
15955   Date de résolution  12/01/2016 11:19:21
15998   Date de résolution  13/01/2016 10:35:29
</code>```

I need to transform my request in order to have one column with the "Date d'ouverture" and another with the "Date de résolution", corresponding dates inside corresponding columns and grouped by id.

I cannot change the database structure which is read only.

Please help me....

答:
Try it like this:</p>

```<code>SELECT issues.id,
CASE
WHEN custom_fields.name = "Date d'ouverture" THEN custom_values.value END AS Date_d_ouverture,
WHEN custom_fields.name = "Date de résolution" THEN custom_values.value END AS Date_de_résolution
FROM
(your_query) sub
</code>```

Body:
Good Morning, I am facing a odd built database and i am trying to requesting it.

My request :

use redmine_tma_ibp;
SELECT issues.id, custom_fields.name, custom_values.value FROM       redmine_tma_ibp.issues
join custom_values
    on issues.id = custom_values.customized_id
join custom_fields
    on custom_values.custom_field_id = custom_fields.id
join enumerations
    on enumerations.id=issues.priority_id
where (enumerations.type="IssuePriority" and (enumerations.position=1 or enumerations.position=2))
    and (status_id=3 or status_id=5)
    and (custom_fields.name = "Date de résolution" or custom_fields.name="Date d'ouverture")
    and str_to_date(custom_values.value, '%d/%m/%Y %H:%i') > date('2016-01-01');

it displays the following :

13430   Date de résolution  20/01/2016 16:52:27
14336   Date de résolution  04/01/2016 16:07:06
15705   Date d'ouverture    02/01/2016 00:28:46
15705   Date de résolution  04/01/2016 11:11:04
15774   Date d'ouverture    05/01/2016 11:15:06
15774   Date de résolution  05/01/2016 15:55:43
15790   Date d'ouverture    05/01/2016 16:24:20
15790   Date de résolution  06/01/2016 10:42:28
15917   Date d'ouverture    07/01/2016 16:04:31
15917   Date de résolution  07/06/2016 11:43:08
15955   Date d'ouverture    11/01/2016 02:21:48
15955   Date de résolution  12/01/2016 11:19:21
15998   Date de résolution  13/01/2016 10:35:29

I need to transform my request in order to have one column with the "Date d'ouverture" and another with the "Date de résolution", corresponding dates inside corresponding columns and grouped by id.

I cannot change the database structure which is read only.

Please help me....

Body:
Try it like this:

SELECT issues.id,
CASE
WHEN custom_fields.name = "Date d'ouverture" THEN custom_values.value END AS Date_d_ouverture,
WHEN custom_fields.name = "Date de résolution" THEN custom_values.value END AS Date_de_résolution
FROM
(your_query) sub


问:
FW generated css full width issue
i have recently generated css using Fireworks cs5 and i cannot seem to set my my header full width.I have been trying various solutions but none has worked very well so far.I need Div2 which is my header to be full width.

Here is the code.

```<code>@charset "utf-8";

body {
    background-color: #fff;
    font-size: 62.5%;
    margin: 0;
    padding: 0;
}
body * {
    font-size: 100%;
}
h1, h2, h3, h4, h5, h6 {
    font-weight: normal;
}
p {
    margin-bottom: 1.1em;
    margin-top: 0;
}
#main p.lastNode {
    margin-bottom: 0;
}
a:link img, a:visited img {
    border: none;
}
div.clearFloat {
    clear: both;
    font-size: 0;
    height: 0;
    line-height: 0px;
}
li.clearFloat {
    clear: both;
}
ul.symbolList {
    display: inline;
    float: left;
    list-style-type: none;
    margin: 0;
    padding: 0;
}
.AbsWrap {
    position: relative;
    width: 100%;
}
.rowWrap {
    width: 100%;
}
#main {
    margin: 0 auto;
    width: 960px;
}
#Div {
    margin-left: 0px;
    margin-top: 0px;
    display: inline;
    float: left;
    margin-bottom: 0;
    background-color: #333;
    width: 960px;
    padding-top: 0px;
    height: 849px;
}
html > body #Div {
    height: auto;
    min-height: 850px;
}
#Div2 {
    margin-left: 0px;
    margin-top: 0px;
    display: inline;
    float: left;
    margin-bottom: 0;
    background-color: #e8807d;
    width: 960px;
    padding-top: 0px;
    height: 99px;
}
html > body #Div2 {
    height: auto;
    min-height: 100px;
}
</code>```

答: Remove float:left and display: inline — that should do it. (And the width property, if that doesn't define what you mean by "full width".)

Title: FW generated css full width issue

Body:
i have recently generated css using Fireworks cs5 and i cannot seem to set my my header full width.I have been trying various solutions but none has worked very well so far.I need Div2 which is my header to be full width.

Here is the code.

@charset "utf-8";

body {
    background-color: #fff;
    font-size: 62.5%;
    margin: 0;
    padding: 0;
}
body * {
    font-size: 100%;
}
h1, h2, h3, h4, h5, h6 {
    font-weight: normal;
}
p {
    margin-bottom: 1.1em;
    margin-top: 0;
}
#main p.lastNode {
    margin-bottom: 0;
}
a:link img, a:visited img {
    border: none;
}
div.clearFloat {
    clear: both;
    font-size: 0;
    height: 0;
    line-height: 0px;
}
li.clearFloat {
    clear: both;
}
ul.symbolList {
    display: inline;
    float: left;
    list-style-type: none;
    margin: 0;
    padding: 0;
}
.AbsWrap {
    position: relative;
    width: 100%;
}
.rowWrap {
    width: 100%;
}
#main {
    margin: 0 auto;
    width: 960px;
}
#Div {
    margin-left: 0px;
    margin-top: 0px;
    display: inline;
    float: left;
    margin-bottom: 0;
    background-color: #333;
    width: 960px;
    padding-top: 0px;
    height: 849px;
}
html > body #Div {
    height: auto;
    min-height: 850px;
}
#Div2 {
    margin-left: 0px;
    margin-top: 0px;
    display: inline;
    float: left;
    margin-bottom: 0;
    background-color: #e8807d;
    width: 960px;
    padding-top: 0px;
    height: 99px;
}
html > body #Div2 {
    height: auto;
    min-height: 100px;
}


问:
How should I or should not use Cassandra and Redis together to build a scalable one on one chat application?
Up until now I have used MySQL to do pretty much everything, but I don't like the thought of sharding my data manually and maintaining all of that for now.

I want to build a one on one chat application that is like Facebook and WhatsApp like the picture below:

So we have two parts here. The right part which is just all messages in a chat thread, and the left part that shows chat threads with information from the last message, and your chat partners information such as name and image and so on.

So far this is what I have:

Cassandra is really good at writing, and reading. But not so much at deleting data because of tombstones. And you don't want to set gc_grace_seconds to 0 because if a node goes down and deletes occur then that deleted row might come back to life when repair is done. So we might end up deleting all data from the node before it enters the cluster. Anyways, as I understood Cassandra would be perfect for the right part of this chat app. Since messages will be stored and ordered by their insertion time and that sorting will never change. So you just write and read. Which is what Cassandra is good at.

I have these table to store messages for the right part:

```<code>CREATE TYPE user_data_for_message (
    from_id INT,
    to_id INT,
    from_username TEXT,
    to_username TEXT,
    from_image_name TEXT,
    to_image_name TEXT
);

CREATE TABLE message_by_thread_id (
    message_id TIMEUUID,
    thread_id UUID,
    user_data FROZEN <user_data_for_message>,
    message TEXT,
    created_time INT,
    is_viewed BOOLEAN,
    PRIMARY KEY (thread_id, message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);
</code>```

Before I insert a new message, if the thread_id is not provided by the client, I can do a check whether a thread between two users exist. I can store that information like this:

```<code>CREATE TABLE message_thread_by_user_ids (
    thread_id UUID,
    user1_id INT,
    user2_id INT,
    PRIMARY KEY (user1_id, user2_id)
);
</code>```

I could store two rows for every thread where user1 and user2 has reversed order, so that I just need to do 1 read to check for the existence. Since I don't want to check for existence of thread before every insert, I could first check if there exists a thread between users in Redis since it is in memory and much faster.

I could save the same information above in Redis too like this (not two way as I did in Cassandra, but one way to save memory. We can do two GET to check for it):

```<code>SET user:1:user:2:message_thread_id 123e4567-e89b-12d3-a456-426655440000
</code>```

So before I send a message, I could first check in Redis whether there exists a thread between the two users. If not found in Redis, I could check in Cassandra, (in case Redis server was down at some point and did not save it), and if there exists a thread just use that thread_id to insert a new message, if not then create the thread, and then insert it in the table:

```<code>message_thread_by_user_ids
</code>```

Insert it in Redis with the SET command above. And then finally insert the message in:

```<code>message_by_thread_id
</code>```

Ok now comes the tricky part. The left part of the chat does not have static sorted order. The ordering changes all the time. If a conversation has a new message, then that conversation goes to the top. So I have not found a good way to model this in Cassandra without doing deletes and inserts. I have to delete a row and then insert it in order for the table to reorder the rows. And to delete a row and insert a row in a table, every time I send a message does not sound like a good idea to me, but I might be wrong, I am not experienced with Cassandra.

So my thought was that I could use Redis for that left part, but the only problem is that if Redis server goes down, then the most recent chat conversations on the left side will be lost, even tho the chat itself will be preserved in Cassandra. Users would need to resend message for the conversation to appear again.

I thought I could do this in Redis in the following way:

Every time a user sends a message, for example if user 1 sends message to user 2 I could do this:

```<code>ZADD user:1:message_thread_ids 1510624312 123e4567-e89b-12d3-a456-426655440000

ZADD user:2:message_thread_ids 1510624312 123e4567-e89b-12d3-a456-426655440000
</code>```

The sorted set will keep track of the id of the threads with most recently active conversations sorted by unix timestamp.

But then another problem is that every time I load this window I have to do ZRANGE and for example get 20 of the most recent conversations on the left side, and then do 20 single SELECT statements with LIMIT 1 in Cassandra to get the information about the last message sent, that is perhaps not so efficient. I thought I could save information for the last message for 20 most recent active conversations in redis with HMSET with the most relevant information such as the message itself trimmed down to 60 characters only, last_message timestamp, from_username, to_username, from_id, to_id, from_image, to_image, and message_id.

```<code>HMSET thread:123e4567-e89b-12d3-a456-426655440000 <... message info ...>
</code>```

But now I have to keep track and delete the hash maps from Redis that are not relevant, since I don't want to keep more than most recent 20, since it is going to eat up memory fast. I will get the most recent 20 from Redis and from memory, and if a user scrolls down then I will get 10 at a time from Cassandra. And the other problem is that if the Redis server goes down I might loose a conversation from the left side of the app, if the conversation is a completely new conversation.

I thought that with this approach I can get a lot of writes per second on the Cassandra side by just adding new nodes, and Redis can do like 200 000 - 800 000 operations per second so doing deletes and adding things to sorted set should not be a limitation. Since there will be some back and forth from the Redis server, I could try to either pipeline the Redis commands or write Lua scripts so that I can send the instructions to Redis in one go.

Is this a good idea? How can I solve this issue of the left side of the app that shows active conversations? Is it a good idea to do this in Redis like I suggested or should I do it differently?

答:
Both are good solutions. But where could be bottlenecks?

1) Redis is limited to memory and can not exceed it. Also when Server shutdowns, u lose your data.

2) When it comes to scaling, redis uses Master-Slave topology with sharding where as Cassandra uses a ring-topology where every node is equal to write and reads.

In my opinion I would rather use Cassandra knowing it isn't as fast as Redis but fast enough and very easy to scale.

Is this a good idea? How can I solve this issue of the left side of the app that shows active conversations? Is it a good idea to do this in Redis like I suggested or should I do it differently?

How do your user write with each other, I think u do this with a websocket, dont you? If yes, just track socket-ID and remove it when socket disconnects.

Another Question is, where and how do you retrieve the friend Ids for a certain person (left side on your picture)?

Body:
Up until now I have used MySQL to do pretty much everything, but I don't like the thought of sharding my data manually and maintaining all of that for now.

I want to build a one on one chat application that is like Facebook and WhatsApp like the picture below:

So we have two parts here. The right part which is just all messages in a chat thread, and the left part that shows chat threads with information from the last message, and your chat partners information such as name and image and so on.

So far this is what I have:

Cassandra is really good at writing, and reading. But not so much at deleting data because of tombstones. And you don't want to set gc_grace_seconds to 0 because if a node goes down and deletes occur then that deleted row might come back to life when repair is done. So we might end up deleting all data from the node before it enters the cluster. Anyways, as I understood Cassandra would be perfect for the right part of this chat app. Since messages will be stored and ordered by their insertion time and that sorting will never change. So you just write and read. Which is what Cassandra is good at.

I have these table to store messages for the right part:

CREATE TYPE user_data_for_message (
    from_id INT,
    to_id INT,
    from_username TEXT,
    to_username TEXT,
    from_image_name TEXT,
    to_image_name TEXT
);

CREATE TABLE message_by_thread_id (
    message_id TIMEUUID,
    thread_id UUID,
    user_data FROZEN <user_data_for_message>,
    message TEXT,
    created_time INT,
    is_viewed BOOLEAN,
    PRIMARY KEY (thread_id, message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);

Before I insert a new message, if the thread_id is not provided by the client, I can do a check whether a thread between two users exist. I can store that information like this:

CREATE TABLE message_thread_by_user_ids (
    thread_id UUID,
    user1_id INT,
    user2_id INT,
    PRIMARY KEY (user1_id, user2_id)
);

I could store two rows for every thread where user1 and user2 has reversed order, so that I just need to do 1 read to check for the existence. Since I don't want to check for existence of thread before every insert, I could first check if there exists a thread between users in Redis since it is in memory and much faster.

I could save the same information above in Redis too like this (not two way as I did in Cassandra, but one way to save memory. We can do two GET to check for it):

SET user:1:user:2:message_thread_id 123e4567-e89b-12d3-a456-426655440000

So before I send a message, I could first check in Redis whether there exists a thread between the two users. If not found in Redis, I could check in Cassandra, (in case Redis server was down at some point and did not save it), and if there exists a thread just use that thread_id to insert a new message, if not then create the thread, and then insert it in the table:

message_thread_by_user_ids

Insert it in Redis with the SET command above. And then finally insert the message in:

message_by_thread_id

Ok now comes the tricky part. The left part of the chat does not have static sorted order. The ordering changes all the time. If a conversation has a new message, then that conversation goes to the top. So I have not found a good way to model this in Cassandra without doing deletes and inserts. I have to delete a row and then insert it in order for the table to reorder the rows. And to delete a row and insert a row in a table, every time I send a message does not sound like a good idea to me, but I might be wrong, I am not experienced with Cassandra.

So my thought was that I could use Redis for that left part, but the only problem is that if Redis server goes down, then the most recent chat conversations on the left side will be lost, even tho the chat itself will be preserved in Cassandra. Users would need to resend message for the conversation to appear again.

I thought I could do this in Redis in the following way:

Every time a user sends a message, for example if user 1 sends message to user 2 I could do this:

ZADD user:1:message_thread_ids 1510624312 123e4567-e89b-12d3-a456-426655440000

ZADD user:2:message_thread_ids 1510624312 123e4567-e89b-12d3-a456-426655440000

The sorted set will keep track of the id of the threads with most recently active conversations sorted by unix timestamp.

But then another problem is that every time I load this window I have to do ZRANGE and for example get 20 of the most recent conversations on the left side, and then do 20 single SELECT statements with LIMIT 1 in Cassandra to get the information about the last message sent, that is perhaps not so efficient. I thought I could save information for the last message for 20 most recent active conversations in redis with HMSET with the most relevant information such as the message itself trimmed down to 60 characters only, last_message timestamp, from_username, to_username, from_id, to_id, from_image, to_image, and message_id.

HMSET thread:123e4567-e89b-12d3-a456-426655440000 <... message info ...>

But now I have to keep track and delete the hash maps from Redis that are not relevant, since I don't want to keep more than most recent 20, since it is going to eat up memory fast. I will get the most recent 20 from Redis and from memory, and if a user scrolls down then I will get 10 at a time from Cassandra. And the other problem is that if the Redis server goes down I might loose a conversation from the left side of the app, if the conversation is a completely new conversation.

I thought that with this approach I can get a lot of writes per second on the Cassandra side by just adding new nodes, and Redis can do like 200 000 - 800 000 operations per second so doing deletes and adding things to sorted set should not be a limitation. Since there will be some back and forth from the Redis server, I could try to either pipeline the Redis commands or write Lua scripts so that I can send the instructions to Redis in one go.

Is this a good idea? How can I solve this issue of the left side of the app that shows active conversations? Is it a good idea to do this in Redis like I suggested or should I do it differently?


问:
How to convert AES encrypt output bytes to string and vise versa
I want to encrypt texts using PyCrypto AES and write the output ciphertext to a text file. As you know the encrypt() output returns bytes and so I have to decode it to unicode first for it to be accepted by write() method. My problem is both str() and decode() methods throw the same error:

```<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc7 in position 0: invalid continuation byte
</code>```

Here's part of the encrypted text I'm trying to decode to utf-8:

...\xa5- \xd9\x14_\x02\x18\x96\xde\xbb\xad\xb57>\xe5i\x82H\x9b\xcc\x19y\x0f\x89\x0c~\x81\xb5(\xcc|6\x0b\x1c\xa3\x93E\x91d\xa4\x01\xb3\x98C\xb4,\x94@,\xb0\xb0\xd7\xe2\xf7\xf6U\x129B\xd6#u\x02\xc3\xe4l\xa3\x05V\x143\xe6\x85-\x88\x7f\x14\xc0\x1e\x1d\x19vQ\xbe\xc3\xda8\x06\xaf\xb9\xb7F\x91\xa6\xba&\xcb\xd7\xd0\x12\xed\xfd\xd3n\x06\xb6\x8fZ\xccpO\x05f\x...

答:
If you are writing to a binary file (something like)

```<code>binfile = open('bin.out', 'wb')
</code>```

wb is the key, then you can just call write.

If you are writing to a text file, you'll need to use base64 or something similar to encode in a format that can be included in text.  base64 and hex are the common options.

To encode in base64 do something like

```<code>import base64
b64_string = str(base64.b64encode(bytes_obj),'utf-8')
</code>```

Then use b64decode to get a string back

Body:
I want to encrypt texts using PyCrypto AES and write the output ciphertext to a text file. As you know the encrypt() output returns bytes and so I have to decode it to unicode first for it to be accepted by write() method. My problem is both str() and decode() methods throw the same error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc7 in position 0: invalid continuation byte

Here's part of the encrypted text I'm trying to decode to utf-8:

...\xa5- \xd9\x14_\x02\x18\x96\xde\xbb\xad\xb57>\xe5i\x82H\x9b\xcc\x19y\x0f\x89\x0c~\x81\xb5(\xcc|6\x0b\x1c\xa3\x93E\x91d\xa4\x01\xb3\x98C\xb4,\x94@,\xb0\xb0\xd7\xe2\xf7\xf6U\x129B\xd6#u\x02\xc3\xe4l\xa3\x05V\x143\xe6\x85-\x88\x7f\x14\xc0\x1e\x1d\x19vQ\xbe\xc3\xda8\x06\xaf\xb9\xb7F\x91\xa6\xba&\xcb\xd7\xd0\x12\xed\xfd\xd3n\x06\xb6\x8fZ\xccpO\x05f\x...

Body:
If you are writing to a binary file (something like)

binfile = open('bin.out', 'wb')

wb is the key, then you can just call write.

If you are writing to a text file, you'll need to use base64 or something similar to encode in a format that can be included in text.  base64 and hex are the common options.

To encode in base64 do something like

import base64
b64_string = str(base64.b64encode(bytes_obj),'utf-8')

Then use b64decode to get a string back


问:
Is there a way in C# to trigger a onclick() event and still be able to detect onDrag() event while still holding mouse click down
I tried the dragOver event handler but it didn't work as it should.

I am working on a piano and I want to be able to play the note even if the mousedown didn't happen on that key.

Is there an event handler for this?

The below is a picture of the piano I am working on.

答:
You should be able to watch for Mouse Enter and then check the Mouse state to see if it's clicked</p>

```<code>private void object_MouseEnter(object sender, EventArgs e)
{
    if (Mouse.LeftButton == MouseButtonState.Pressed)
    {
        'Do Something
    }
}
</code>```

Body:
You should be able to watch for Mouse Enter and then check the Mouse state to see if it's clicked

private void object_MouseEnter(object sender, EventArgs e)
{
    if (Mouse.LeftButton == MouseButtonState.Pressed)
    {
        'Do Something
    }
}


问:
Remove or Clear All Fragments From ViewPager
I'm populating view pager through fragments likes this

```<code>pagerAdapter = new PagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.container);

        for (int i = 0; i < 10; i++) {
            newfragment fragobj = new newfragment();
            fragobj.setArguments(bundle);
            pagerAdapter.addFragment(fragobj, "Category");
        }

            mViewPager.setAdapter(pagerAdapter);
            mViewPager.setCurrentItem(page);
</code>```

I want to clear all fragments and add new fragments after clearing. If I add new fragments now it ads on with old fragments.

I tried many stack overflow answers but none of them worked for me.

答:
Add this method in ViewPagerAdapter and call it when you want to clear fragments from viewPager</p>

```<code>public void clear() {
    FragmentTransaction transaction = manager.beginTransaction();
    for (Fragment fragment : mFragmentList) {
        transaction.remove(fragment);
    }
    mFragmentList.clear();
    transaction.commitAllowingStateLoss();
}
</code>```

Body:
I'm populating view pager through fragments likes this

pagerAdapter = new PagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.container);

        for (int i = 0; i < 10; i++) {
            newfragment fragobj = new newfragment();
            fragobj.setArguments(bundle);
            pagerAdapter.addFragment(fragobj, "Category");
        }

            mViewPager.setAdapter(pagerAdapter);
            mViewPager.setCurrentItem(page);

I want to clear all fragments and add new fragments after clearing. If I add new fragments now it ads on with old fragments.

I tried many stack overflow answers but none of them worked for me.

Body:
Add this method in ViewPagerAdapter and call it when you want to clear fragments from viewPager

public void clear() {
    FragmentTransaction transaction = manager.beginTransaction();
    for (Fragment fragment : mFragmentList) {
        transaction.remove(fragment);
    }
    mFragmentList.clear();
    transaction.commitAllowingStateLoss();
}


问:
PHP split to preg_split()
I wanted to convert the following split function, which I have been using to preg_split.. it's a little confusing, because the value will change from time to time...

Current code:

```<code>$root_dir = 'www';
$current_dir = 'D:/Projects/job.com/www/www/path/source';
$array = split('www', 'D:/Projects/job.com/www/www/path/source', 2);
print_r($array);
</code>```

Output of the split function:

```<code>Array ( [0] => D:/Projects/job.com/ [1] => /www/path/source )
</code>```

答:
preg_split() is similar to the old ereg-function split(). You only have to enclose the regex in /.../ like so:

```<code>preg_split('/www/', 'D:/Projects/job.com/www/www/path/source', 2);
</code>```

The enclosing slashes / here are really part of the regular expression syntax, not searched for in the string. If the www delimiter is variable, you should additionally use preg_quote() for the inner part.

But note that you don't need regular expressions if you only look for static strings anyway. In such cases you can use explode() pretty much like you used split() before:

```<code>explode('www', 'D:/Projects/job.com/www/www/path/source', 2);
</code>```

Title: PHP split to preg_split()

Body:
I wanted to convert the following split function, which I have been using to preg_split.. it's a little confusing, because the value will change from time to time...

Current code:

$root_dir = 'www';
$current_dir = 'D:/Projects/job.com/www/www/path/source';
$array = split('www', 'D:/Projects/job.com/www/www/path/source', 2);
print_r($array);

Output of the split function:

Array ( [0] => D:/Projects/job.com/ [1] => /www/path/source )

Body:
preg_split() is similar to the old ereg-function split(). You only have to enclose the regex in /.../ like so:

preg_split('/www/', 'D:/Projects/job.com/www/www/path/source', 2);

The enclosing slashes / here are really part of the regular expression syntax, not searched for in the string. If the www delimiter is variable, you should additionally use preg_quote() for the inner part.

But note that you don't need regular expressions if you only look for static strings anyway. In such cases you can use explode() pretty much like you used split() before:

explode('www', 'D:/Projects/job.com/www/www/path/source', 2);


问:
how to convert integer to binary for serial port
I am trying to send a value over serial port. I am unsure how to convert it into the correct format. I tried bin() for binary and format() but it didn't work.

```<code>result = 2
ser.open()
ser.write(b'1')
time.sleep(3)

ser.write(result)                 # wrong format
ser.write("{0:b}".format(result)) # TypeError: unicode strings
                                  # are not supported, please
                                  # encode to bytes: '10'
</code>```

The first write operation sends '1' as binary string. Now I want the variable to be send as binary string as well.

答:
Like this :

```<code>import binascii

def write(num):
    pack = binascii.unlexlify("%04X"%num)
    ser.write(pack)
</code>```

Important point: Which number system used on device (8,16,32,64 bit) ?

8 Bit = 1 Byte(0-255)

16Bit = 2 Byte(0-65535)

32Bit = 4 Byte(like upside)(0-4294967295)

All ranges are UNSIGNED(look up), but float
  got extra definition !

You can't type binary 1 value with keyboard :

binascii.unlexlify("%01X"%1) so equal to \x01 (of course you can use struct package)

Body:
I am trying to send a value over serial port. I am unsure how to convert it into the correct format. I tried bin() for binary and format() but it didn't work.

result = 2
ser.open()
ser.write(b'1')
time.sleep(3)

ser.write(result)                 # wrong format
ser.write("{0:b}".format(result)) # TypeError: unicode strings
                                  # are not supported, please
                                  # encode to bytes: '10'

The first write operation sends '1' as binary string. Now I want the variable to be send as binary string as well.

Body:
Like this :

import binascii

def write(num):
    pack = binascii.unlexlify("%04X"%num)
    ser.write(pack)

Important point: Which number system used on device (8,16,32,64 bit) ?

8 Bit = 1 Byte(0-255)

16Bit = 2 Byte(0-65535)

32Bit = 4 Byte(like upside)(0-4294967295)

All ranges are UNSIGNED(look up), but float
  got extra definition !

You can't type binary 1 value with keyboard :

binascii.unlexlify("%01X"%1) so equal to \x01 (of course you can use struct package)


问:
How do I make the Script execution box in Atom bigger?
In Atom, I am currently coding a simple beginner program to get me antiquated with the general lingo of Python. I really love atom and how advanced it is, but I have a small problem. When I execute the code I have written in Atom using the script package, I find the output text is very small and not easily readable. Is there any way to change this?

(As you can see from this screenshot, it is pretty hard to read.)

https://i.stack.imgur.com/pDl3u.png

答:
If you get the "Error compiling Less stylesheet", just remove blank space before script-view... The correct version should be </p>

```<code>.script-view .line {
        font-size: 20px;
   }
</code>```

Body:
If you get the "Error compiling Less stylesheet", just remove blank space before script-view... The correct version should be

.script-view .line {
        font-size: 20px;
   }


问:
What is the mass matrix in ode solvers in MATLAB?
Without using a mass matrix, ode solvers like ode45 can solve y'=f(t,y).

But there is an option of mass matrix in ode solvers for problems that involve a "mass" matrix, M(t,y)y'=f(t,y).

What exactly is the "mass" matrix? Does this term come from the mass of mass-spring system oscillation? I cannot find an example code about this in the documentation. Also, it seems that I can encode information about t and y in f(t,y) in the equation of y'=f(t,y). In what situation/example will M(t,y)y'=f(t,y) arise where M(t,y) is needed?

答:
The mass matrix can be used to solve coupled ordinary differential equations and algebraic equations simultaneously.

For example

y'(1) = 2y(1) + 3(y)^2

y'(2) = 5y(1) - 2y(2)^4

 0 = y(1)^3 + y(3) + 2

0 = y(2)^4 + y(4) - 8

can be solved using ode23t with a mass matrix as:

M =

[1 0 0 0

     0 1 0 0

     0 0 0 0

     0 0 0 0]

Note than few ode solvers cannot handle singular mass matrix well. ode23t and ode15s can do this job.

For more details refer: https://se.mathworks.com/help/matlab/ref/odeset.html#input_argument_namevalue_d119e730030


问:
Xamarin.Forms - Difference between Label.TextProperty.PropertyName and nameof(myLabel.Text)
Besides the syntax, is there any difference between:

```<code>Label.TextProperty.PropertyName //(Xamarin.Forms.BindableProperty.PropertyName)
</code>```

and

```<code>nameof(myLabel.Text)
</code>```

?

答:
nameof(someObject.someProperty) gives you the name of the property (someProperty)

calling someObject.someProperty returns a value, which is defined in the property, so if u have a property like int myProperty {get;set;} it will return an object of type int. The int-type has no property or function like propertyName you can call.

The only case i know where comeObject.someProperty.ProeprtyName will not fail is when the property someProperty returns an object of the type PropertyInfo.

You can get PropertyInfo for every Property via reflection.

```<code>foreach(var propertyInfo in someObject.GetType().GetProperties())
{
    string propertyName = propertyInfo.PropertyName;
}
</code>```

Body:
Besides the syntax, is there any difference between:

Label.TextProperty.PropertyName //(Xamarin.Forms.BindableProperty.PropertyName)

and

nameof(myLabel.Text)

?

Body:
nameof(someObject.someProperty) gives you the name of the property (someProperty)

calling someObject.someProperty returns a value, which is defined in the property, so if u have a property like int myProperty {get;set;} it will return an object of type int. The int-type has no property or function like propertyName you can call.

The only case i know where comeObject.someProperty.ProeprtyName will not fail is when the property someProperty returns an object of the type PropertyInfo.

You can get PropertyInfo for every Property via reflection.

foreach(var propertyInfo in someObject.GetType().GetProperties())
{
    string propertyName = propertyInfo.PropertyName;
}


问:
React native runs slow on ios device when remote debugger is off
I run into this issue when try to run app on ios device(ipad4,ios10).

The app runs slow on device when remote debugger is off, if remote js debugger is on, then it runs pretty fine.

I also tried react-native run-ios --configuration Release, but its still slow. Don't know what's going on here.

Any idea how can I evaluate the real performance of the app ?

Many thanks.

答:
It's not a solution to your problem (I really hope for you, your problem is solved in the meantime, but I'm still posting this answer if anyone else is having this problem).

As written in this github issue, when you run your app with a debugger, the JS thread lives in your debugger and not in your app. This means if you're using for example the chrome debugger, your JS get executed with the google V8 VM and the speed of your Browser/Computer. Make sure to disable every debug option and switch to release mode when you do a performance test.

If you still have performance problems you have to look and analyze other things.


答:
nameof is processed by the compiler into a constant string and thus incurs no runtime cost.

The second example, someObject.someProperty.PropertyName doesn't appear to be valid C# but, were it valid, would be computed at runtime and incur a cost at runtime. It is invalid because there is no PropertyName property that resides on every property (say that a few times fast).

The closest thing I can think of that looks similar to your second example is the Name property on a PropertyInfo object. For example, typeof(MyThing).GetProperty("MyProperty").Name. But that wouldn't solve your issue because it hardcodes the string "MyProperty".

Title: Xamarin.Forms - Difference between Label.TextProperty.PropertyName and nameof(myLabel.Text)


问:
Checkstyle not detecting @throws tag
Checkstyle keeps giving me this error:

Expected @throws tag for RemoteException

This is my javadoc comments and first line of method:

```<code>   /**
     * Inits the filter
     *
     * @throws RemoteException if there is an issue
     */

    public void init() throws RemoteException {
</code>```

答:
A late answer that worked for me is to add an extra space after the exception in the javaDoc comment:  </p>

```<code>    /**
     * ......
     * @throws DummyException (notice the extra space in this line)
     * ......
     */
</code>```

Title: Checkstyle not detecting @throws tag

Body:
Checkstyle keeps giving me this error:

Expected @throws tag for RemoteException

This is my javadoc comments and first line of method:

   /**
     * Inits the filter
     *
     * @throws RemoteException if there is an issue
     */

    public void init() throws RemoteException {

Body:
A late answer that worked for me is to add an extra space after the exception in the javaDoc comment:

    /**
     * ......
     * @throws DummyException (notice the extra space in this line)
     * ......
     */


问:
JavaScript Mobile number verification for Turkey
I want to check for mobile number entry via JavaScript RegEx but I am having difficulty on construction the proper query. What I want is to validate mobile numbers only. The format I require is :
5(0/3/4)X XXX XXXX
including the spaces.

For example;
532 123 4567 will be valid while
532 1234567 is invalid. Also
458 123 4567 is invalid.

To clarify the rules are:

First digit must be 5

Second digit must be either 0 or 3 or 4 or 5

Followed by any digit according to the following rules:

If previous digit is 0 this digit must be (5, 6 or 7)

If previous digit is 3 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

If previous digit is 4 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

If previous digit is 5 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Single space

Any 3-digit number

Single space

Any 4-digit number

Code I am using is as follows:

```<code>function isPhone(phone) {
    var pattern = [PATTERN HERE];
    return pattern.test(phone);
}
</code>```

Which pattern should I use for validation?

Regards.

答:
This is the regex you need:

```<code>/^5(0[5-7]|[3-5]\d)\s\d{3}\s\d{4}$/gm
</code>```

This is how should be your function:

```<code>function isPhone(phone) {
    var pattern = /^5(0[5-7]|[3-5]\d)\s\d{3}\s\d{4}$/gm;
    return pattern.test(phone);
}
</code>```

Demo:

const regex = /^5(0[5-7]|[3-5]\d)\s\d{3}\s\d{4}$/gm;
const str = `532 123 4567
509 457 5879
551 123 1478
532 1234567
458 123 4567
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```

Body:
I want to check for mobile number entry via JavaScript RegEx but I am having difficulty on construction the proper query. What I want is to validate mobile numbers only. The format I require is :
5(0/3/4)X XXX XXXX
including the spaces.

For example;
532 123 4567 will be valid while
532 1234567 is invalid. Also
458 123 4567 is invalid.

To clarify the rules are:

First digit must be 5

Second digit must be either 0 or 3 or 4 or 5

Followed by any digit according to the following rules:

If previous digit is 0 this digit must be (5, 6 or 7)

If previous digit is 3 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

If previous digit is 4 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

If previous digit is 5 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Single space

Any 3-digit number

Single space

Any 4-digit number

Code I am using is as follows:

function isPhone(phone) {
    var pattern = [PATTERN HERE];
    return pattern.test(phone);
}

Which pattern should I use for validation?

Regards.

Body:
This is the regex you need:

/^5(0[5-7]|[3-5]\d)\s\d{3}\s\d{4}$/gm

This is how should be your function:

function isPhone(phone) {
    var pattern = /^5(0[5-7]|[3-5]\d)\s\d{3}\s\d{4}$/gm;
    return pattern.test(phone);
}

Demo:

const regex = /^5(0[5-7]|[3-5]\d)\s\d{3}\s\d{4}$/gm;
const str = `532 123 4567
509 457 5879
551 123 1478
532 1234567
458 123 4567
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}


问:
Parameters in POST request changes automatically on the receiving end
I am using HTTPClient with Eclipse to generate a POST request to our own software.

Here is my POST request code:

```<code>import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class Posts {

    public void sendPost() throws ClientProtocolException, IOException, AuthenticationException{

    HttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("http://localhost:8080/zarr-web/command/import/BDP?deltaImport=true");

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("fileName", "D:\\\\Colibri_workspace\\colibri_trunk\\zarr\\zarr-backend\\servers\\wildfly-8.2.0.Final\\bin\\presentation\\soap_automation\\BANKDIRECTORYPLUS_V3_DAILY_DELTA_20170930.txt"));

     UsernamePasswordCredentials creds
     = new UsernamePasswordCredentials("administrator", "administrator");

    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    httppost.addHeader("Content-Type", "text/plain");
    httppost.addHeader(new BasicScheme().authenticate(creds, httppost, null));

    //Execute and get the response.
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            // do something useful
        } finally {
            instream.close();
        }
    }

    }
}
</code>```

But when I send the request on the sending side the correct "filename" is sent however when the request is received on the other side the "filename" becomes:

fileName=D%3A%5C%5CColibri_workspace%5Ccolibri_trunk%5Czarr%5Czarr-backend%5Cservers%5Cwildfly-8.2.0.Final%5Cbin%5Cpresentation%5Csoap_automation%5CBANKDIRECTORYPLUS_V3_DAILY_DELTA_20170930.txt

When I use SOAPUI software to send the request the file name is the same one as sent. Am I missing something here?

Please help.

答:
Yes you did miss that body you send is URL Encoded.
you did it explicitly:

httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

and I bet because of UrlEncodedFormEntity actual "Content-Type" header is application/x-www-form-urlencoded

you can check what you actually send to the server by bringing up any kind of TCP monitor (as example Tcpmon). Then compare what your code sends and what SOAPUI does.

URL decoded value of your example is actually what you send:

```<code>fileName=D:\\Colibri_workspace\colibri_trunk\zarr\zarr-backend\servers\wildfly-8.2.0.Final\bin\presentation\soap_automation\BANKDIRECTORYPLUS_V3_DAILY_DELTA_20170930.txt
</code>```

UPD:
First simple try make another than UrlEncodedFormEntity. As example SringEntity. If you have only one parameter just pass your file name parameter "as is":

like

```<code>"fileName=D:\\\\Colibri_workspace\\colibri_trunk\\zarr\\zarr-backend\\servers\\wildfly-8.2.0.Final\\bin\\presentation\\soap_automation\\BANKDIRECTORYPLUS_V3_DAILY_DELTA_20170930.txt"
</code>```

if you have more parameters you need to separate them by & character, like:

{param1Name}={param1Value}&{param2Name}={param2Value} and so on.

But keep in mind if your value will have & in it all be broken.

I just can say that your server side software is not good. It needs form kind of body (param=value) but violates HTTP protocol...

Body:
I am using HTTPClient with Eclipse to generate a POST request to our own software.

Here is my POST request code:

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class Posts {

    public void sendPost() throws ClientProtocolException, IOException, AuthenticationException{

    HttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("http://localhost:8080/zarr-web/command/import/BDP?deltaImport=true");

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("fileName", "D:\\\\Colibri_workspace\\colibri_trunk\\zarr\\zarr-backend\\servers\\wildfly-8.2.0.Final\\bin\\presentation\\soap_automation\\BANKDIRECTORYPLUS_V3_DAILY_DELTA_20170930.txt"));

     UsernamePasswordCredentials creds
     = new UsernamePasswordCredentials("administrator", "administrator");

    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    httppost.addHeader("Content-Type", "text/plain");
    httppost.addHeader(new BasicScheme().authenticate(creds, httppost, null));

    //Execute and get the response.
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            // do something useful
        } finally {
            instream.close();
        }
    }

    }
}

But when I send the request on the sending side the correct "filename" is sent however when the request is received on the other side the "filename" becomes:

fileName=D%3A%5C%5CColibri_workspace%5Ccolibri_trunk%5Czarr%5Czarr-backend%5Cservers%5Cwildfly-8.2.0.Final%5Cbin%5Cpresentation%5Csoap_automation%5CBANKDIRECTORYPLUS_V3_DAILY_DELTA_20170930.txt

When I use SOAPUI software to send the request the file name is the same one as sent. Am I missing something here?

Please help.

Body:
Yes you did miss that body you send is URL Encoded.
you did it explicitly:

httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

and I bet because of UrlEncodedFormEntity actual "Content-Type" header is application/x-www-form-urlencoded

you can check what you actually send to the server by bringing up any kind of TCP monitor (as example Tcpmon). Then compare what your code sends and what SOAPUI does.

URL decoded value of your example is actually what you send:

fileName=D:\\Colibri_workspace\colibri_trunk\zarr\zarr-backend\servers\wildfly-8.2.0.Final\bin\presentation\soap_automation\BANKDIRECTORYPLUS_V3_DAILY_DELTA_20170930.txt

UPD:
First simple try make another than UrlEncodedFormEntity. As example SringEntity. If you have only one parameter just pass your file name parameter "as is":

like

"fileName=D:\\\\Colibri_workspace\\colibri_trunk\\zarr\\zarr-backend\\servers\\wildfly-8.2.0.Final\\bin\\presentation\\soap_automation\\BANKDIRECTORYPLUS_V3_DAILY_DELTA_20170930.txt"

if you have more parameters you need to separate them by & character, like:

{param1Name}={param1Value}&{param2Name}={param2Value} and so on.

But keep in mind if your value will have & in it all be broken.

I just can say that your server side software is not good. It needs form kind of body (param=value) but violates HTTP protocol...


问:
Having scss-lint ignore a particular line
How do you tell scss-lint to ignore a particular line in a .scss file?

i.e. can you do something like this:

```<code>.example {
  display: block !important;  // sass-lint: ignore
}
</code>```

答:
Just adding to steveax's great answer:

If it's just for the one line, you can directly add the comment there and it will only affect that very line.

For instance, consider the following piece of code:

.example {
  display: block !important; // scss-lint:disable ImportantRule
  color: #BADA55 !important;
}
```

Your linter will issue a warning for the color line (not complying with ImportantRule) but correctly ignore your dirty work with the display property.

I usually feel it's much clearer to be as specific as possible about the scope of the rule-bending exceptions and always try not to widen these to an entire block of code -- unless it indeed makes sense.

Body:
How do you tell scss-lint to ignore a particular line in a .scss file?

i.e. can you do something like this:

.example {
  display: block !important;  // sass-lint: ignore
}

Body:
Just adding to steveax's great answer:

If it's just for the one line, you can directly add the comment there and it will only affect that very line.

For instance, consider the following piece of code:

.example {
  display: block !important; // scss-lint:disable ImportantRule
  color: #BADA55 !important;
}

Your linter will issue a warning for the color line (not complying with ImportantRule) but correctly ignore your dirty work with the display property.

I usually feel it's much clearer to be as specific as possible about the scope of the rule-bending exceptions and always try not to widen these to an entire block of code -- unless it indeed makes sense.