问:
Error when performing a join in SQLAlchemy 'Please specify the 'onclause' of this join explicitly.'
I have the following sqlalchemy model using flask-sqlalchemy. I have 3 talentpref items in my schedule model. There will always need to be 3 and no fewer.

```<code>class TalentPref(db.Model):
    __tablename__ = 'talentpref'
    id = db.Column(db.Integer, primary_key=True)
    firstName = db.Column(db.String(80), unique=True)
    lastName = db.Column(db.String(80), unique=True)

    def __init__(self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName

    def __repr__(self):
        return '<talentpref %r %r>' % (self.firstName, self.lastName)

class Schedule(db.Model):
    __tablename__ = 'schedule'

    id = db.Column(db.Integer, primary_key=True)

    talentpref1_id = db.Column(db.Integer, db.ForeignKey('talentpref.id'))
    talentpref2_id = db.Column(db.Integer, db.ForeignKey('talentpref.id'))
    talentpref3_id = db.Column(db.Integer, db.ForeignKey('talentpref.id'))

    talentpref1 = db.relationship("TalentPref", uselist=False, foreign_keys=talentpref1_id)
    talentpref2 = db.relationship("TalentPref", uselist=False, foreign_keys=talentpref2_id)
    talentpref3 = db.relationship("TalentPref", uselist=False, foreign_keys=talentpref3_id)
</code>```

I am using flask-restless to serve the schedule model as an api resource. When I perform a query on schedule and ask to sort my query by talentpref1__lastName, I receive an error which is related to my having multiple instances that refer to the "TalentPref" table:

I can use a query string successfully on the id column, like so:

```<code>/api/schedule?id=id&page=1&q={"order_by":[{"field":"id","direction":"desc"}]}
</code>```

But a query using the following http GET query string fails:

```<code>/api/schedule?id=id&page=1&q={"order_by":[{"field":"talentpref1__lastName","direction":"desc"}]}
</code>```

with:

```<code>Traceback (most recent call last):
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/flask_restless/views.py", line 1172, in _search
    result = search(self.session, self.model, search_params)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/flask_restless/search.py", line 587, in search
    query = create_query(session, model, search_params, _ignore_order_by)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/flask_restless/search.py", line 549, in create_query
    _ignore_order_by)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/flask_restless/search.py", line 498, in create_query
    query = query.join(relation_model)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 1971, in join
    from_joinpoint=from_joinpoint)
  File "<string>", line 2, in _join
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/sqlalchemy/orm/base.py", line 201, in generate
    fn(self, *args[1:], **kw)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2115, in _join
    outerjoin, full, create_aliases, prop)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2188, in _join_left_to_right
    self._join_to_left(l_info, left, right, onclause, outerjoin, full)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2317, in _join_to_left
    "Tried joining to %s, but got: %s" % (right, ae))

InvalidRequestError: Could not find a FROM clause to join from.  Tried
joining to <class 'app.model.TalentPref'>, but got: Can't determine
join between 'schedule' and 'talentpref'; tables have more than one
foreign key constraint relationship between them. Please specify the
'onclause' of this join explicitly.
</code>```

Is there a way I can query this relationship successfully?

答:
This seems to be a limitation of flask-restless itself. When passed a <fieldname> of the form <relationname>__<fieldname> it will split the name and use the 1st part as the relationship. It uses the relationship attribute to find the related model class to join to:

```<code>if '__' in field_name:
    field_name, field_name_in_relation = \
        field_name.split('__')
    relation = getattr(model, field_name)
    relation_model = relation.mapper.class_
    field = getattr(relation_model, field_name_in_relation)
    direction = getattr(field, val.direction)
    query = query.join(relation_model)
    #                  ^^^^^^^^^^^^^^ TalentPref model class
    query = query.order_by(direction())
</code>```

https://github.com/jfinkels/flask-restless/blob/0.17.0/flask_restless/search.py#L498

In your case this is effectively

```<code>query = query.join(TalentPref)
</code>```

and since you have multiple join paths, SQLAlchemy is unable to determine what to do. This would not be an issue, if flask-restless were to either use a simple relationship join instead of joining a target entity, or adapt the relationship() -driven ON clause to the target entity.

You could patch your flask-restless to fix this particular query:

```<code>--- search.py   2017-03-29 09:56:00.439981932 +0300
+++ search_joinfix.py   2017-03-29 09:56:41.375851375 +0300
@@ -495,7 +495,7 @@
                         relation_model = relation.mapper.class_
                         field = getattr(relation_model, field_name_in_relation)
                         direction = getattr(field, val.direction)
-                        query = query.join(relation_model)
+                        query = query.join(relation)
                         query = query.order_by(direction())
                     else:
                         field = getattr(model, val.field)
</code>```

Body:
I have the following sqlalchemy model using flask-sqlalchemy. I have 3 talentpref items in my schedule model. There will always need to be 3 and no fewer.

class TalentPref(db.Model):
    __tablename__ = 'talentpref'
    id = db.Column(db.Integer, primary_key=True)
    firstName = db.Column(db.String(80), unique=True)
    lastName = db.Column(db.String(80), unique=True)

    def __init__(self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName

    def __repr__(self):
        return '<talentpref %r %r>' % (self.firstName, self.lastName)

class Schedule(db.Model):
    __tablename__ = 'schedule'

    id = db.Column(db.Integer, primary_key=True)

    talentpref1_id = db.Column(db.Integer, db.ForeignKey('talentpref.id'))
    talentpref2_id = db.Column(db.Integer, db.ForeignKey('talentpref.id'))
    talentpref3_id = db.Column(db.Integer, db.ForeignKey('talentpref.id'))

    talentpref1 = db.relationship("TalentPref", uselist=False, foreign_keys=talentpref1_id)
    talentpref2 = db.relationship("TalentPref", uselist=False, foreign_keys=talentpref2_id)
    talentpref3 = db.relationship("TalentPref", uselist=False, foreign_keys=talentpref3_id)

I am using flask-restless to serve the schedule model as an api resource. When I perform a query on schedule and ask to sort my query by talentpref1__lastName, I receive an error which is related to my having multiple instances that refer to the "TalentPref" table:

I can use a query string successfully on the id column, like so:

/api/schedule?id=id&page=1&q={"order_by":[{"field":"id","direction":"desc"}]}

But a query using the following http GET query string fails:

/api/schedule?id=id&page=1&q={"order_by":[{"field":"talentpref1__lastName","direction":"desc"}]}

with:

Traceback (most recent call last):
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/flask_restless/views.py", line 1172, in _search
    result = search(self.session, self.model, search_params)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/flask_restless/search.py", line 587, in search
    query = create_query(session, model, search_params, _ignore_order_by)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/flask_restless/search.py", line 549, in create_query
    _ignore_order_by)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/flask_restless/search.py", line 498, in create_query
    query = query.join(relation_model)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 1971, in join
    from_joinpoint=from_joinpoint)
  File "<string>", line 2, in _join
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/sqlalchemy/orm/base.py", line 201, in generate
    fn(self, *args[1:], **kw)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2115, in _join
    outerjoin, full, create_aliases, prop)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2188, in _join_left_to_right
    self._join_to_left(l_info, left, right, onclause, outerjoin, full)
  File "/Users/myuser/Documents/pythonenvironments/venv/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2317, in _join_to_left
    "Tried joining to %s, but got: %s" % (right, ae))

InvalidRequestError: Could not find a FROM clause to join from.  Tried
joining to <class 'app.model.TalentPref'>, but got: Can't determine
join between 'schedule' and 'talentpref'; tables have more than one
foreign key constraint relationship between them. Please specify the
'onclause' of this join explicitly.

Is there a way I can query this relationship successfully?

Body:
This seems to be a limitation of flask-restless itself. When passed a <fieldname> of the form <relationname>__<fieldname> it will split the name and use the 1st part as the relationship. It uses the relationship attribute to find the related model class to join to:

if '__' in field_name:
    field_name, field_name_in_relation = \
        field_name.split('__')
    relation = getattr(model, field_name)
    relation_model = relation.mapper.class_
    field = getattr(relation_model, field_name_in_relation)
    direction = getattr(field, val.direction)
    query = query.join(relation_model)
    #                  ^^^^^^^^^^^^^^ TalentPref model class
    query = query.order_by(direction())

https://github.com/jfinkels/flask-restless/blob/0.17.0/flask_restless/search.py#L498

In your case this is effectively

query = query.join(TalentPref)

and since you have multiple join paths, SQLAlchemy is unable to determine what to do. This would not be an issue, if flask-restless were to either use a simple relationship join instead of joining a target entity, or adapt the relationship() -driven ON clause to the target entity.

You could patch your flask-restless to fix this particular query:

--- search.py   2017-03-29 09:56:00.439981932 +0300
+++ search_joinfix.py   2017-03-29 09:56:41.375851375 +0300
@@ -495,7 +495,7 @@
                         relation_model = relation.mapper.class_
                         field = getattr(relation_model, field_name_in_relation)
                         direction = getattr(field, val.direction)
-                        query = query.join(relation_model)
+                        query = query.join(relation)
                         query = query.order_by(direction())
                     else:
                         field = getattr(model, val.field)


来源: stackexchange

问:
RegisterClassEx Fails as Invalid Parameter - C++
A call to RegisterClassEx in my application is failing with error code 87, "The parameter is incorrect."

```<code>memset( &m_wcx, 0, sizeof(WNDCLASSEX) );

m_wcx.cbSize = sizeof(WNDCLASSEX);  // size of structure
m_wcx.style = WS_ICONIC;            // initially minimized
m_wcx.lpfnWndProc = &WndProc;       // points to window procedure
m_wcx.cbClsExtra = 0;               // no extra class memory
m_wcx.cbWndExtra = 0;               // no extra window memory
m_wcx.hInstance = m_hInstance;      // handle to instance
m_wcx.hIcon = ::LoadIcon( NULL, IDI_APPLICATION ); // default app icon
m_wcx.hCursor = ::LoadCursor( NULL, IDC_ARROW ); // standard arrow cursor
m_wcx.hbrBackground = NULL;         // no background to paint
m_wcx.lpszMenuName = NULL;          // no menu resource
m_wcx.lpszClassName = _pwcWindowClass; // name of window class
m_wcx.hIconSm = NULL;               // search system resources for sm icon

m_atom = ::RegisterClassEx( &m_wcx );

if ( m_atom == 0 )
{
    TRACE(_T("CNotifyWindow::CNotifyWindow : Failed to register window class.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    THROW(::GetLastError());
}
</code>```

Does anyone know what I'm doing wrong?  Thanks.

答: The first thing is the WS_ICONIC. The window class style is something entirely diferent from window style. The class styles are the CS_* ones.

ContentLicense: CC BY-SA 2.5

Body:
A call to RegisterClassEx in my application is failing with error code 87, "The parameter is incorrect."

memset( &m_wcx, 0, sizeof(WNDCLASSEX) );

m_wcx.cbSize = sizeof(WNDCLASSEX);  // size of structure
m_wcx.style = WS_ICONIC;            // initially minimized
m_wcx.lpfnWndProc = &WndProc;       // points to window procedure
m_wcx.cbClsExtra = 0;               // no extra class memory
m_wcx.cbWndExtra = 0;               // no extra window memory
m_wcx.hInstance = m_hInstance;      // handle to instance
m_wcx.hIcon = ::LoadIcon( NULL, IDI_APPLICATION ); // default app icon
m_wcx.hCursor = ::LoadCursor( NULL, IDC_ARROW ); // standard arrow cursor
m_wcx.hbrBackground = NULL;         // no background to paint
m_wcx.lpszMenuName = NULL;          // no menu resource
m_wcx.lpszClassName = _pwcWindowClass; // name of window class
m_wcx.hIconSm = NULL;               // search system resources for sm icon

m_atom = ::RegisterClassEx( &m_wcx );

if ( m_atom == 0 )
{
    TRACE(_T("CNotifyWindow::CNotifyWindow : Failed to register window class.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    THROW(::GetLastError());
}

Does anyone know what I'm doing wrong?  Thanks.


问:
Force a refresh on parent component
I'm working with a small datagrid in Angular 2 and i have a question about parent/child relationships between components. I have two components: app-datagrid and app-add-item. The datagrid component, in his HTML, includes the app-add-item component, which is composed of a button and a modal. When clicked, the button displays the modal with a form to create a new item.

All the logic is isolated and nice: the app-add-item component creates and handles the form, sends the form data to the service and creates a new item. However, how can i update the datagrid once its child component has finished adding a new item?

Should the app-datagrid component listen for an event? Should it be passed as a dependency to the child? What's the proper way of doing this?

答:
I think you could have the app-add-item component emit an @Output event to indicate an item has been added.  Then have the app-datagrid bind to that event - something like this:

```<code><app-data-grid #dataGrid>
..
   <app-add-item (itemAdded)="dataGrid.addNewItem($event)"></app-add-item>
..
</app-data-grid>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Force a refresh on parent component

Body:
I think you could have the app-add-item component emit an @Output event to indicate an item has been added.  Then have the app-datagrid bind to that event - something like this:

<app-data-grid #dataGrid>
..
   <app-add-item (itemAdded)="dataGrid.addNewItem($event)"></app-add-item>
..
</app-data-grid>


问:
ERROR | [iOS] file patterns: The `source_files` pattern did not match any file
I renamed my Existing library to github, I changed everything and things are working fine apart from it's not validating my library now by - pod spec lint KJCircularSlider.podspec for trunk push. I checked my folder structure and it looks perfect, anyone can help me what can be the actual issue?

Here is my library if you want to check folder structure - KJCircularSlider

Here is my podspec file.

```<code>Pod::Spec.new do |s|
  s.name             = 'KJCircularSlider'
  s.version          = '0.1.0'
  s.summary          = 'Circular slider - to slide from 0 to 100 in circular shape'

# This description is used to generate tags and improve search results.
#   * Think: What does it do? Why did you write it? What is the focus?
#   * Try to keep it short, snappy and to the point.
#   * Write the description between the DESC delimiters below.
#   * Finally, don't worry about the indent, CocoaPods strips it!

  s.description      = <<-DESC
TODO: Add long description of the pod here.
It's circular slider, It provides circular shape to slide around from 0 to 100 percent, You can use it when you required a circular shape on slider rather than traditional iOS line shape slider.
                       DESC

  s.homepage         = 'https://github.com/KiranJasvanee/KJCircularSlider'
  # s.screenshots     = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
  s.license          = { :type => 'MIT', :file => 'LICENSE' }
  s.author           = { 'Kiran Jasvanee' => 'kiran.jasvanee@yahoo.com' }
  s.source           = { :git => 'https://github.com/KiranJasvanee/KJCircularSlider.git', :tag => s.version.to_s }
  # s.social_media_url = 'https://twitter.com/KiranJasvanee'

  s.ios.deployment_target = '9.0'

  s.source_files = 'Classes/**/*'

  # s.resource_bundles = {
  #   'KJCircularSlider' => ['KJCircularSlider/Assets/*.png']
  # }

  # s.public_header_files = 'Pod/Classes/**/*.h'
  # s.frameworks = 'UIKit', 'MapKit'
  # s.dependency 'AFNetworking', '~> 2.3'
end
</code>```

答:
I've solved my issue by changing version number of my pod.

I've renamed my KJCurveSlider library to KJCircularSlider, because of major changes in library I wouldn't be able to push it using pod trunk push. I was constantly receiving following error when I tried to validate using pod spec lint library.podspec, nevertheless I had mention perfect path of s.source_files in podspec

- ERROR | [iOS] file patterns: Thesource_filespattern did not match any file.

Then I updated version from 0.1.0 to 0.2.0, it validated successfully

Body:
I renamed my Existing library to github, I changed everything and things are working fine apart from it's not validating my library now by - pod spec lint KJCircularSlider.podspec for trunk push. I checked my folder structure and it looks perfect, anyone can help me what can be the actual issue?

Here is my library if you want to check folder structure - KJCircularSlider

Here is my podspec file.

Pod::Spec.new do |s|
  s.name             = 'KJCircularSlider'
  s.version          = '0.1.0'
  s.summary          = 'Circular slider - to slide from 0 to 100 in circular shape'

# This description is used to generate tags and improve search results.
#   * Think: What does it do? Why did you write it? What is the focus?
#   * Try to keep it short, snappy and to the point.
#   * Write the description between the DESC delimiters below.
#   * Finally, don't worry about the indent, CocoaPods strips it!

  s.description      = <<-DESC
TODO: Add long description of the pod here.
It's circular slider, It provides circular shape to slide around from 0 to 100 percent, You can use it when you required a circular shape on slider rather than traditional iOS line shape slider.
                       DESC

  s.homepage         = 'https://github.com/KiranJasvanee/KJCircularSlider'
  # s.screenshots     = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
  s.license          = { :type => 'MIT', :file => 'LICENSE' }
  s.author           = { 'Kiran Jasvanee' => 'kiran.jasvanee@yahoo.com' }
  s.source           = { :git => 'https://github.com/KiranJasvanee/KJCircularSlider.git', :tag => s.version.to_s }
  # s.social_media_url = 'https://twitter.com/KiranJasvanee'

  s.ios.deployment_target = '9.0'

  s.source_files = 'Classes/**/*'

  # s.resource_bundles = {
  #   'KJCircularSlider' => ['KJCircularSlider/Assets/*.png']
  # }

  # s.public_header_files = 'Pod/Classes/**/*.h'
  # s.frameworks = 'UIKit', 'MapKit'
  # s.dependency 'AFNetworking', '~> 2.3'
end


问:
Update dynamoDB key that contains map
I'm using:

http://awspilot.github.io/dynamodb-oop/#query

(aws-sdk wrapper)

I have an object that is stored in DB.
I want to update a value that it's a map.

This is my table:

```<code>userId, myMap

123     {'abc': '123'}
</code>```

And this is the code:

```<code>var tableName = 'myTable';
var userIdKey = 'userId';

function updateMyMap(userId, dic) {

    DynamoDB
    .table(tableName)
    .where(userIdKey).eq(userId)
    .return(DynamoDB.ALL_OLD)
    .insert_or_update({
        myMap: dic
    }, function( err, data ) {
        console.log( err, data )
    })
}
</code>```

First example:

When I call updateMyMap:

```<code>updateMyMap('123', {'abc':'456', 'def':'555'});
</code>```

I want the table to be:

```<code>userId, myMap

123     {'abc': '456', 'def':'555'}
</code>```

Second example:

When I call updateMyMap:

```<code>updateMyMap('123', {'ghi':'222'});
</code>```

I want the table to be:

```<code>userId, myMap

123     {'abc': '456', 'def':'555', 'ghi':'222'}
</code>```

Any help appreciated!

答:
Use an update expression in an UpdateItem call:

```<code>SET myMap.#key = :value
</code>```

The other parameters would be:

```<code>ConditionExpression: attribute_exists(myMap)
ExpressionAttributeNames: { "#key": "ghi" }
ExpressionAttributeValues: { ":value": 222 }
</code>```

Title: Update dynamoDB key that contains map

Body:
I'm using:

http://awspilot.github.io/dynamodb-oop/#query

(aws-sdk wrapper)

I have an object that is stored in DB.
I want to update a value that it's a map.

This is my table:

userId, myMap

123     {'abc': '123'}

And this is the code:

var tableName = 'myTable';
var userIdKey = 'userId';

function updateMyMap(userId, dic) {

    DynamoDB
    .table(tableName)
    .where(userIdKey).eq(userId)
    .return(DynamoDB.ALL_OLD)
    .insert_or_update({
        myMap: dic
    }, function( err, data ) {
        console.log( err, data )
    })
}

First example:

When I call updateMyMap:

updateMyMap('123', {'abc':'456', 'def':'555'});

I want the table to be:

userId, myMap

123     {'abc': '456', 'def':'555'}

Second example:

When I call updateMyMap:

updateMyMap('123', {'ghi':'222'});

I want the table to be:

userId, myMap

123     {'abc': '456', 'def':'555', 'ghi':'222'}

Any help appreciated!

Body:
Use an update expression in an UpdateItem call:

SET myMap.#key = :value

The other parameters would be:

ConditionExpression: attribute_exists(myMap)
ExpressionAttributeNames: { "#key": "ghi" }
ExpressionAttributeValues: { ":value": 222 }


问:
Create variable with many types in swift3
I have a struct and in this struct I have variable that I want to be of any type UITextField of UIButton. I think I can use generics somehow.
So, my code looks like this

```<code>private struct ValidationObject {
    var textField: RITextFieldLine
        ...
}
</code>```

textField variable with type RITextFieldLine is my custom view. But I don't want it to be of this specific type.

答:
If all you want to assign are view elements then:

```<code>private struct ValidationObject {
    var textField: UIView
        ...
}
</code>```

Otherwise:

```<code>private struct ValidationObject {
    var textField: Any
        ...
}
</code>```

Considering your property naming (textField), I'd say go with the first one. Just remember to use this when you a want to use the variable as a specific type:

```<code>if let textField = validationObjectInstance.textField as? RITextFieldLine {
    textField.someMethodOrProperty
}
</code>```

Body:
I have a struct and in this struct I have variable that I want to be of any type UITextField of UIButton. I think I can use generics somehow.
So, my code looks like this

private struct ValidationObject {
    var textField: RITextFieldLine
        ...
}

textField variable with type RITextFieldLine is my custom view. But I don't want it to be of this specific type.

Body:
If all you want to assign are view elements then:

private struct ValidationObject {
    var textField: UIView
        ...
}

Otherwise:

private struct ValidationObject {
    var textField: Any
        ...
}

Considering your property naming (textField), I'd say go with the first one. Just remember to use this when you a want to use the variable as a specific type:

if let textField = validationObjectInstance.textField as? RITextFieldLine {
    textField.someMethodOrProperty
}


问:
Nodemailer error when required
My resume website is almost done, I'm just finalizing a "Contact me" form that should send me an e-mail with some plain text.

Here's what it looks like in Jade:

```<code>div.contact-email-box
    form(id='contact-form' action='/' method='post')
        h3 Contact me
        div
            label
                span Name:
                input(placeholder='e.g: Mark' type='text' tabindex='1' required autofocus)
        div
            label
                span Email:
                input(placeholder='e.g: mark@example.com' type='email' tabindex='2' required)
        div
            label
                span Message:
                textarea(tabindex='3' required)
        div
            button(name='Submit' type='submit' id='contact-submit') Send Email
</code>```

And here's where I catch the POST in my server.js:

```<code>var express = require('express')
              , app = express()
var nodemailer = require('nodemailer')

app.post('/', function(req, res) {
})
</code>```

As you can see it does not do anything, yet I receive the following error:

/home/kade_c/website/node_modules/nodemailer/lib/mailer/index.js:31
              compile: [(...args) => this._convertDataImages(...args)],
                         ^^^

SyntaxError: Unexpected token ...

That happens only when I require('nodemailer') even though it is installed correctly to my node_modules.

Is this a known bug? How may I fix it?

答:
Node.js version 6+ is must. Check your Node version with the following command:

node --version

If you are not at least 6+ then you must upgrade.

You may receive another error message instructing you to login to your account. In that case, go to your email inbox and you will see a message from Google with a link to a page for setting up less secure app permissions.

Title: Nodemailer error when required

Body:
My resume website is almost done, I'm just finalizing a "Contact me" form that should send me an e-mail with some plain text.

Here's what it looks like in Jade:

div.contact-email-box
    form(id='contact-form' action='/' method='post')
        h3 Contact me
        div
            label
                span Name:
                input(placeholder='e.g: Mark' type='text' tabindex='1' required autofocus)
        div
            label
                span Email:
                input(placeholder='e.g: mark@example.com' type='email' tabindex='2' required)
        div
            label
                span Message:
                textarea(tabindex='3' required)
        div
            button(name='Submit' type='submit' id='contact-submit') Send Email

And here's where I catch the POST in my server.js:

var express = require('express')
              , app = express()
var nodemailer = require('nodemailer')

app.post('/', function(req, res) {
})

As you can see it does not do anything, yet I receive the following error:

/home/kade_c/website/node_modules/nodemailer/lib/mailer/index.js:31
              compile: [(...args) => this._convertDataImages(...args)],
                         ^^^

SyntaxError: Unexpected token ...

That happens only when I require('nodemailer') even though it is installed correctly to my node_modules.

Is this a known bug? How may I fix it?


问:
matlab version doesn't support some functions
Undefined function 'extractHOGFeatures' and am using Matlab R2016a version , Is  'extractHOGFeatures' included in this version or not ? if yes how can i include ?
if not in which version and how can i use it ?</p>

答:
As one could see in the documentation of extractHOGFeatures() it was introduced in MATLAB R2013b:

This is a great feature in the documentation of any MATLAB's function.

If you still don't have access to it, probably it's because the function is part of Computer Vision System Toolbox which requires a license you may not have.

ContentLicense: CC BY-SA 4.0


问:
search on ng-repeat by grouping the items
I have created ng-repeat by group on which I am applying the filter, everything is working fine but the search functionality is not doing well, means when I am searching an item then its displaying the item but along with other group names are displaying which I want to hide.
when I search for an item then it should display the item along with the group and hide all the groups and other items.
Below is the

{{ key }}

{{pop.EmpName}}

Id: {{pop.EmpNo}}

Desig: {{pop.Designation | titlecase}}

```

code.

答:
add your js code pls . Or you can create </p>

```<code><input ng-model="lookfor "/>
</code>```

Body:
I have created ng-repeat by group on which I am applying the filter, everything is working fine but the search functionality is not doing well, means when I am searching an item then its displaying the item but along with other group names are displaying which I want to hide.
when I search for an item then it should display the item along with the group and hide all the groups and other items.
Below is the

{{ key }}

{{pop.EmpName}}

Id: {{pop.EmpNo}}

Desig: {{pop.Designation | titlecase}}

code.

Body:
add your js code pls . Or you can create

<input ng-model="lookfor "/>


问:
lists with parenthesis using only javascript or jquery?
I need a list (
 and
) with parenthesis like this.

```<code>(1) List1
(2) List2
(3) List3
(4) List4
</code>```

The important thing is that I need this using only javascript or jQuery without using external, internal css.

This is my code

```<code>$("ol").css("counter-reset", "list");
$("ol li").css("list-style", "none");
$("ol li:before").css({"content": "counter(list, lower-alpha) ') '", "counter-increment": "list"});
</code>```

答:
sir you just need to use:</p>

```<code>$(document).ready(function() {
    var ol = $('ol li');
    ol.css("list-style", "none");

    $.each(ol, function(i, el){
        $(el).text('(' + (i + 1 )+') ' + $(el).text());
    });

});
</code>```

Body:
I need a list (
 and
) with parenthesis like this.

(1) List1
(2) List2
(3) List3
(4) List4

The important thing is that I need this using only javascript or jQuery without using external, internal css.

This is my code

$("ol").css("counter-reset", "list");
$("ol li").css("list-style", "none");
$("ol li:before").css({"content": "counter(list, lower-alpha) ') '", "counter-increment": "list"});

Body:
sir you just need to use:

$(document).ready(function() {
    var ol = $('ol li');
    ol.css("list-style", "none");

    $.each(ol, function(i, el){
        $(el).text('(' + (i + 1 )+') ' + $(el).text());
    });

});


问:
HTML5 Background Color fill too big
When I try to make an HTML background color fill for a div, it ends up with a huge amount of extra space at the bottom - I want to make a sort of header, but it becomes really wide. Can someone help me with this?

My HTML is

```<code><div class="header">
    <h1>Welcome to My Site</h1>
</div>
</code>```

My CSS is

```<code>div.header{
  background-color:grey;
}
</code>```

Thanks!

答:
I would recommend adding width, height, and margin to your code. You can experiment with your code with a website like codepen.io! Below is a link to an example of what I'm talking about.

https://codepen.io/wykydtronik/pen/VpEGer

```<code>div.header{
  background-color:grey;
  width: 350px;
  height: 150px;
  margin: 0 auto;
}
</code>```

If you look at the CSS code you will see I set a width of 350px, and height of 150px. I also added a margin: 0 auto; to make the header div to be center. It's a neat trick that isn't intuitive until you've seen it a few times.

Let me know if this helps, good luck!

Title: HTML5 Background Color fill too big

Body:
When I try to make an HTML background color fill for a div, it ends up with a huge amount of extra space at the bottom - I want to make a sort of header, but it becomes really wide. Can someone help me with this?

My HTML is

Welcome to My Site

My CSS is

div.header{
  background-color:grey;
}

Thanks!

Body:
I would recommend adding width, height, and margin to your code. You can experiment with your code with a website like codepen.io! Below is a link to an example of what I'm talking about.

https://codepen.io/wykydtronik/pen/VpEGer

div.header{
  background-color:grey;
  width: 350px;
  height: 150px;
  margin: 0 auto;
}

If you look at the CSS code you will see I set a width of 350px, and height of 150px. I also added a margin: 0 auto; to make the header div to be center. It's a neat trick that isn't intuitive until you've seen it a few times.

Let me know if this helps, good luck!


问:
Unable to load data from Apache hive to ElasticSearch -
I am using CDH5.5,ElasticSearch-2.4.1.
I have created Hive table and trying to push the hive table data to ElasticSearch using the below query.

```<code>CREATE EXTERNAL TABLE test1_es(
  id string,
  timestamp string,
  dept string)<br>
ROW FORMAT SERDE 'org.elasticsearch.hadoop.hive.EsSerDe'
STORED BY 'org.elasticsearch.hadoop.hive.EsStorageHandler'
LOCATION
  'hdfs://quickstart.cloudera:8020/user/cloudera/elasticsearch/test1_es'
TBLPROPERTIES (  'es.nodes'='localhost',
'es.resource'='sample/test1',
'es.mapping.names' = 'timestamp:@timestamp',
'es.port' = '9200',
'es.input.json' = 'false',
'es.write.operation' = 'index',
'es.index.auto.create' = 'yes'
);<br>
INSERT INTO TABLE default.test1_es select id,timestamp,dept from test1_hive;
</code>```

I'm getting the below error in the Job Tracker URL
"

```<code> Failed while trying to construct the redirect url to the log server. Log Server url may not be configured. <br>
java.lang.Exception: Unknown container. Container either has not started or has already completed or doesn't belong to this node at all. "
</code>```

It will throw "FAILED: Execution Error, return code 2 from org.apache.hadoop.hive.ql.exec.mr.MapRedTask" in hive terminal.

I tried all the steps mentioned in forums like including /usr/lib/hive/bin/elasticsearch-hadoop-2.0.2.jar in hive-site.xml, adding ES-hadoop jar to HIVEAUXJARS_PATH, copied yarn jar to /usr/lib/hadoop/elasticsearch-yarn-2.1.0.Beta3.jar also. Please suggest me how to fix the error.

Thanks in Advance,
Sreenath

答:
```<code>REATE EXTERNAL TABLE test1_es(
  id string,
  timestamp string,
  dept string)<br>
ROW FORMAT SERDE 'org.elasticsearch.hadoop.hive.EsSerDe'
STORED BY 'org.elasticsearch.hadoop.hive.EsStorageHandler'
TBLPROPERTIES ...........
</code>```

don't need location

Body:
I am using CDH5.5,ElasticSearch-2.4.1.
I have created Hive table and trying to push the hive table data to ElasticSearch using the below query.

CREATE EXTERNAL TABLE test1_es(
  id string,
  timestamp string,
  dept string)

ROW FORMAT SERDE 'org.elasticsearch.hadoop.hive.EsSerDe'
STORED BY 'org.elasticsearch.hadoop.hive.EsStorageHandler'
LOCATION
  'hdfs://quickstart.cloudera:8020/user/cloudera/elasticsearch/test1_es'
TBLPROPERTIES (  'es.nodes'='localhost',
'es.resource'='sample/test1',
'es.mapping.names' = 'timestamp:@timestamp',
'es.port' = '9200',
'es.input.json' = 'false',
'es.write.operation' = 'index',
'es.index.auto.create' = 'yes'
);

INSERT INTO TABLE default.test1_es select id,timestamp,dept from test1_hive;

I'm getting the below error in the Job Tracker URL
"

 Failed while trying to construct the redirect url to the log server. Log Server url may not be configured.

java.lang.Exception: Unknown container. Container either has not started or has already completed or doesn't belong to this node at all. "

It will throw "FAILED: Execution Error, return code 2 from org.apache.hadoop.hive.ql.exec.mr.MapRedTask" in hive terminal.

I tried all the steps mentioned in forums like including /usr/lib/hive/bin/elasticsearch-hadoop-2.0.2.jar in hive-site.xml, adding ES-hadoop jar to HIVEAUXJARS_PATH, copied yarn jar to /usr/lib/hadoop/elasticsearch-yarn-2.1.0.Beta3.jar also. Please suggest me how to fix the error.

Thanks in Advance,
Sreenath

Body:
REATE EXTERNAL TABLE test1_es(
  id string,
  timestamp string,
  dept string)<br>
ROW FORMAT SERDE 'org.elasticsearch.hadoop.hive.EsSerDe'
STORED BY 'org.elasticsearch.hadoop.hive.EsStorageHandler'
TBLPROPERTIES ...........

don't need location


问:
Nodejs how to block the actual endpoint that was requested from an .all endpoint?
I've got an .all endpoint which gets called for all endpoints connected to accounts. What I want to do in it is check a token and then if it's true, progress to the endpoint that was actually requested.

I thought next() was supposed to do this but the other requests are being called regardless of the token being valid or not.

What am I doing wrong?

```<code>router.all(['/accounts', '/accounts/*'], (req, res, next) => {

  admin.auth().verifyIdToken(req.headers.authorization)
  .then((token) => {

    // TODO: Fix so that this actually works, now the other routes are being called regardless
    next();
  }).catch((error) => {

    res.send({
      error: error,
      data: {
        account: null,
        message: 'Invalid token',
        status: 401
      }
    });
  });
});

router.post('/accounts', (req.res, next) => {});
router.post('/accounts/:uid', (req.res, next) => {});
</code>```

How can I make sure that the .all endpoint only continues to either /accounts or /accounts/:uid if the verifyToken function is successful? Apparently next() doesn't do anything in terms of blocking consecutive requests.

答:
If you don't return in the catch then it will continue to the next route, if you return it breaks the chain:

```<code>router.all(['/accounts', '/accounts/*'], (req, res, next) => {

  admin.auth().verifyIdToken(req.headers.authorization)
  .then((token) => {
    next();
  }).catch((error) => {

    return res.send({
      error: error,
      data: {
        account: null,
        message: 'Invalid token',
        status: 401
      }
    });
  });
});
</code>```

Body:
I've got an .all endpoint which gets called for all endpoints connected to accounts. What I want to do in it is check a token and then if it's true, progress to the endpoint that was actually requested.

I thought next() was supposed to do this but the other requests are being called regardless of the token being valid or not.

What am I doing wrong?

router.all(['/accounts', '/accounts/*'], (req, res, next) => {

  admin.auth().verifyIdToken(req.headers.authorization)
  .then((token) => {

    // TODO: Fix so that this actually works, now the other routes are being called regardless
    next();
  }).catch((error) => {

    res.send({
      error: error,
      data: {
        account: null,
        message: 'Invalid token',
        status: 401
      }
    });
  });
});

router.post('/accounts', (req.res, next) => {});
router.post('/accounts/:uid', (req.res, next) => {});

How can I make sure that the .all endpoint only continues to either /accounts or /accounts/:uid if the verifyToken function is successful? Apparently next() doesn't do anything in terms of blocking consecutive requests.

Body:
If you don't return in the catch then it will continue to the next route, if you return it breaks the chain:

router.all(['/accounts', '/accounts/*'], (req, res, next) => {

  admin.auth().verifyIdToken(req.headers.authorization)
  .then((token) => {
    next();
  }).catch((error) => {

    return res.send({
      error: error,
      data: {
        account: null,
        message: 'Invalid token',
        status: 401
      }
    });
  });
});


问:
Ruby: Send define_method with block arguments
I'm trying to do something like this, where the send method's block has block arguments:

```<code>  klass.attribute_names.each do |attribute|
    klass.send(define_method("next_by_" + attribute) { object, user = nil
      if user
        klass.joins(:users).where("#{attribute} > ?", object.send(attribute)).where(users: {id: user.id}).first
      else
        klass.where("#{attribute} > ?", object.send(attribute)).first
      end
    })
  end
</code>```

Which isn't valid Ruby. Is this possible to do, and if so what is the best way to do so?

EDIT: I realize the reserved keyword "class" here. It is simply for illustration purposes. I've changed it to klass to prevent further confusion.

More detail, this is the entire file:

```<code>module Helpers::ResourceRecordHelper

  # Remove this and call upon the module's methods to include instead to fix performance hit
  def self.included(source)
    define_class_methods(source)
  end

  def define_class_methods(source)
    source.attribute_names.each do |attribute|

      # These defined methods never reach the class
      define_method("next_by_" + attribute) { object, user = nil
        if user
          self.class.joins(:users).where("#{attribute} > ?", object.send(attribute)).where(users: {id: user.id}).first
        else
          self.class.where("#{attribute} > ?", object.send(attribute)).first
        end
      }

      define_method("previous_by_" + attribute) do object, user = nil
        if user
          self.class.joins(:users).where("#{attribute} < ?", object.send(attribute)).where(users: {id: user.id}).last
        else
          self.class.where("#{attribute} < ?", object.send(attribute)).last
        end
      end
    end

    def source.next(object, user = nil)
      source.next_by_id(object, user)
    end

    def source.previous(object, user = nil)
      source.previous_by_id(object, user)
    end
  end

  extend self

end
</code>```

答:
You have few issues, like using reserved words, not understanding the self (or rather not implementing your understanding correctly).

```<code>source.attribute_names.each do |attribute|
  source.singleton_class.instance_eval do
    define_method('next_by_' + attribute) do |object, user = nil|
      if user
        source.joins(:users)
              .where("#{attribute} > ?", object.public_send(attribute))
              .where(users: { id: user.id })
              .first
      else
        source.where("#{attribute} > ?", object.public_send(attribute)).first
      end
    end
  end
end
</code>```

Body:
I'm trying to do something like this, where the send method's block has block arguments:

  klass.attribute_names.each do |attribute|
    klass.send(define_method("next_by_" + attribute) { object, user = nil
      if user
        klass.joins(:users).where("#{attribute} > ?", object.send(attribute)).where(users: {id: user.id}).first
      else
        klass.where("#{attribute} > ?", object.send(attribute)).first
      end
    })
  end

Which isn't valid Ruby. Is this possible to do, and if so what is the best way to do so?

EDIT: I realize the reserved keyword "class" here. It is simply for illustration purposes. I've changed it to klass to prevent further confusion.

More detail, this is the entire file:

module Helpers::ResourceRecordHelper

  # Remove this and call upon the module's methods to include instead to fix performance hit
  def self.included(source)
    define_class_methods(source)
  end

  def define_class_methods(source)
    source.attribute_names.each do |attribute|

      # These defined methods never reach the class
      define_method("next_by_" + attribute) { object, user = nil
        if user
          self.class.joins(:users).where("#{attribute} > ?", object.send(attribute)).where(users: {id: user.id}).first
        else
          self.class.where("#{attribute} > ?", object.send(attribute)).first
        end
      }

      define_method("previous_by_" + attribute) do object, user = nil
        if user
          self.class.joins(:users).where("#{attribute} < ?", object.send(attribute)).where(users: {id: user.id}).last
        else
          self.class.where("#{attribute} < ?", object.send(attribute)).last
        end
      end
    end

    def source.next(object, user = nil)
      source.next_by_id(object, user)
    end

    def source.previous(object, user = nil)
      source.previous_by_id(object, user)
    end
  end

  extend self

end

Body:
You have few issues, like using reserved words, not understanding the self (or rather not implementing your understanding correctly).

source.attribute_names.each do |attribute|
  source.singleton_class.instance_eval do
    define_method('next_by_' + attribute) do |object, user = nil|
      if user
        source.joins(:users)
              .where("#{attribute} > ?", object.public_send(attribute))
              .where(users: { id: user.id })
              .first
      else
        source.where("#{attribute} > ?", object.public_send(attribute)).first
      end
    end
  end
end


问:
MVC2 DisplayFormat Attribute Doesn't Work After PostBack
I have a ViewModel with a property as below:

```<code>    [DisplayName("As Configured On:")]
    [DisplayFormat(DataFormatString="{0:d}", ApplyFormatInEditMode=true)]
    public DateTime ConfigDate { get; set; }
</code>```

The Form that displays the ConfigDate is as below:

```<code><%= Html.EditorFor(Model => Model.ConfigDate)%>
</code>```

When the Index Action comes back, everything looks formatted correctly, i.e. the <input> box has the date value as 12/12/2001.  When the form is posted, the result that comes back is as though the DisplayFormat attribute isn't being applied.

EDIT:
More info was requested: here is the code en toto:

The Search Form

```<code><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Config.Web.Models.AirplanesViewModel>" %>
<% using (Html.BeginForm("Details", "Airplanes", FormMethod.Post, new { id = "SearchForm" })) { %>
<%= Html.LabelFor(model => model.ConfigDate) %>
<%= Html.EditorFor(Model => Model.ConfigDate)%>
<input id="searchButton" type="submit" value="Search" />
<% } %>
</code>```

The AirplanesViewModel

```<code>    public class AirplanesViewModel
{
    [DisplayName("As Configured On:")]
    [DisplayFormat(DataFormatString="{0:d}", ApplyFormatInEditMode=true)]
    public DateTime ConfigDate { get; set; }
}
}
</code>```

The Controller

```<code>        [HttpGet]
    public ActionResult Index()
    {
        AirplanesViewModel avm = new AirplanesViewModel
        {
            ConfigDate = DateTime.Now
        };
        return View(avm);
    }

    [HttpPost]
    [ActionName("Details")]
    public ActionResult Details_Post(AirplanesViewModel avm)
    {
        return RedirectToAction("Details", avm);
    }

    [HttpGet]
    public ActionResult Details(AirplanesViewModel avm)
    {
        int page = 0;
        int pageSize = 10;

        if (!ModelState.IsValid)
        {
            avm.Airplanes = new PaginatedList<Airplane>();
            return View(avm);
        }

        try
        {
            Query q = new Query(avm.Query);

            PaginatedList<Airplane> paginatedPlanes = new PaginatedList<Airplane>(repo.ByQuery(q), page, pageSize);

            avm.Airplanes = paginatedPlanes;

            return View(avm);
        }
        catch (Exception)
        {
            // Should log exception
            avm.Airplanes = new PaginatedList<Airplane>();
            return View(avm);
        }
    }
</code>```

Additional Information

It has something to do with the redirection to the GET Action.  When I take out the POST Action and remove the GET attribute (so both GET and POST use the Details() Action) the problem goes away - but this also gets rid of my pretty URL's when the form is submitted (and causes the annoying "are you sure?" popup on refresh).  Strangely, the only problem is the loss of formatting in that field.  Everything else is fine.

答:
While waiting for you to clearly specify the problem, here's a full working counter example that what you describe in your question doesn't actually happen:

Model:

```<code>public class MyViewModel
{
    [DisplayName("As Configured On:")]
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    public DateTime ConfigDate { get; set; }
}
</code>```

Controller:

```<code>public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            ConfigDate = DateTime.Now
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}
</code>```

View:

```<code><% using (Html.BeginForm()) { %>
    <%= Html.EditorFor(x => x.ConfigDate) %>
    <input type="submit" value="OK" />
<% } %>
</code>```

You can submit the form as much as you wish, the formatting will be preserved.

UPDATE:

After providing additional information here's why the problem occurs. When you redirect to the Details action with return RedirectToAction("Details", avm); a query string parameter is applied to the url:

```<code>http://localhost:1114/Airplanes/Details?ConfigDate=11/30/2010%2000:00:00
</code>```

Notice how the hour is included and that's normal. Now when you return the view in the Details GET action the HTML helper responsible for generating the editor template will do the following tasks:

Check to see whether there's a ConfigDate parameter (either GET or POST). If none was found check the value of the Model which is passed to the view and use the ConfigValue property of the model and generate the textbox.

As a ConfigValue is found in the query string the model is not used at all. So it simply takes the value passed in the redirect which also contains the time and uses it to bind to it.

Body:
I have a ViewModel with a property as below:

    [DisplayName("As Configured On:")]
    [DisplayFormat(DataFormatString="{0:d}", ApplyFormatInEditMode=true)]
    public DateTime ConfigDate { get; set; }

The Form that displays the ConfigDate is as below:

<%= Html.EditorFor(Model => Model.ConfigDate)%>

When the Index Action comes back, everything looks formatted correctly, i.e. the <input> box has the date value as 12/12/2001.  When the form is posted, the result that comes back is as though the DisplayFormat attribute isn't being applied.

EDIT:
More info was requested: here is the code en toto:

The Search Form

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Config.Web.Models.AirplanesViewModel>" %>
<% using (Html.BeginForm("Details", "Airplanes", FormMethod.Post, new { id = "SearchForm" })) { %>
<%= Html.LabelFor(model => model.ConfigDate) %>
<%= Html.EditorFor(Model => Model.ConfigDate)%>
<input id="searchButton" type="submit" value="Search" />
<% } %>

The AirplanesViewModel

    public class AirplanesViewModel
{
    [DisplayName("As Configured On:")]
    [DisplayFormat(DataFormatString="{0:d}", ApplyFormatInEditMode=true)]
    public DateTime ConfigDate { get; set; }
}
}

The Controller

        [HttpGet]
    public ActionResult Index()
    {
        AirplanesViewModel avm = new AirplanesViewModel
        {
            ConfigDate = DateTime.Now
        };
        return View(avm);
    }

    [HttpPost]
    [ActionName("Details")]
    public ActionResult Details_Post(AirplanesViewModel avm)
    {
        return RedirectToAction("Details", avm);
    }

    [HttpGet]
    public ActionResult Details(AirplanesViewModel avm)
    {
        int page = 0;
        int pageSize = 10;

        if (!ModelState.IsValid)
        {
            avm.Airplanes = new PaginatedList<Airplane>();
            return View(avm);
        }

        try
        {
            Query q = new Query(avm.Query);

            PaginatedList<Airplane> paginatedPlanes = new PaginatedList<Airplane>(repo.ByQuery(q), page, pageSize);

            avm.Airplanes = paginatedPlanes;

            return View(avm);
        }
        catch (Exception)
        {
            // Should log exception
            avm.Airplanes = new PaginatedList<Airplane>();
            return View(avm);
        }
    }

Additional Information

It has something to do with the redirection to the GET Action.  When I take out the POST Action and remove the GET attribute (so both GET and POST use the Details() Action) the problem goes away - but this also gets rid of my pretty URL's when the form is submitted (and causes the annoying "are you sure?" popup on refresh).  Strangely, the only problem is the loss of formatting in that field.  Everything else is fine.

Body:
While waiting for you to clearly specify the problem, here's a full working counter example that what you describe in your question doesn't actually happen:

Model:

public class MyViewModel
{
    [DisplayName("As Configured On:")]
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    public DateTime ConfigDate { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            ConfigDate = DateTime.Now
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View:

<% using (Html.BeginForm()) { %>
    <%= Html.EditorFor(x => x.ConfigDate) %>
    <input type="submit" value="OK" />
<% } %>

You can submit the form as much as you wish, the formatting will be preserved.

UPDATE:

After providing additional information here's why the problem occurs. When you redirect to the Details action with return RedirectToAction("Details", avm); a query string parameter is applied to the url:

http://localhost:1114/Airplanes/Details?ConfigDate=11/30/2010%2000:00:00

Notice how the hour is included and that's normal. Now when you return the view in the Details GET action the HTML helper responsible for generating the editor template will do the following tasks:

Check to see whether there's a ConfigDate parameter (either GET or POST). If none was found check the value of the Model which is passed to the view and use the ConfigValue property of the model and generate the textbox.

As a ConfigValue is found in the query string the model is not used at all. So it simply takes the value passed in the redirect which also contains the time and uses it to bind to it.


问:
inserting value in postgres custom-built type field using java api
I have a type as 'designation' in my postgreSQL DB instance.
I have a table named 'Prof' that has a column 'designation' of type 'designation'.
I want to insert values into this column using java.

code snippet:

```<code>insProf.setInt(1, id);
insProf.setInt(2, univ_id);
insProf.setString(3, desg);
int rs_insProf = insProf.executeUpdate();
</code>```

output error:

```<code>Enter designation: org.postgresql.util.PSQLException: ERROR: invalid input value for enum designation: ""
</code>```

Please help with with syntax, I am not able to figure out how best I can handle this.

答:
you can use setObject() and getObject() method.

https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#setObject(int,%20java.lang.Object)

take a look at the setObject() and getObject().

according to the documentation, "If the object is of a class implementing the interface SQLData, the JDBC driver should call the method SQLData.writeSQL to write it to the SQL data stream."

so you can create your own type by creating a custom class implementing SQLData interface.

plus, don't forget to register your custom type into the driver's type map.

there is a tutorial too: https://docs.oracle.com/javase/tutorial/jdbc/basics/sqlcustommapping.html

Body:
I have a type as 'designation' in my postgreSQL DB instance.
I have a table named 'Prof' that has a column 'designation' of type 'designation'.
I want to insert values into this column using java.

code snippet:

insProf.setInt(1, id);
insProf.setInt(2, univ_id);
insProf.setString(3, desg);
int rs_insProf = insProf.executeUpdate();

output error:

Enter designation: org.postgresql.util.PSQLException: ERROR: invalid input value for enum designation: ""

Please help with with syntax, I am not able to figure out how best I can handle this.


问:
Access denied error when curl'ing S3 object from pre-signed url
This is the script which I wrote for downloading object from S3 via a pre-signed url:

```<code>import boto3
import os

AWS_ACCESS_KEY_ID = '<>'
AWS_SECRET_ACCESS_KEY = '<>'
region = '<>'

session = boto3.Session(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, region_name = region)
s3 = session.client('s3')
url = s3.generate_presigned_url('get_object', Params = {'Bucket': '<>', 'Key': '<>.json'}, ExpiresIn = 100)

print url

os.system('curl ' + url)
</code>```

From this, I am able to get the url, but the os.system command is giving me the following error:

```<code><Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>...</RequestId><HostId>...</HostId></Error>
</code>```

But, when I directly try the url in my browser, it is downloading the file.

So, what did I do wrong here? How do I download the file via the Python script?

答:
Surround the url with quotes (") when making the curl request.

```<code>os.system('curl "'+ url + '"')
</code>```

To save it in a file, use

```<code>os.system('curl -o /tmp/file.txt "'+ url + '"')
</code>```

Or, Use the requests module to make the GET

```<code>import requests
response = requests.get(url)
</code>```

Body:
This is the script which I wrote for downloading object from S3 via a pre-signed url:

import boto3
import os

AWS_ACCESS_KEY_ID = '<>'
AWS_SECRET_ACCESS_KEY = '<>'
region = '<>'

session = boto3.Session(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, region_name = region)
s3 = session.client('s3')
url = s3.generate_presigned_url('get_object', Params = {'Bucket': '<>', 'Key': '<>.json'}, ExpiresIn = 100)

print url

os.system('curl ' + url)

From this, I am able to get the url, but the os.system command is giving me the following error:

<Error>AccessDenied<Message>Access Denied</Message><RequestId>...</RequestId><HostId>...</HostId></Error>

But, when I directly try the url in my browser, it is downloading the file.

So, what did I do wrong here? How do I download the file via the Python script?

Body:
Surround the url with quotes (") when making the curl request.

os.system('curl "'+ url + '"')

To save it in a file, use

os.system('curl -o /tmp/file.txt "'+ url + '"')

Or, Use the requests module to make the GET

import requests
response = requests.get(url)


问:
Why doesn't the value change in Java
I just thought of this question: Using Java

```<code>int x = 1
int y = x;
x = 5;
</code>```

why doesn't y = 5 now?

答:
Because y is a separate variable to x, albeit initialised with the original value of x.

y is not a reference to x, or a reference to the same object as x. (int is a primitive type in Java).

Title: Why doesn't the value change in Java

Body:
I just thought of this question: Using Java

int x = 1
int y = x;
x = 5;

why doesn't y = 5 now?


问:
Find and replace in a loop using macro in Excel
I have two sheets. Sheet 1 contains the following data

Sheet 1:

```<code>Column 1  column 2
Hotel A   New York
Hotel B   Melbourne
</code>```

And I wish to replace the value in sheet 2 with this value

Sheet 2 is like that :

```<code>Column 1    Column 2   Column 3

Name        ....        .....
.....       ....        City
....        ....        ....
Name        ....        .....
....        .....       City
</code>```

My ideal output will be :

```<code>Column1     Column 2    Column 3

Hotel A     ....        .....
.....       ....        New York
....        ....        ....
Hotel B     ....        .....
....        ....        Melbourne
</code>```

So, I wish to go through a loop in sheet 1 and read the name and city of hotels and go to sheet 2 and find the words Name and City and replace them with what I read in sheet 1. I'm very new in VBA and started my code like that and it even goes to loop. Why is it so?

```<code>Sub testLoopPaste()
   Dim j, k, L, b As String
   Dim i As Long
   Dim wb As Workbook
   Dim sht1 As Worksheet
   Dim sht2 As Worksheet

  Set wb = ThisWorkbook
  Set sht1 = wb.Sheets("Sheet1")
  Set sht2 = wb.Sheets("Sheet2")

   j = "Name"
   b = "City"

   For i = 1 To 2

    k = sht1.Range("A" & i)
    L = sht1.Range("B" & i)

    sht2.Cells.Replace what:=j, replacement:=k, lookat:=xlWhole, MatchCase:=False
    sht2.Cells.Replace what:=b, replacement:=L, lookat:=xlWhole, MatchCase:=False

  Next i

 End Sub
</code>```

Any tips or guidance is appreciated.

答:
This should work.  The loop searches for each Name and City in sht1 and replaces the first occurrence in columns "A" and "C" of sht2:</p>

```<code>Sub testLoopPaste()
  Dim i As Long
  Dim wb As Workbook
  Dim sht1 As Worksheet, sht2 As Worksheet

  Set wb = ThisWorkbook
  Set sht1 = wb.Sheets("Sheet1")
  Set sht2 = wb.Sheets("Sheet2")

  Dim Loc As Range
  For i = 1 To sht1.Range("A" & sht1.Rows.Count).End(xlUp).row
   Set Loc = sht2.Columns(1).Find(What:="Name")
   If Not Loc Is Nothing Then Loc.Value = sht1.Cells(i, "A")
   Set Loc = sht2.Columns(3).Find(What:="City")
   If Not Loc Is Nothing Then Loc.Value = sht1.Cells(i, "B")
  Next i

End Sub
</code>```

Body:
I have two sheets. Sheet 1 contains the following data

Sheet 1:

Column 1  column 2
Hotel A   New York
Hotel B   Melbourne

And I wish to replace the value in sheet 2 with this value

Sheet 2 is like that :

Column 1    Column 2   Column 3

Name        ....        .....
.....       ....        City
....        ....        ....
Name        ....        .....
....        .....       City

My ideal output will be :

Column1     Column 2    Column 3

Hotel A     ....        .....
.....       ....        New York
....        ....        ....
Hotel B     ....        .....
....        ....        Melbourne

So, I wish to go through a loop in sheet 1 and read the name and city of hotels and go to sheet 2 and find the words Name and City and replace them with what I read in sheet 1. I'm very new in VBA and started my code like that and it even goes to loop. Why is it so?

Sub testLoopPaste()
   Dim j, k, L, b As String
   Dim i As Long
   Dim wb As Workbook
   Dim sht1 As Worksheet
   Dim sht2 As Worksheet

  Set wb = ThisWorkbook
  Set sht1 = wb.Sheets("Sheet1")
  Set sht2 = wb.Sheets("Sheet2")

   j = "Name"
   b = "City"

   For i = 1 To 2

    k = sht1.Range("A" & i)
    L = sht1.Range("B" & i)

    sht2.Cells.Replace what:=j, replacement:=k, lookat:=xlWhole, MatchCase:=False
    sht2.Cells.Replace what:=b, replacement:=L, lookat:=xlWhole, MatchCase:=False

  Next i

 End Sub

Any tips or guidance is appreciated.

Body:
This should work.  The loop searches for each Name and City in sht1 and replaces the first occurrence in columns "A" and "C" of sht2:

Sub testLoopPaste()
  Dim i As Long
  Dim wb As Workbook
  Dim sht1 As Worksheet, sht2 As Worksheet

  Set wb = ThisWorkbook
  Set sht1 = wb.Sheets("Sheet1")
  Set sht2 = wb.Sheets("Sheet2")

  Dim Loc As Range
  For i = 1 To sht1.Range("A" & sht1.Rows.Count).End(xlUp).row
   Set Loc = sht2.Columns(1).Find(What:="Name")
   If Not Loc Is Nothing Then Loc.Value = sht1.Cells(i, "A")
   Set Loc = sht2.Columns(3).Find(What:="City")
   If Not Loc Is Nothing Then Loc.Value = sht1.Cells(i, "B")
  Next i

End Sub


问:
Amp XHR Form Pages Redirect
I created amp form.
When I click on Butona, I check the values in the form from different pages.
I have no problems here.
If all the data is correct I want to direct a unique adrese.
How can I direct the visitor when the form is positive?

```<code> <script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>
 <script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.1.js"></script>

<form method="POST" action-xhr="//example.com/control" target="_top">
<input type="checkbox" name="items[]" value="1" />
<input type="checkbox" name="items[]" value="2" />
<input type="checkbox" name="items[]" value="3" />
...
<button type="submit" class="btn">Check and go</button>
<div submit-success>
   <template type="amp-mustache">
       {{message}}
   </template>
</div>
<div submit-error>
   <template type="amp-mustache">
       {{message}}
   </template>
</div>
</form>
</code>```

I am showing the requests coming with Json in the variable named message.
I want to forward a different address instead of showing the last message. Is this possible with AMP?

答:
Instead of using

```<code>action-xhr="//example.com/control"
</code>```

Use

```<code>action="//example.com/control"
</code>```

And let the URL (//example.com/control) redirect the user

Title: Amp XHR Form Pages Redirect

Body:
I created amp form.
When I click on Butona, I check the values in the form from different pages.
I have no problems here.
If all the data is correct I want to direct a unique adrese.
How can I direct the visitor when the form is positive?

<form method="POST" action-xhr="//example.com/control" target="_top">
<input type="checkbox" name="items[]" value="1" />
<input type="checkbox" name="items[]" value="2" />
<input type="checkbox" name="items[]" value="3" />
...
<button type="submit" class="btn">Check and go</button>

   <template type="amp-mustache">
       {{message}}
   </template>

   <template type="amp-mustache">
       {{message}}
   </template>

</form>

I am showing the requests coming with Json in the variable named message.
I want to forward a different address instead of showing the last message. Is this possible with AMP?

Body:
Instead of using

action-xhr="//example.com/control"

Use

action="//example.com/control"

And let the URL (//example.com/control) redirect the user


问:
Get string array from Pymongo query
I need to get an array with the values from the field 'colname'. I can't return a Cursor, just the array of values.

Is there a way to query this array without having to loop the Cursor? I feel this is a waste of processing resources.

Right now I'm doing this:

```<code>from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
headers = client['headers']

entomo = headers.entomo

entomo_data = entomo.find()
entomo_array = []
for data in entomo_data:
    entomo_array.append(data['colname'])
</code>```

Then I return the entomo_array.

答:
You can do this with the .aggregate() method by $grouping your documents by None

```<code>cursor = entomo.aggregate([
    {'$group': {
        '_id': None,
        'data': {'$push': '$colname'}
    }}
])
</code>```

From there, you simply consume the cursor using next.

```<code>entomo_array = next(cursor)['data']
</code>```

But if 'colname' is unique within the collection, you can simply use the the distinct method.

```<code>entomo_array = entomo.distinct('colname')
</code>```

Title: Get string array from Pymongo query

Body:
I need to get an array with the values from the field 'colname'. I can't return a Cursor, just the array of values.

Is there a way to query this array without having to loop the Cursor? I feel this is a waste of processing resources.

Right now I'm doing this:

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
headers = client['headers']

entomo = headers.entomo

entomo_data = entomo.find()
entomo_array = []
for data in entomo_data:
    entomo_array.append(data['colname'])

Then I return the entomo_array.

Body:
You can do this with the .aggregate() method by $grouping your documents by None

cursor = entomo.aggregate([
    {'$group': {
        '_id': None,
        'data': {'$push': '$colname'}
    }}
])

From there, you simply consume the cursor using next.

entomo_array = next(cursor)['data']

But if 'colname' is unique within the collection, you can simply use the the distinct method.

entomo_array = entomo.distinct('colname')


答:
```<code>int x = 1
int y = x;
x = 5;
</code>```

primitive value is copied on this line int y=x; This is not copy of reference of an object which x is pointing to.

For reference :
http://javarevisited.blogspot.hk/2015/09/difference-between-primitive-and-reference-variable-java.html
Is Java "pass-by-reference" or "pass-by-value"?

Title: Why doesn't the value change in Java

Body:
int x = 1
int y = x;
x = 5;

primitive value is copied on this line int y=x; This is not copy of reference of an object which x is pointing to.

For reference :
http://javarevisited.blogspot.hk/2015/09/difference-between-primitive-and-reference-variable-java.html
Is Java "pass-by-reference" or "pass-by-value"?


问:
Order of arguments and pipe-right operator
Is there a way to simplify the following, so I won't need a runWithTimeout function?

```<code>let runWithTimeout timeout computation =
   Async.RunSynchronously(computation, timeout)

let processOneItem item =  fetchAction item
                           |> runWithTimeout 2000
</code>```

Edit:
Here's why i needed the extra method:

```<code>let processOneItem item =  fetchAction item
                           |> Async.Catch
                           |> runWithTimeout 2000
                           |> handleExceptions
</code>```

答:
Perhaps you mean something like this:</p>

```<code>let processOneItem item =
  fetchAction item
  |> fun x -> Async.RunSynchronously(x, 2000)
</code>```

Body:
Is there a way to simplify the following, so I won't need a runWithTimeout function?

let runWithTimeout timeout computation =
   Async.RunSynchronously(computation, timeout)

let processOneItem item =  fetchAction item
                           |> runWithTimeout 2000

Edit:
Here's why i needed the extra method:

let processOneItem item =  fetchAction item
                           |> Async.Catch
                           |> runWithTimeout 2000
                           |> handleExceptions

Body:
Perhaps you mean something like this:

let processOneItem item =
  fetchAction item
  |> fun x -> Async.RunSynchronously(x, 2000)


问:
Protractor element not clickable at some point? But same element receiving its click event?
I am doing end to end testing using protractor. I am getting an error like

```<code>Failed: unknown error: Element
<button type="button" ng-click="onGPlusBtnPress()" class="btn btn-lg
btn-google btn-block">...</button>
is not clickable at point (919, 241). Other element would receive
the click:
<button type="button" ng-click="onGPlusBtnPress()" class="btn btn-lg
btn-google btn-block">...</button>
</code>```

It seems that the error is telling that same element is receiving click event, then why it is not working. there are no other clickable elements overlapping on it.

What should be done to resolve the problem?

see web page design here

答:
Try by adding window size in your config file.

```<code>onPrepare: function() {
  browser.manage().window().setSize(1600, 800);
}
</code>```

if it still doesn't work try it.

```<code>browser.actions().mouseMove(element).click();
</code>```

Body:
I am doing end to end testing using protractor. I am getting an error like

Failed: unknown error: Element
<button type="button" ng-click="onGPlusBtnPress()" class="btn btn-lg
btn-google btn-block">...</button>
is not clickable at point (919, 241). Other element would receive
the click:
<button type="button" ng-click="onGPlusBtnPress()" class="btn btn-lg
btn-google btn-block">...</button>

It seems that the error is telling that same element is receiving click event, then why it is not working. there are no other clickable elements overlapping on it.

What should be done to resolve the problem?

see web page design here

Body:
Try by adding window size in your config file.

onPrepare: function() {
  browser.manage().window().setSize(1600, 800);
}

if it still doesn't work try it.

browser.actions().mouseMove(element).click();


问:
search 2 fields in a file in another huge file, passing 2nd file only once
file1 has 100,000 lines. Each line has 2 fields such as:

```<code>test 12345678
test2 43213423
</code>```

Another file has millions of lines.  Here is an example of how the above file entries look in file2:

```<code>'99' 'databases' '**test**' '**12345678**'
'1002' 'exchange' '**test2**' '**43213423**'
</code>```

I would like a way to grep these 2 fields from file1 so that I can find any line that contains both, but the gotcha is, I would like to search the 100,000 entries through the 2nd file once as looping a grep is very slow as it could loop 100,000 x 10,000,000.

Is that at all possible?

答:
fgrep and sed method:

```<code>sed "s/\b/'/g;s/\b/**/g" file1 | fgrep -f - file2
</code>```

Modify a stream from file1 with sed to match the format of the second file, (i.e. surround the fields with single quotes and asterisks), and send the stream to standard output.  The fgrep -f - inputs that stream as a list of fixed strings (but no regexps) and finds every matching line in file2.

Output:

```<code>'99' 'databases' '**test**' '**12345678**'
'1002' 'exchange' '**test2**' '**43213423**'
</code>```

Body:
file1 has 100,000 lines. Each line has 2 fields such as:

test 12345678
test2 43213423

Another file has millions of lines.  Here is an example of how the above file entries look in file2:

'99' 'databases' '**test**' '**12345678**'
'1002' 'exchange' '**test2**' '**43213423**'

I would like a way to grep these 2 fields from file1 so that I can find any line that contains both, but the gotcha is, I would like to search the 100,000 entries through the 2nd file once as looping a grep is very slow as it could loop 100,000 x 10,000,000.

Is that at all possible?

Body:
fgrep and sed method:

sed "s/\b/'/g;s/\b/**/g" file1 | fgrep -f - file2

Modify a stream from file1 with sed to match the format of the second file, (i.e. surround the fields with single quotes and asterisks), and send the stream to standard output.  The fgrep -f - inputs that stream as a list of fixed strings (but no regexps) and finds every matching line in file2.

Output:

'99' 'databases' '**test**' '**12345678**'
'1002' 'exchange' '**test2**' '**43213423**'


问:
Unable to find a specification for 'Firebase' (IOS Swift)
I am adding cocoa pods to my ios project (swift).
I have initalized the pods in the project directory using 'pod init myproject.xcodeproj'. I then added pod 'Firebase' to the Podfile as such:

```<code>project 'HOTS IOS.xcodeproj/'

platform : ios, '9.0'

target 'HOTS IOS' do

  use_frameworks!

  pod 'Firebase'

  target 'HOTS IOSTests' do
    inherit! :search_paths
    pod 'Firebase'
  end

  target 'HOTS IOSUITests' do
    inherit! :search_paths
    pod 'Firebase'
  end

end
</code>```

Now when I run pod install i get the error: Unable to find a specification for 'Firebase'.

答:
Depending on what Firebase service you want to use you have to add different Firebase services in your podfile. "'Firebase'" is not a valid pod.

pod 'Firebase/Core' is the most basic and will give you the prerequisite libraries needed to get Firebase running. If you want to use other services you can choose between these pods:

pod 'Firebase/Core' --> Prerequisite libraries and Analytics

pod 'Firebase/AdMob' --> AdMob

pod 'Firebase/Messaging' --> Cloud Messaging / Notifications

pod 'Firebase/Database' --> Realtime Database

pod 'Firebase/Invites' --> Invites

pod 'Firebase/DynamicLinks' --> Dynamic Links

pod 'Firebase/Crash' --> Crash Reporting

pod 'Firebase/RemoteConfig' --> Remote Config

pod 'Firebase/Auth' --> Authentication

pod 'Firebase/Storage' --> Storage

(Note: without --> text. Only add for example pod 'Firebase/Database')

Here is the documentation for setting up iOS:

https://firebase.google.com/docs/ios/setup

Body:
I am adding cocoa pods to my ios project (swift).
I have initalized the pods in the project directory using 'pod init myproject.xcodeproj'. I then added pod 'Firebase' to the Podfile as such:

project 'HOTS IOS.xcodeproj/'

platform : ios, '9.0'

target 'HOTS IOS' do

  use_frameworks!

  pod 'Firebase'

  target 'HOTS IOSTests' do
    inherit! :search_paths
    pod 'Firebase'
  end

  target 'HOTS IOSUITests' do
    inherit! :search_paths
    pod 'Firebase'
  end

end

Now when I run pod install i get the error: Unable to find a specification for 'Firebase'.


问:
UITextField, text jumps down slightly when editing begins
I'm having an odd issue here. I have UITextFields in my table cells. When I select the field the text jumps very slightly down:

The font is system default 17. I have adjust to fit turned on at size 17. I have tried turning off adjust to fit and there is still a jump. I have tried using different border styles and this also makes no difference. I have tried turning off clip to bounds, it still jumps. I have also tried making the frame taller (much taller) and it still jumps. The only thing that works is if I make the font size much smaller eg 13. What am I doing wrong here? If I can make the font smaller to fix the jump then why doesn't making the frame bigger work? Any pointers on this would be really appreciated. Thanks!

答:
You can try to increase the height of inputView in UITextField.

UITextField has inputView that will present when object becomes first responder.


问:
Better SQL Replace
I wanted to know if there is a better way of writing this Update.

```<code>update Alumni_Export_New
set phone = replace(replace(replace(replace(phone,'-',''),' ',''),')',''),'(','')
from tbl
</code>```

I have a stored procedure in MSSQL 2005 to clean the phone field in a table and thought there should be a better way of doing this then what I have.

答: Assuming this is for MySQL, I don't think there is an alternative to the REPLACE() function for multiple arguments (such as TRANSLATE() in other dbs).</p>

Title: Better SQL Replace

Body:
I wanted to know if there is a better way of writing this Update.

update Alumni_Export_New
set phone = replace(replace(replace(replace(phone,'-',''),' ',''),')',''),'(','')
from tbl

I have a stored procedure in MSSQL 2005 to clean the phone field in a table and thought there should be a better way of doing this then what I have.


问:
Deleted /etc/shadow file on Gnome ubuntu 15.04
I was going through my network security notes and fiddling through my system .

Accidentally, I deleted my /etc/shadow file ( file that store encrypted value of /etc/passwd ). Currently, I am on my system as I can't logout ( if I do I will loose it forever).
So now I have /etc/shadow- and /etc/passwd on my system. Can anyone tell me how to generate or get my shadow file back. I don't want to delete this OS.

I have looked for its answer on stackoverflow or other ubuntu forum nothing has came close to solve this issue.

答: Due to exam pressure , unable to think how to respond to this issue. But if any one get struck with Ubuntu system file failure or accidental deletion. Just boot an OS through pendrive and move the file to desired location, which I did. If you have dual boot, problem more easier to solve as just go to other OS access your hard drive and make necessary changes.</p>


问:
How to use a calculated column to calculate another column in the same view
I am hoping you can help with this question.  I am using Oracle SQL (SQL Developer for this view)...

If I have a table with the following columns:

ColumnA (Number)

ColumnB (Number)

ColumnC (Number)

In my view I have

```<code>Select
ColumnA,
ColumnB,
ColumnA + ColumnB As calccolumn1
</code>```

Now at this point, I want to use calccolumn1
but I cannot just say...

```<code>Select
ColumnA,
ColumnB,
ColumnA + ColumnB As calccolumn1
calccolumn1 / ColumnC as calccolumn2
</code>```

I am assuming I need some type of subquery..but this is where I need your help...
How would I word the query so that I can use calccolumn1 in another calculation within the same query?  It might be an If then or a Case when, but bottomline it is some derived number.

答:
In Sql Server

You can do this using cross apply

```<code>Select
  ColumnA,
  ColumnB,
  c.calccolumn1 As calccolumn1,
  c.calccolumn1 / ColumnC As calccolumn2
from t42
cross apply (select (ColumnA + ColumnB) as calccolumn1) as c
</code>```

Body:
I am hoping you can help with this question.  I am using Oracle SQL (SQL Developer for this view)...

If I have a table with the following columns:

ColumnA (Number)

ColumnB (Number)

ColumnC (Number)

In my view I have

Select
ColumnA,
ColumnB,
ColumnA + ColumnB As calccolumn1

Now at this point, I want to use calccolumn1
but I cannot just say...

Select
ColumnA,
ColumnB,
ColumnA + ColumnB As calccolumn1
calccolumn1 / ColumnC as calccolumn2

I am assuming I need some type of subquery..but this is where I need your help...
How would I word the query so that I can use calccolumn1 in another calculation within the same query?  It might be an If then or a Case when, but bottomline it is some derived number.

Body:
In Sql Server

You can do this using cross apply

Select
  ColumnA,
  ColumnB,
  c.calccolumn1 As calccolumn1,
  c.calccolumn1 / ColumnC As calccolumn2
from t42
cross apply (select (ColumnA + ColumnB) as calccolumn1) as c


问:
I'm using SOLR 6.1.0 and would like to understand how to extract a particular portion of a document to show as result
I'm using SOLR 6.1.0 and would like to understand how to extract a particular portion of a document (Word and PDF) to show as result.</p>

答:
Highlighting in Solr allows fragments of documents that match the user's query to be included with the query response. The fragments are included in a special section of the response (the highlighting section), and the client uses the formatting clues also included to determine how to present the snippets to users.

For more info please check Highlighting in solr


问:
laravel Echo does not listen to channel and events
To broadcast an event on a channel I used laravel Echo , redis and socket-io.

this is my event :

```<code>    class ChatNewMessage implements ShouldBroadcast
    {
        use InteractsWithSockets, SerializesModels;

        public $targetUsers;
        public $message;

        public function __construct ($message)
        {
            $this->targetUsers = $message->chat->users->pluck('user_id');
            $this->message     = $message;
        }

        public function broadcastOn ()
        {
            $userChannels = [];
            foreach ($this->targetUsers as $id) {
                $userChannels[] = 'user-channel.' . $id;
            }
            return $userChannels;

        }

        public function broadcastAs()
        {
            return 'NewMessage';
        }

    }
</code>```

For Socket.io server I'm using laravel-echo-server and below is configuration:

```<code>{
    "authHost": "http://api.pars-app.dev",
    "authEndpoint": "/broadcasting/auth",
    "clients": [
        {
            "appId": "1924bf1d59b3759d",
            "key": "eaf9e3c843493421f4be488fba11f49d"
        }
    ],
    "database": "redis",
    "databaseConfig": {
        "redis": {},
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": "127.0.0.1",
    "port": "3000",
    "protocol": "http",
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": ""
}
</code>```

And this is Echo structure in bootstrap.js file :

```<code>import Echo from "laravel-echo";
window.echo = new Echo({
    broadcaster: 'socket.io',
    host: 'http://127.0.0.1:3000',
    auth: {
        headers: {
            Authorization: 'bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjUsImlzcyI6Imh0dHA6XC9cL2FwaS5wYXJzLWFwcC5kZXZcL3YxXC9hdXRoXC9zaWduSW4iLCJpYXQiOjE0ODkzMTY1ODgsImV4cCI6MTQ5MTkwNDk4OCwibmJmIjoxNDg5MzE2NTg4LCJqdGkiOiIwNzdiN2NjYjNlODE4MDU2NjBiMWNjYTkzZjI1ZTZmMyJ9.Y_BvVnJIq8k3uN1sQQuBna1CcLsrn7VnpH3RxXS8JEQ'
        }
    }
});
echo.channel('user-channel.5').listen('NewMessage', (e) => {
    console.log(e);
});
</code>```

After running laravel-echo-server and call event, below logs show in console that shows event broadcasts to channel :

```<code>[2:26:05 PM] - Xt_VSaSRHirHHxtUAAAE left channel: user-channel.5 (transport close)
[2:26:06 PM] - FwfOFMZqfrI9_H11AAAF joined channel: user-channel.5
Channel: user-channel.2
Event: NewMessage
CHANNEL user-channel.2
Channel: user-channel.1
Event: NewMessage
CHANNEL user-channel.1
Channel: user-channel.5
Event: NewMessage
CHANNEL user-channel.5
</code>```

But Echo could not listen to channels and occurred events.

What is problem?

答:
I found the solution.

According to this comment on laravel-echo-server github page,The event name needs to be prefixed with a dot. like this :

```<code>echo.channel('user-channel.5').listen('.NewMessage', (e) => {
    console.log(e);
});
</code>```

Body:
To broadcast an event on a channel I used laravel Echo , redis and socket-io.

this is my event :

    class ChatNewMessage implements ShouldBroadcast
    {
        use InteractsWithSockets, SerializesModels;

        public $targetUsers;
        public $message;

        public function __construct ($message)
        {
            $this->targetUsers = $message->chat->users->pluck('user_id');
            $this->message     = $message;
        }

        public function broadcastOn ()
        {
            $userChannels = [];
            foreach ($this->targetUsers as $id) {
                $userChannels[] = 'user-channel.' . $id;
            }
            return $userChannels;

        }

        public function broadcastAs()
        {
            return 'NewMessage';
        }

    }

For Socket.io server I'm using laravel-echo-server and below is configuration:

{
    "authHost": "http://api.pars-app.dev",
    "authEndpoint": "/broadcasting/auth",
    "clients": [
        {
            "appId": "1924bf1d59b3759d",
            "key": "eaf9e3c843493421f4be488fba11f49d"
        }
    ],
    "database": "redis",
    "databaseConfig": {
        "redis": {},
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": "127.0.0.1",
    "port": "3000",
    "protocol": "http",
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": ""
}

And this is Echo structure in bootstrap.js file :

import Echo from "laravel-echo";
window.echo = new Echo({
    broadcaster: 'socket.io',
    host: 'http://127.0.0.1:3000',
    auth: {
        headers: {
            Authorization: 'bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjUsImlzcyI6Imh0dHA6XC9cL2FwaS5wYXJzLWFwcC5kZXZcL3YxXC9hdXRoXC9zaWduSW4iLCJpYXQiOjE0ODkzMTY1ODgsImV4cCI6MTQ5MTkwNDk4OCwibmJmIjoxNDg5MzE2NTg4LCJqdGkiOiIwNzdiN2NjYjNlODE4MDU2NjBiMWNjYTkzZjI1ZTZmMyJ9.Y_BvVnJIq8k3uN1sQQuBna1CcLsrn7VnpH3RxXS8JEQ'
        }
    }
});
echo.channel('user-channel.5').listen('NewMessage', (e) => {
    console.log(e);
});

After running laravel-echo-server and call event, below logs show in console that shows event broadcasts to channel :

[2:26:05 PM] - Xt_VSaSRHirHHxtUAAAE left channel: user-channel.5 (transport close)
[2:26:06 PM] - FwfOFMZqfrI9_H11AAAF joined channel: user-channel.5
Channel: user-channel.2
Event: NewMessage
CHANNEL user-channel.2
Channel: user-channel.1
Event: NewMessage
CHANNEL user-channel.1
Channel: user-channel.5
Event: NewMessage
CHANNEL user-channel.5

But Echo could not listen to channels and occurred events.

What is problem?

Body:
I found the solution.

According to this comment on laravel-echo-server github page,The event name needs to be prefixed with a dot. like this :

echo.channel('user-channel.5').listen('.NewMessage', (e) => {
    console.log(e);
});


问:
Swipe card view undo card item in Android
I need some help. I am using  swipe card library like Tinder app in Android and I am removing the cards by using cross button and Now I want undo options also on the click of back option. Can anyone please tell me what is the method used for that ? I really appreciate that.
Thanks!</p>

答:
I assume that you have implemented an ÌtemTouchHelper.SimpleCallback interface to control the swiping. I've included an example of such an implementation below:

```<code>ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {

                final int adapterPosition = viewHolder.getAdapterPosition();
                final Task taskItem = tasks.remove(adapterPosition); //tasks is an ArrayList of data that populates the RecyclerView. This line deletes an element from the ArrayList, but at the same time saves it in a variable.
                adapter.notifyItemRemoved(viewHolder.getAdapterPosition()); //adapter represents my adapter class.

                Snackbar snackbar = Snackbar    //assuming that a Snackbar with "UNDO" button is what you want.
                        .make(rvTasks, "Item removed", Snackbar.LENGTH_LONG)
                        .setAction("Undo", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //this happens when "Undo" is clicked.
                                tasks.add(adapterPosition, taskItem);
                                adapter.notifyItemInserted(adapterPosition);
                                rvTasks.scrollToPosition(adapterPosition);
                            }
                        });
                snackbar.show();
            }

            @Override
            public void onMoved(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, int fromPos, RecyclerView.ViewHolder target, int toPos, int x, int y) {
                super.onMoved(recyclerView, viewHolder, fromPos, target, toPos, x, y);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }
        };

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
        itemTouchHelper.attachToRecyclerView(rvTasks);
</code>```

Sequence:

```<code>final int adapterPosition = viewHolder.getAdapterPosition();
//saves the position of card/item in case we want to reinstate it.
final Task taskItem = tasks.remove(adapterPosition);
//deletes an element from the ArrayList, but at the same time saves it in a variable.
adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
//adapter is notified that item is removed and thus removed from view.
</code>```

then,

```<code>Snackbar.make(... details omitted ...) //remember to add in your build.gradle: compile 'com.android.support:design:25.3.1'
tasks.add(adapterPosition, taskItem); //deleted element readded to ArrayList
adapter.notifyItemInserted(adapterPosition); //adapter notified of reinstated item
rvTasks.scrollToPosition(adapterPosition); //auto-scrolls to position where item is reinstated
</code>```

Body:
I assume that you have implemented an ÌtemTouchHelper.SimpleCallback interface to control the swiping. I've included an example of such an implementation below:

ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {

                final int adapterPosition = viewHolder.getAdapterPosition();
                final Task taskItem = tasks.remove(adapterPosition); //tasks is an ArrayList of data that populates the RecyclerView. This line deletes an element from the ArrayList, but at the same time saves it in a variable.
                adapter.notifyItemRemoved(viewHolder.getAdapterPosition()); //adapter represents my adapter class.

                Snackbar snackbar = Snackbar    //assuming that a Snackbar with "UNDO" button is what you want.
                        .make(rvTasks, "Item removed", Snackbar.LENGTH_LONG)
                        .setAction("Undo", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //this happens when "Undo" is clicked.
                                tasks.add(adapterPosition, taskItem);
                                adapter.notifyItemInserted(adapterPosition);
                                rvTasks.scrollToPosition(adapterPosition);
                            }
                        });
                snackbar.show();
            }

            @Override
            public void onMoved(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, int fromPos, RecyclerView.ViewHolder target, int toPos, int x, int y) {
                super.onMoved(recyclerView, viewHolder, fromPos, target, toPos, x, y);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }
        };

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
        itemTouchHelper.attachToRecyclerView(rvTasks);

Sequence:

final int adapterPosition = viewHolder.getAdapterPosition();
//saves the position of card/item in case we want to reinstate it.
final Task taskItem = tasks.remove(adapterPosition);
//deletes an element from the ArrayList, but at the same time saves it in a variable.
adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
//adapter is notified that item is removed and thus removed from view.

then,

Snackbar.make(... details omitted ...) //remember to add in your build.gradle: compile 'com.android.support:design:25.3.1'
tasks.add(adapterPosition, taskItem); //deleted element readded to ArrayList
adapter.notifyItemInserted(adapterPosition); //adapter notified of reinstated item
rvTasks.scrollToPosition(adapterPosition); //auto-scrolls to position where item is reinstated


问:
56 Received HTTP code 403 from proxy after CONNECT?
I am getting an "56 Received HTTP code 403 from proxy after CONNECT" Error while generating a lead to salesforce using cUrl from my web page. SSL certificate of the site is already expired.

UPDATED:

my code is as follows:

```<code>  curl_setopt($curl, CURLOPT_URL, $_url);
  curl_setopt($curl, CURLOPT_POST, count($field));
  curl_setopt($curl, CURLOPT_POSTFIELDS, $query_data);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_HEADER, 1);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  curl_setopt($curl, CURLOPT_USERAGENT, "cusom module");
</code>```

答:
Add

```<code>AllowCONNECT port[-port] [port[-port]] ...
</code>```

below ProxyRequests On in httpd_proxy.conf of apache proxy

eg:

```<code>ProxyRequests On
AllowCONNECT 443 563 5000
</code>```

5000 is port of destination address.

Body:
I am getting an "56 Received HTTP code 403 from proxy after CONNECT" Error while generating a lead to salesforce using cUrl from my web page. SSL certificate of the site is already expired.

UPDATED:

my code is as follows:

  curl_setopt($curl, CURLOPT_URL, $_url);
  curl_setopt($curl, CURLOPT_POST, count($field));
  curl_setopt($curl, CURLOPT_POSTFIELDS, $query_data);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_HEADER, 1);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  curl_setopt($curl, CURLOPT_USERAGENT, "cusom module");

Body:
Add

AllowCONNECT port[-port] [port[-port]] ...

below ProxyRequests On in httpd_proxy.conf of apache proxy

eg:

ProxyRequests On
AllowCONNECT 443 563 5000

5000 is port of destination address.


问:
inserting value in postgres custom-built type field using java api
I have a type as 'designation' in my postgreSQL DB instance.
I have a table named 'Prof' that has a column 'designation' of type 'designation'.
I want to insert values into this column using java.

code snippet:

```<code>insProf.setInt(1, id);
insProf.setInt(2, univ_id);
insProf.setString(3, desg);
int rs_insProf = insProf.executeUpdate();
</code>```

output error:

```<code>Enter designation: org.postgresql.util.PSQLException: ERROR: invalid input value for enum designation: ""
</code>```

Please help with with syntax, I am not able to figure out how best I can handle this.

答:
To insert an enum, you have to use this syntax:

```<code>INSERT INTO Prof (id, unit_id, designation) VALUES(?, ?, {?, ?, ?});
//-------------------------------------------------------^-------^
</code>```

Or

You can use an array in your case of type designation like this :

```<code>INSERT INTO Prof (id, unit_id, designation) VALUES(?, ?, ARRAY[?]::designation[]);
//-------------------------------------------------------------^
</code>```

To set multiple you can use a loop for example to fill your enum, if you have more then one enum.

Body:
I have a type as 'designation' in my postgreSQL DB instance.
I have a table named 'Prof' that has a column 'designation' of type 'designation'.
I want to insert values into this column using java.

code snippet:

insProf.setInt(1, id);
insProf.setInt(2, univ_id);
insProf.setString(3, desg);
int rs_insProf = insProf.executeUpdate();

output error:

Enter designation: org.postgresql.util.PSQLException: ERROR: invalid input value for enum designation: ""

Please help with with syntax, I am not able to figure out how best I can handle this.

Body:
To insert an enum, you have to use this syntax:

INSERT INTO Prof (id, unit_id, designation) VALUES(?, ?, {?, ?, ?});
//-------------------------------------------------------^-------^

Or

You can use an array in your case of type designation like this :

INSERT INTO Prof (id, unit_id, designation) VALUES(?, ?, ARRAY[?]::designation[]);
//-------------------------------------------------------------^

To set multiple you can use a loop for example to fill your enum, if you have more then one enum.