答:
If the ID:s for a pair always match the formula x and x+1, you could say something like

```<code>WHERE MOD(`id`, 2) = 1
</code>```

EDIT: I haven't tested this code, so I can't guarantee that it's possible to put a column name into a MOD like this, but it might be worth a try, and/or further investigation.

Title: Table has pairs of matching records, need to select and update only one record

Body:
I have a table with pairs of matching records that I query like this:

select id,name,amount,type from accounting_entries
  where name like "%05" and amount != 0 order by name limit 10;

Results:

+------+----------------------+--------+-------+
| id   | name                 | amount | type  |
+------+----------------------+--------+-------+
|  786 | D-1194-838HELLUJP-05 |  -5800 | DEBIT |
|  785 | D-1194-838HELLUJP-05 |  -5800 | DEBIT |
| 5060 | D-1195-UOK4HS5POF-05 |  -5000 | DEBIT |
| 5059 | D-1195-UOK4HS5POF-05 |  -5000 | DEBIT |
|  246 | D-1196-0FUCJI66BX-05 |  -7000 | DEBIT |
|  245 | D-1196-0FUCJI66BX-05 |  -7000 | DEBIT |
| 9720 | D-1197-W2J0EC1BOB-05 |  -6500 | DEBIT |
| 9719 | D-1197-W2J0EC1BOB-05 |  -6500 | DEBIT |
| 2694 | D-1198-MFKIKHGW0S-05 |  -5500 | DEBIT |
| 2693 | D-1198-MFKIKHGW0S-05 |  -5500 | DEBIT |
+------+----------------------+--------+-------+
10 rows in set (0.01 sec)

I need to perform an update so that the resulting data will look like this:

+------+----------------------+--------+--------+
| id   | name                 | amount | type   |
+------+----------------------+--------+--------+
|  786 | D-1194-838HELLUJP-05 |  -5800 | DEBIT  |
|  785 | C-1194-838HELLUJP-05 |   5800 | CREDIT |
| 5060 | D-1195-UOK4HS5POF-05 |  -5000 | DEBIT  |
| 5059 | C-1195-UOK4HS5POF-05 |   5000 | CREDIT |
|  246 | D-1196-0FUCJI66BX-05 |  -7000 | DEBIT  |
|  245 | C-1196-0FUCJI66BX-05 |   7000 | CREDIT |
| 9720 | D-1197-W2J0EC1BOB-05 |  -6500 | DEBIT  |
| 9719 | C-1197-W2J0EC1BOB-05 |   6500 | CREDIT |
| 2694 | D-1198-MFKIKHGW0S-05 |  -5500 | DEBIT  |
| 2693 | C-1198-MFKIKHGW0S-05 |   5500 | CREDIT |
+------+----------------------+--------+--------+
10 rows in set (0.01 sec)

One entry should negate the other entry. It doesn't matter if I update the first or second matching record, what matters is that one has a positive amount and the other has a negative amount. And the type and name need to be updated.

Any clues on how to do this? What would the update command look like? Maybe using a group by clause? I have some ideas on how to do it with a stored procedure, but can I do it with a simple update?

Body:
If the ID:s for a pair always match the formula x and x+1, you could say something like

WHERE MOD(`id`, 2) = 1

EDIT: I haven't tested this code, so I can't guarantee that it's possible to put a column name into a MOD like this, but it might be worth a try, and/or further investigation.


来源: stackexchange

问:
Enter-PSSession cmdlet: Username containing a space is not working
In PowerShell 6.2, using the Enter-PSSession cmdlet, we have a username like "John Green".

Here the resulting error:

```<code>PS C:\> Enter-PSSession -Hostname 192.168.1.1 -Username "John Green" -SSHTransport
Enter-PSSession : The background process reported an error with the following message: The SSH client session has ended with error message: ssh: Could not resolve hostname john: No such host is known. .
At line:1 char:1
+ Enter-PSSession -Hostname 192.168.1.1 -Username "John Green" -SSHTra ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ResourceUnavailable: (:) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : System.Management.Automation.Remoting.PSRemotingDataStructureException,Microsoft.PowerShell.Commands.EnterPSSessionCommand
</code>```

Now a working example with "John.Green" (space replaced by a dot).

```<code>PS C:\> Enter-PSSession -Hostname  192.168.1.1 -Username "John" -SSHTransport
The authenticity of host '192.168.1.1 (192.168.1.1)' can't be established.
ECDSA key fingerprint is <snip>.
Are you sure you want to continue connecting (yes/no)?
</code>```

A Linux like command would also gives an error in PowerShell:

```<code>PS C:\> ssh "John Green"@192.168.1.1
At line:1 char:22
+ ssh "John Green"@192.168.1.1
+                      ~
Missing property name after reference operator.
At line:1 char:17
+ ssh "John Green"@192.168.1.1
+                 ~~~~
The splatting operator '@' cannot be used to reference variables in an expression. '@192' can be used only as an
argument to a command. To reference variables in an expression use '$192'.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingPropertyName
</code>```

Questions:

How a username with a space can be use with that kind of cmdlets?

If not possible, in PowerShell, how to start a SSH Session with an username containing a space?

答:
Thanks to @LarrySong the answers for SSH:

```<code>ssh "John Green@192.168.1.1"
</code>```

The other proposed formats are not working.

The following command is working in PowerShell (no client side error) but because it replaces the space by "%20" the username isn't valid on the server side.

```<code>Enter-PSSession -Hostname "John Green@192.168.1.1" -SSHTransport
John%20Green@192.168.1.1's password:
Enter-PSSession : The background process reported an error with the following message: The SSH client session has ended with error message: Permission denied, please try again..
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In PowerShell 6.2, using the Enter-PSSession cmdlet, we have a username like "John Green".

Here the resulting error:

PS C:\> Enter-PSSession -Hostname 192.168.1.1 -Username "John Green" -SSHTransport
Enter-PSSession : The background process reported an error with the following message: The SSH client session has ended with error message: ssh: Could not resolve hostname john: No such host is known. .
At line:1 char:1
+ Enter-PSSession -Hostname 192.168.1.1 -Username "John Green" -SSHTra ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ResourceUnavailable: (:) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : System.Management.Automation.Remoting.PSRemotingDataStructureException,Microsoft.PowerShell.Commands.EnterPSSessionCommand

Now a working example with "John.Green" (space replaced by a dot).

PS C:\> Enter-PSSession -Hostname  192.168.1.1 -Username "John" -SSHTransport
The authenticity of host '192.168.1.1 (192.168.1.1)' can't be established.
ECDSA key fingerprint is <snip>.
Are you sure you want to continue connecting (yes/no)?

A Linux like command would also gives an error in PowerShell:

PS C:\> ssh "John Green"@192.168.1.1
At line:1 char:22
+ ssh "John Green"@192.168.1.1
+                      ~
Missing property name after reference operator.
At line:1 char:17
+ ssh "John Green"@192.168.1.1
+                 ~~~~
The splatting operator '@' cannot be used to reference variables in an expression. '@192' can be used only as an
argument to a command. To reference variables in an expression use '$192'.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingPropertyName

Questions:

How a username with a space can be use with that kind of cmdlets?

If not possible, in PowerShell, how to start a SSH Session with an username containing a space?

Body:
Thanks to @LarrySong the answers for SSH:

ssh "John Green@192.168.1.1"

The other proposed formats are not working.

The following command is working in PowerShell (no client side error) but because it replaces the space by "%20" the username isn't valid on the server side.

Enter-PSSession -Hostname "John Green@192.168.1.1" -SSHTransport
John%20Green@192.168.1.1's password:
Enter-PSSession : The background process reported an error with the following message: The SSH client session has ended with error message: Permission denied, please try again..


问:
react-native-image-resizer issue. 'React/RCTImageURLLoader.h' file not found
I'm using react-native-image-resizer.
RN - 0.59

I don't want to upgrade RN.

When I installed this library and ran, it said  'React/RCTImageURLLoader.h' file not found.

How can I solve this?

Thanks,

答: Upgrade your React Native and also do a pod install. This should fix your problem</p>


问:
Python - Display Seaborn KDE Plot
I want to display Seaborn KDE Plot but I could'nt get to display it with a normal show method. How shall I do it?

```<code>import numpy as np
from scipy.fftpack import dct
import seaborn

sample1 = dct(np.random.rand(100))
sample2 = dct(np.random.rand(30))
seaborn.kdeplot(sample1, color="r")
seaborn.kdeplot(sample2, color="b")
</code>```

答:
Try

import numpy as np
from scipy.fftpack import dct
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()

sample1 = dct(np.random.rand(100))
sample2 = dct(np.random.rand(30))
sns.kdeplot(sample1, color="r")
sns.kdeplot(sample2, color="b")
plt.show()

```

Output

Title: Python - Display Seaborn KDE Plot

Body:
I want to display Seaborn KDE Plot but I could'nt get to display it with a normal show method. How shall I do it?

import numpy as np
from scipy.fftpack import dct
import seaborn

sample1 = dct(np.random.rand(100))
sample2 = dct(np.random.rand(30))
seaborn.kdeplot(sample1, color="r")
seaborn.kdeplot(sample2, color="b")

Body:
Try

import numpy as np
from scipy.fftpack import dct
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()

sample1 = dct(np.random.rand(100))
sample2 = dct(np.random.rand(30))
sns.kdeplot(sample1, color="r")
sns.kdeplot(sample2, color="b")
plt.show()

Output


问:
PropTypes in functional stateless component
Without using class, how do I use PropTypes in functional stateless component of react?</p>

```<code>export const Header = (props) => (
   <div>hi</div>
)
</code>```

答:
Same way you do in class based components:

```<code>   import PropTypes from 'prop-types';

   const funcName = (props) => {
       ...
   }
   funcName.propTypes = {
       propName: PropTypes.string.isRequired
   }
</code>```

Note: You might have to install prop-types via npm install prop-types or yarn add prop-types, depending on the React version you are using.

ContentLicense: CC BY-SA 3.0

Body:
Without using class, how do I use PropTypes in functional stateless component of react?

export const Header = (props) => (

hi

)

Body:
Same way you do in class based components:

   import PropTypes from 'prop-types';

   const funcName = (props) => {
       ...
   }
   funcName.propTypes = {
       propName: PropTypes.string.isRequired
   }

Note: You might have to install prop-types via npm install prop-types or yarn add prop-types, depending on the React version you are using.


问:
Use DASH to display two dataframes on one page
I would like to create a second dataframe and then display two tables on a page.  Right now this displays just one.  It looks like dash_bootstrap_components would allow me to segment the screen, but I can't find examples with more than one table</p>

```<code>import dash
import dash_html_components as html
import pandas as pd

#would like to add a second dataframe here
df1 = pd.read_sas('C:\PY_DASH\file1.sas7bdat', format = 'sas7bdat', encoding='utf-8' )

def generate_table(dataframe, max_rows=7):
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] +

        # Body
        [html.Tr([
            html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
        ]) for i in range(min(len(dataframe), max_rows))]
    )

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

#I would like to add the second table here
app.layout = html.Div(children=[
    html.H1(children='QA Test: Test 0-1: Output Files Record Count Comparison'),
    generate_table(df1)
])

if __name__ == '__main__':
    app.run_server(debug=True, port=8000)
</code>```

答:
Try to separate out the chunk of code that generates each table. Then assemble them both inside a dcc container, which can then be used in your layout. This makes it easy to debug also later :). Below is some sample code to give you an idea of what I mean.

First the section to generate table 1. Within this you may use your function generate_table

```<code>one_row = html.Tr([html.Td(<content>, id="row1" )])
t_head = [
      html.Thead(html.Tr([html.Th("Table1")]))
]
table1_section = dbc.Card(children=[
    dbc.CardHeader(html.H5("Table1 header", id="t_head")),
    dbc.CardBody([
      dbc.Table(t_head + [html.Tbody([one_row])])
    ])
])
</code>```

Similarly make table2_section
Next assemble this as a dbc.Row() if required.

Finally, put them all together in a dbc.Container eg:

```<code>page_content = dbc.Container([
      table1_section,
      table2_section,
      somegraph_section
], fluid=True)
</code>```

Hope this helps.

Body:
I would like to create a second dataframe and then display two tables on a page.  Right now this displays just one.  It looks like dash_bootstrap_components would allow me to segment the screen, but I can't find examples with more than one table

import dash
import dash_html_components as html
import pandas as pd

#would like to add a second dataframe here
df1 = pd.read_sas('C:\PY_DASH\file1.sas7bdat', format = 'sas7bdat', encoding='utf-8' )

def generate_table(dataframe, max_rows=7):
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] +

        # Body
        [html.Tr([
            html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
        ]) for i in range(min(len(dataframe), max_rows))]
    )

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

#I would like to add the second table here
app.layout = html.Div(children=[
    html.H1(children='QA Test: Test 0-1: Output Files Record Count Comparison'),
    generate_table(df1)
])

if __name__ == '__main__':
    app.run_server(debug=True, port=8000)

Body:
Try to separate out the chunk of code that generates each table. Then assemble them both inside a dcc container, which can then be used in your layout. This makes it easy to debug also later :). Below is some sample code to give you an idea of what I mean.

First the section to generate table 1. Within this you may use your function generate_table

one_row = html.Tr([html.Td(<content>, id="row1" )])
t_head = [
      html.Thead(html.Tr([html.Th("Table1")]))
]
table1_section = dbc.Card(children=[
    dbc.CardHeader(html.H5("Table1 header", id="t_head")),
    dbc.CardBody([
      dbc.Table(t_head + [html.Tbody([one_row])])
    ])
])

Similarly make table2_section
Next assemble this as a dbc.Row() if required.

Finally, put them all together in a dbc.Container eg:

page_content = dbc.Container([
      table1_section,
      table2_section,
      somegraph_section
], fluid=True)

Hope this helps.


问:
Pass and access params in a ReactJS link
I need to pass params in a ReactJS link, and access them in the component I'm linking to. This is what I tried:

In the router:

```<code><Route path="/NextComponent/:paramName" component={NextComponent}> <NextComponent/></Route>
</code>```

In the table where the links are:

```<code><Link
   to={{
     pathname: "/NextComponent/paramvalue",
     state: { paramName: 'paramvalue' }
  }}
>my link text</Link>
</code>```

I tried retrieving it like this in NextComponent:

```<code>constructor(props) {
    super(props);
    console.log(props);
    this.state = { data: [] };
}
</code>```

Then in componentDidMount:

```<code>async componentDidMount() {
   const data = this.props;
   this.setState({ data });
   console.log(data);
   console.log(this.props);
}
</code>```

But the props is an empty object. I tried looking for anything else in the component, like

```<code>console.log(this.search);
console.log(this.props.match);
console.log(this.props.location);
console.log(this.paramName);
</code>```

but they're all undefined.

What am I missing here?

答:
Route

Warning: <Route children> takes precedence over both <Route component> and <Route render> so don’t use more than one in the same
  .

ROUTE PROPS

I think due to this your wrapped child components take precedence and aren't getting route-props since you are also specifying a component. Try not specifying a component prop AND a wrapped child component.

```<code><Route
  path="/NextComponent/:paramName"
  component={NextComponent}
>
  <NextComponent/> // This one doesn't receive route-props (i.e. match, location, etc..)
</Route>
</code>```

Specify one or the other

```<code><Route
  path="/NextComponent/:paramName"
  component={NextComponent} // will receive route-props
/>

// or

<Route
  path="/NextComponent/:paramName"
>
  <NextComponent/> // needs to use hooks to access route-props
</Route>
</code>```

SENDING ROUTE PARAMS

The string literal "/NextComponent/:paramName" isn't a pathname you can match.

When pushing the route you can't pass route parameters in state, you need to properly format the route pathname (i.e. the URL). This is commonly done using string interpolation.

```<code><Link
  to={{
    pathname: `/NextComponent/${paramvalue}`
  }}
>
  my link text
</Link>
</code>```

Or more succinctly using the standard to as a string

```<code><Link to=`/NextComponent/${paramvalue}`>my link text</Link>
</code>```

Body:
I need to pass params in a ReactJS link, and access them in the component I'm linking to. This is what I tried:

In the router:

<Route path="/NextComponent/:paramName" component={NextComponent}> <NextComponent/></Route>

In the table where the links are:

<Link
   to={{
     pathname: "/NextComponent/paramvalue",
     state: { paramName: 'paramvalue' }
  }}
>my link text</Link>

I tried retrieving it like this in NextComponent:

constructor(props) {
    super(props);
    console.log(props);
    this.state = { data: [] };
}

Then in componentDidMount:

async componentDidMount() {
   const data = this.props;
   this.setState({ data });
   console.log(data);
   console.log(this.props);
}

But the props is an empty object. I tried looking for anything else in the component, like

console.log(this.search);
console.log(this.props.match);
console.log(this.props.location);
console.log(this.paramName);

but they're all undefined.

What am I missing here?

Body:
Route

Warning: <Route children> takes precedence over both <Route component> and <Route render> so don’t use more than one in the same
  .

ROUTE PROPS

I think due to this your wrapped child components take precedence and aren't getting route-props since you are also specifying a component. Try not specifying a component prop AND a wrapped child component.

<Route
  path="/NextComponent/:paramName"
  component={NextComponent}
>
  <NextComponent/> // This one doesn't receive route-props (i.e. match, location, etc..)
</Route>

Specify one or the other

<Route
  path="/NextComponent/:paramName"
  component={NextComponent} // will receive route-props
/>

// or

<Route
  path="/NextComponent/:paramName"
>
  <NextComponent/> // needs to use hooks to access route-props
</Route>

SENDING ROUTE PARAMS

The string literal "/NextComponent/:paramName" isn't a pathname you can match.

When pushing the route you can't pass route parameters in state, you need to properly format the route pathname (i.e. the URL). This is commonly done using string interpolation.

<Link
  to={{
    pathname: `/NextComponent/${paramvalue}`
  }}
>
  my link text
</Link>

Or more succinctly using the standard to as a string

<Link to=`/NextComponent/${paramvalue}`>my link text</Link>


问:
For the apps Built using create-react-app command, does it optimize css files also for production build?
I have used Bootstrap for my react project, for simple HTML landing pages I used purgeCSS, however in react (cra template) does the production build remove unused CSS also? </p>

答: The commented code goes away but not unused css. </p>


问:
Getting Undefined Method "Error" in Rails
I am creating a survey tool with Rails. I am trying to set up validation for the Answer where the participant has to submit an answer that is longer than 5 characters. I am getting the following error when I try to add a new answer.

undefined method `errors'

I have read in other posts that it is likely to be caused because you haven't initialised the answer object in the answers controller. My problem with this is that I have - it just doesn't look like this:

```<code>def new
  @answer = Answer.new
end
</code>```

It looks like this in my code:

```<code>  def new
    @study = Study.find(params[:study_id])
    @question = @study.questions.find(params[:question_id])
    @participant = find_participant
    @answer = @question.answers.build(participant: @participant)
  end
</code>```

This is the code for my Answer Model:

```<code>class Answer < ApplicationRecord
  belongs_to :question
  belongs_to :participant
  validates :answer, presence: true,
            length: { minimum: 5 }
end

</code>```

And this is the full error that I am getting in my server:

```<code>Started GET "/studies/32/questions/63/answers/new" for ::1 at 2020-02-18 10:14:41 +1300
   (2.1ms)  SELECT sqlite_version(*)
Processing by AnswersController#new as HTML
  Parameters: {"study_id"=>"32", "question_id"=>"63"}
  Study Load (1.1ms)  SELECT "studies".* FROM "studies" WHERE "studies"."id" = ? LIMIT ?  [["id", 32], ["LIMIT", 1]]
  ↳ app/controllers/answers_controller.rb:3:in `new'
  Question Load (1.5ms)  SELECT "questions".* FROM "questions" WHERE "questions"."study_id" = ? AND "questions"."id" = ? LIMIT ?  [["study_id", 32], ["id", 63], ["LIMIT", 1]]
  ↳ app/controllers/answers_controller.rb:4:in `new'
   (0.5ms)  begin transaction
  ↳ app/controllers/answers_controller.rb:33:in `find_participant'
  Participant Create (4.5ms)  INSERT INTO "participants" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2020-02-17 21:14:45.571329"], ["updated_at", "2020-02-17 21:14:45.571329"]]
  ↳ app/controllers/answers_controller.rb:33:in `find_participant'
   (3.0ms)  commit transaction
  ↳ app/controllers/answers_controller.rb:33:in `find_participant'
  Rendering answers/new.html.erb within layouts/application
  Answer Load (1.5ms)  SELECT "answers".* FROM "answers" WHERE "answers"."question_id" = ?  [["question_id", 63]]
  Rendered answers/new.html.erb within layouts/application (Duration: 1228.1ms | Allocations: 13885323)
Completed 500 Internal Server Error in 4106ms (ActiveRecord: 12.0ms | Allocations: 37401284)

ActionView::Template::Error (undefined method `errors' for #<Answer::ActiveRecord_Associations_CollectionProxy:0x00007fae2e5792f0>):
    4:   <%= form_with model: @answer, url: study_question_answers_path(@study, @question), local: true do |form| %>
    5:     <%= form.hidden_field :participant_id %>
    6:
    7:     <% if @question.answers.errors.any? %>
    8:
    9:
   10:     <% end %>
</code>```

This is my first rails project and I'm not sure what I'm missing - can anyone help me out here?

Thanks

答:
The Solution provided by @RockwellRice is correct and I briefed it for better understanding below

answers is a collection and not a single object. Iterate through them and then call errors on a single answer instance

```<code><% @question.answers.each do |ans| %>
    <% if ans.errors.any? %>

    <% end %>
<% end %>
</code>```

or if you want to handle an error on a specific answer record
then you can modify that line

```<code>from
<% @question.answers.errors.any? %>
to
<% @question.answers[0].errors.any? %>
</code>```

here you can refer to specific answer through array index and then can access its errors info

Body:
I am creating a survey tool with Rails. I am trying to set up validation for the Answer where the participant has to submit an answer that is longer than 5 characters. I am getting the following error when I try to add a new answer.

undefined method `errors'

I have read in other posts that it is likely to be caused because you haven't initialised the answer object in the answers controller. My problem with this is that I have - it just doesn't look like this:

def new
  @answer = Answer.new
end

It looks like this in my code:

  def new
    @study = Study.find(params[:study_id])
    @question = @study.questions.find(params[:question_id])
    @participant = find_participant
    @answer = @question.answers.build(participant: @participant)
  end

This is the code for my Answer Model:

class Answer < ApplicationRecord
  belongs_to :question
  belongs_to :participant
  validates :answer, presence: true,
            length: { minimum: 5 }
end

And this is the full error that I am getting in my server:

Started GET "/studies/32/questions/63/answers/new" for ::1 at 2020-02-18 10:14:41 +1300
   (2.1ms)  SELECT sqlite_version(*)
Processing by AnswersController#new as HTML
  Parameters: {"study_id"=>"32", "question_id"=>"63"}
  Study Load (1.1ms)  SELECT "studies".* FROM "studies" WHERE "studies"."id" = ? LIMIT ?  [["id", 32], ["LIMIT", 1]]
  ↳ app/controllers/answers_controller.rb:3:in `new'
  Question Load (1.5ms)  SELECT "questions".* FROM "questions" WHERE "questions"."study_id" = ? AND "questions"."id" = ? LIMIT ?  [["study_id", 32], ["id", 63], ["LIMIT", 1]]
  ↳ app/controllers/answers_controller.rb:4:in `new'
   (0.5ms)  begin transaction
  ↳ app/controllers/answers_controller.rb:33:in `find_participant'
  Participant Create (4.5ms)  INSERT INTO "participants" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2020-02-17 21:14:45.571329"], ["updated_at", "2020-02-17 21:14:45.571329"]]
  ↳ app/controllers/answers_controller.rb:33:in `find_participant'
   (3.0ms)  commit transaction
  ↳ app/controllers/answers_controller.rb:33:in `find_participant'
  Rendering answers/new.html.erb within layouts/application
  Answer Load (1.5ms)  SELECT "answers".* FROM "answers" WHERE "answers"."question_id" = ?  [["question_id", 63]]
  Rendered answers/new.html.erb within layouts/application (Duration: 1228.1ms | Allocations: 13885323)
Completed 500 Internal Server Error in 4106ms (ActiveRecord: 12.0ms | Allocations: 37401284)

ActionView::Template::Error (undefined method `errors' for #<Answer::ActiveRecord_Associations_CollectionProxy:0x00007fae2e5792f0>):
    4:   <%= form_with model: @answer, url: study_question_answers_path(@study, @question), local: true do |form| %>
    5:     <%= form.hidden_field :participant_id %>
    6:
    7:     <% if @question.answers.errors.any? %>
    8:
    9:
   10:     <% end %>

This is my first rails project and I'm not sure what I'm missing - can anyone help me out here?

Thanks

Body:
The Solution provided by @RockwellRice is correct and I briefed it for better understanding below

answers is a collection and not a single object. Iterate through them and then call errors on a single answer instance

<% @question.answers.each do |ans| %>
    <% if ans.errors.any? %>

    <% end %>
<% end %>

or if you want to handle an error on a specific answer record
then you can modify that line

from
<% @question.answers.errors.any? %>
to
<% @question.answers[0].errors.any? %>

here you can refer to specific answer through array index and then can access its errors info


问:
Java programs in Linux Machine (UTC timezone) returning date in HDT timezone instead of UTC timezone
I have a linux machine in UTC timezone.

[user@test packages]$ date +'%:z %Z'
+00:00 UTC
```

<p>Running <code>cat /etc/localtime</code> also seems to indicate that my machine is in UTC timezone;</p>

<pre class="lang-sh prettyprint-override"><code>[user@test ~]$ cat /etc/localtime
f2UTCTZif2UTC
UTC0

</code>```

However calling logger.info(new Date()) in a application running tomcat under Java 1.7 returns something like Mon Oct 28 01:51:39 HDT 2019

This is very strange, so I created a simple Java program for testing:

import java.util.Date;

class Test
{
        public static void main (String args[])
        {
                Date dt = new Date();
                System.out.println(dt);
        }
}
```

<p>Compile and run it</p>

<pre class="lang-sh prettyprint-override"><code>[user@test]$ /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.211.x86_64/bin/javac Test.java
[user@test]$ /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.211.x86_64/bin/java Test
Mon Oct 28 02:08:49 HDT 2019
</code>```

My question is why my Linux utility is return date in UTC format, and yet my Java apps are returning dates in HDT format (I don't even know what HDT is).

Since the app I'm maintaining is legacy, I can't use Joda Time or upgrade to Java8 or higher as this would meant lots of code changes.

答:
tl;dr

Never use the legacy class Date.

Instant.now()
For current moment as seen in UTC.

ZonedDateTime.now( ZoneId.of( "Pacific/Honolulu" ) )
For current moment as seen in a particular time zone.

2020-02-18T05:28:11.146726Z

2020-02-17T19:28:11.146726-10:00[Pacific/Honolulu]

Details

Firstly, you should know that your java.util.Date is actually a moment in UTC but its toString method dynamically applies the JVM's current default time zone while generating the text. Very confusing. One of many reasons to never use this class.

Date, Calendar, and the other legacy date-time classes were supplanted by java.time years ago with the adoption of JSR 310.

Avoid depending on default time zone

Using the java.time classes, you can easily write code that does not depend on a default time zone. You can specify your desired offset-from-UTC or time zone explicitly, whether that be UTC itself (an offset of zero hours-minutes-seconds) or a time zone like Pacific/Honolulu.

UTC

If you want to track a moment in UTC, use Instant.

```<code>Instant instant = Instant.now() ;
</code>```

The Instant::toString method generates text in standard ISO 8601 format. The formats defined by this standard are designed for data exchange.

```<code>String output = instant.toString() ;
</code>```

output: 2020-02-18T05:28:11.146726Z

The Z on the end means UTC, and is pronounced “Zulu”.

Zoned

If you want to see that same moment by the wall-clock time used by the people in Hawaii, apply a ZoneId to get a ZonedDateTime.

Never use the 2-4 letter abbreviation such as HDT or EST or IST as they are not true time zones, not standardized, and not even unique(!).

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland.

```<code>ZoneId z = ZoneId.of( "Pacific/Honolulu" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
</code>```

The ZonedDateTime::toString method wisely extends the ISO 8601 format by appending the name of the time zone is square brackets.

```<code>String output = zdt.toString() ;
</code>```

See this code run live at IdeOne.com.

outputZdt: 2020-02-17T19:28:11.146726-10:00[Pacific/Honolulu]

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

Later versions of Android bundle implementations of the java.time classes.

For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

Body:
I have a linux machine in UTC timezone.

[user@test packages]$ date +'%:z %Z'
+00:00 UTC

Running cat /etc/localtime also seems to indicate that my machine is in UTC timezone;

[user@test ~]$ cat /etc/localtime
f2UTCTZif2UTC
UTC0

However calling logger.info(new Date()) in a application running tomcat under Java 1.7 returns something like Mon Oct 28 01:51:39 HDT 2019

This is very strange, so I created a simple Java program for testing:

import java.util.Date;

class Test
{
        public static void main (String args[])
        {
                Date dt = new Date();
                System.out.println(dt);
        }
}

Compile and run it

[user@test]$ /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.211.x86_64/bin/javac Test.java
[user@test]$ /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.211.x86_64/bin/java Test
Mon Oct 28 02:08:49 HDT 2019

My question is why my Linux utility is return date in UTC format, and yet my Java apps are returning dates in HDT format (I don't even know what HDT is).

Since the app I'm maintaining is legacy, I can't use Joda Time or upgrade to Java8 or higher as this would meant lots of code changes.

Body:
tl;dr

Never use the legacy class Date.

Instant.now()
For current moment as seen in UTC.

ZonedDateTime.now( ZoneId.of( "Pacific/Honolulu" ) )
For current moment as seen in a particular time zone.

2020-02-18T05:28:11.146726Z

2020-02-17T19:28:11.146726-10:00[Pacific/Honolulu]

Details

Firstly, you should know that your java.util.Date is actually a moment in UTC but its toString method dynamically applies the JVM's current default time zone while generating the text. Very confusing. One of many reasons to never use this class.

Date, Calendar, and the other legacy date-time classes were supplanted by java.time years ago with the adoption of JSR 310.

Avoid depending on default time zone

Using the java.time classes, you can easily write code that does not depend on a default time zone. You can specify your desired offset-from-UTC or time zone explicitly, whether that be UTC itself (an offset of zero hours-minutes-seconds) or a time zone like Pacific/Honolulu.

UTC

If you want to track a moment in UTC, use Instant.

Instant instant = Instant.now() ;

The Instant::toString method generates text in standard ISO 8601 format. The formats defined by this standard are designed for data exchange.

String output = instant.toString() ;

output: 2020-02-18T05:28:11.146726Z

The Z on the end means UTC, and is pronounced “Zulu”.

Zoned

If you want to see that same moment by the wall-clock time used by the people in Hawaii, apply a ZoneId to get a ZonedDateTime.

Never use the 2-4 letter abbreviation such as HDT or EST or IST as they are not true time zones, not standardized, and not even unique(!).

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland.

ZoneId z = ZoneId.of( "Pacific/Honolulu" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

The ZonedDateTime::toString method wisely extends the ISO 8601 format by appending the name of the time zone is square brackets.

String output = zdt.toString() ;

See this code run live at IdeOne.com.

outputZdt: 2020-02-17T19:28:11.146726-10:00[Pacific/Honolulu]

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

Later versions of Android bundle implementations of the java.time classes.

For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


问:
How do I stop SQL Server 2008 R2 trying to install some package when I build my setup project?
I have a WPF Linq-to-SQL project which I have been developing using MS Visual Studio 2008. I was running SQL Server 2008, and recently upgraded it to version R2. Now, whenever I build my SETUP project (not the app itself), the build process causes a window to launch:

SQL Server 2008 R2 Management Studio
Please wait while Windows configures SQL Server 2008 R2 Management Studio

Which after a progress bar and some delay, complains: "The feature you are trying to use is on a network resource that is unavaiable." With an option to point to a source, and it is apparently trying to use c:\687b0370badbfcf47c\x86\setup\ , which doesn't exist.

If I click Cancel at that point, it says, "An installation package for the product SQL Server 2008 R2 Management Studio cannot be found. Try the installation again using a valid copy of the installation package 'sql_ssms.msi'."

I then get to watch the progress bar go backwards, and then it starts all over again. At this point, the setup build is waiting trying to build the MSI for my project. One time this resulted in Visual Studio crashing. Other times, I have been able to tell the progress bar window to cancel, and then my setup project builds fine.

So my questions are:

How do I get this to stop launching unwanted installer attempts when I try to build my setup?

and

Why is it doing this in the first place?

答:
Here it is,

```<code>regsvr32.exe /u "C:\Program Files (x86)\Common Files\microsoft shared\MSI Tools\mergemod.dll"
regsvr32.exe "C:\Program Files (x86)\Common Files\microsoft shared\MSI Tools\mergemod.dll"
</code>```

Note: open cmd with administrator rights.

ContentLicense: CC BY-SA 2.5

Body:
Here it is,

regsvr32.exe /u "C:\Program Files (x86)\Common Files\microsoft shared\MSI Tools\mergemod.dll"
regsvr32.exe "C:\Program Files (x86)\Common Files\microsoft shared\MSI Tools\mergemod.dll"

Note: open cmd with administrator rights.


问:
Open application/json type printed in the browser
Foursquare's api has the option to search for venues.
It's an HTTP GET method and has this form:

```<code>https://api.foursquare.com/v2/venues/search?ll=40.7,-74&oauth_token=xxxx
</code>```

In Foursquare's example (which is within the api website) works great, shows the array of venues for the given latitude and longitude (40.7,-74) printed in the browser. When I try to use it out of Foursquare here's what happens:

I'm using it like a normal url, I paste it in a browser but instead of showing an array printed in the browser, a download window with the following:

" You have chosen to open -search- which is an application/json type from https://api.foursquare.com. What should the browser do, open it with a program or save it? "

pops up. If I open the file -search- with an editor (or I save it and I open it later) the array is in there.

What am I doing wrong with this? any clues on why I'm not getting the venues array in the browser?

Thanks a million

答:
Sorry, I may not have explained myself correctly, I'm still getting json. The solution that worked in my case:

```<code>   $.ajax({
           url: 'page.php',
           success: function(data) {
         $('.result').html(data);
        // alert('Load was performed.');
           }
         });
</code>```

Thanks a lot

Body:
Foursquare's api has the option to search for venues.
It's an HTTP GET method and has this form:

https://api.foursquare.com/v2/venues/search?ll=40.7,-74&oauth_token=xxxx

In Foursquare's example (which is within the api website) works great, shows the array of venues for the given latitude and longitude (40.7,-74) printed in the browser. When I try to use it out of Foursquare here's what happens:

I'm using it like a normal url, I paste it in a browser but instead of showing an array printed in the browser, a download window with the following:

" You have chosen to open -search- which is an application/json type from https://api.foursquare.com. What should the browser do, open it with a program or save it? "

pops up. If I open the file -search- with an editor (or I save it and I open it later) the array is in there.

What am I doing wrong with this? any clues on why I'm not getting the venues array in the browser?

Thanks a million

Body:
Sorry, I may not have explained myself correctly, I'm still getting json. The solution that worked in my case:

   $.ajax({
           url: 'page.php',
           success: function(data) {
         $('.result').html(data);
        // alert('Load was performed.');
           }
         });

Thanks a lot


问:
Scroll to bottom of Div on page load (jQuery)
I have a div on my page:

```<code><div id='div1' style='overflow:scroll;overflow-x:hidden;max-height:200px;'></div>
</code>```

How can I make the div scroll to the bottom of the div?? Not the page, just the DIV.

答:
When page is load then scroll is max value .

This is message box when user send message then always show latest chat in down so that scroll value is always is maxium.

```<code>$('#message').scrollTop($('#message')[0].scrollHeight);
</code>```

see image

Body:
I have a div on my page:

How can I make the div scroll to the bottom of the div?? Not the page, just the DIV.

Body:
When page is load then scroll is max value .

This is message box when user send message then always show latest chat in down so that scroll value is always is maxium.

$('#message').scrollTop($('#message')[0].scrollHeight);

see image


问:
How to split a dataframe into two based on data from another dataframe (before and after some action) in pandas?
I need to split a dataframe with posts using data of date and time of registration into two dataframes, where I will have data of posts before and after registration.

A dataframe with posts:

```<code>posts = {'Login':['User1', 'User1', 'User2', 'User3', 'User3'], 'Posted':['13.12.2018 07:12', '13.05.2019 00:00', '13.05.2019 12:32', '13.06.2019 00:06', '01.07.2019 14:43']}
df_posts = pd.DataFrame(posts)
</code>```

A dataframe with dates of registration:

```<code>registr_date = {'Login':['User1', 'User2', 'User3'], 'Registered':['14.12.2018 12:07', '17.05.2019 14:01', '20.06.2019 15:00']}
df_registr = pd.DataFrame(registr_date)
</code>```

I changed the format of columns with time and date:

```<code>df_posts['Posted']= pd.to_datetime(df_posts['Posted'])
df_registr['Date_of_registration']= pd.to_datetime(df_registr['Date_of_registration'])
</code>```

I need to get the following output.
Posts before registration:

```<code>    Login   Posted_before
0   User1   13.12.2018 07:12
1   User2   13.05.2019 12:32
2   User3   13.06.2019 00:06
</code>```

Posts after registration:

```<code>    Login   Posted_after
0   User1   13.05.2019 00:00
1   User3   01.07.2019 14:43
</code>```

How I should split the dataframe with posts?

答:
First you can convert datetime with proper format and then make a dictionary with key as login and value as registered, and apply this map of Posted date as below.</p>

```<code>df_posts['Posted']= pd.to_datetime(df_posts['Posted'], format = '%d.%m.%Y %H:%M')
df_registr['Registered']= pd.to_datetime(df_registr['Registered'], format = '%d.%m.%Y %H:%M')

map_user = dict(zip(df_registr['Login'], df_registr['Registered']))

df_posts['pre_register'] = df_posts.apply(lambda x: x['Posted'] < map_user[x['Login']], axis = 1)

pre = df_posts[df_posts['pre_register']]
post = df_posts[~df_posts['pre_register']]
</code>```

Body:
I need to split a dataframe with posts using data of date and time of registration into two dataframes, where I will have data of posts before and after registration.

A dataframe with posts:

posts = {'Login':['User1', 'User1', 'User2', 'User3', 'User3'], 'Posted':['13.12.2018 07:12', '13.05.2019 00:00', '13.05.2019 12:32', '13.06.2019 00:06', '01.07.2019 14:43']}
df_posts = pd.DataFrame(posts)

A dataframe with dates of registration:

registr_date = {'Login':['User1', 'User2', 'User3'], 'Registered':['14.12.2018 12:07', '17.05.2019 14:01', '20.06.2019 15:00']}
df_registr = pd.DataFrame(registr_date)

I changed the format of columns with time and date:

df_posts['Posted']= pd.to_datetime(df_posts['Posted'])
df_registr['Date_of_registration']= pd.to_datetime(df_registr['Date_of_registration'])

I need to get the following output.
Posts before registration:

    Login   Posted_before
0   User1   13.12.2018 07:12
1   User2   13.05.2019 12:32
2   User3   13.06.2019 00:06

Posts after registration:

    Login   Posted_after
0   User1   13.05.2019 00:00
1   User3   01.07.2019 14:43

How I should split the dataframe with posts?

Body:
First you can convert datetime with proper format and then make a dictionary with key as login and value as registered, and apply this map of Posted date as below.

df_posts['Posted']= pd.to_datetime(df_posts['Posted'], format = '%d.%m.%Y %H:%M')
df_registr['Registered']= pd.to_datetime(df_registr['Registered'], format = '%d.%m.%Y %H:%M')

map_user = dict(zip(df_registr['Login'], df_registr['Registered']))

df_posts['pre_register'] = df_posts.apply(lambda x: x['Posted'] < map_user[x['Login']], axis = 1)

pre = df_posts[df_posts['pre_register']]
post = df_posts[~df_posts['pre_register']]


问:
How to retrieve data from fire-base into a new activity On-click RecyclerView
It's an app that retrieves book data from firebase, I want to know how to retrieve specific data into a new activity. Like, retrieve specific book data on click RecyclerView. I am able to get the onclick position on the RecyclerView but I don't know how to use that with firebase

Here is my code:

```<code>public class SearchPage extends AppCompatActivity {
    EditText searchbar;

    RecyclerView recyclerView;
    DatabaseReference reference;

    ArrayList <String> BookNameList;
    ArrayList <String> AuthorNameList;
    ArrayList <String> PicList;
    ArrayList <String> PublisherList;
    ArrayList <String> Shelfnols;
    ArrayList <String> Desc;
    SearchAdapter searchAdapter;

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

        searchbar = (EditText) findViewById(R.id.searchbar);
        reference = FirebaseDatabase.getInstance().getReference();
        reference.keepSynced(true);
        recyclerView = (RecyclerView) findViewById(R.id.rv);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        BookNameList = new ArrayList <> ();
        PublisherList = new ArrayList <> ();
        AuthorNameList = new ArrayList <> ();
        Shelfnols = new ArrayList <> ();
        PicList = new ArrayList <> ();
        Desc = new ArrayList <> ();
        final ArrayList <String> uidlist = new ArrayList <String> ();

        searchbar.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().isEmpty()) {
                    setAdapter(s.toString());

                } else {
                    BookNameList.clear();
                    AuthorNameList.clear();
                    PicList.clear();
                    PublisherList.clear();
                    Shelfnols.clear();
                    Desc.clear();
                    uidlist.clear();

                }
            }

            private void setAdapter(final String searchedString) {
                reference.child("books").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                        BookNameList.clear();
                        AuthorNameList.clear();
                        PicList.clear();
                        PublisherList.clear();
                        Shelfnols.clear();
                        Desc.clear();
                        uidlist.clear();

                        int counter = 0;
                        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                            String uid = snapshot.getKey();

                            String desc = snapshot.child("Desc").getValue(String.class);
                            String bookname = snapshot.child("bookname").getValue(String.class);
                            String author = snapshot.child("author").getValue(String.class);
                            String image = snapshot.child("image").getValue(String.class);
                            String publisher = snapshot.child("Publisher").getValue(String.class);
                            String shelfno = snapshot.child("Shelf_no").getValue(String.class);
                            try {

                                if (bookname.toLowerCase().contains(searchedString.toLowerCase())) {
                                    BookNameList.add(bookname);
                                    AuthorNameList.add(author);
                                    PublisherList.add(publisher);
                                    Shelfnols.add(shelfno);
                                    PicList.add(image);
                                    Desc.add(desc);

                                    counter++;
                                } else if (author.toLowerCase().contains(searchedString.toLowerCase())) {
                                    BookNameList.add(bookname);
                                    AuthorNameList.add(author);
                                    PublisherList.add(publisher);
                                    Shelfnols.add(shelfno);
                                    PicList.add(image);
                                    Desc.add(desc);
                                    counter++;
                                }
                            } catch (Exception e) {
                                Toast.makeText(getApplicationContext(), "not found", Toast.LENGTH_LONG).show();
                            }

                            if (counter == 15) {
                                break;
                            }
                            SearchAdapter searchAdapter = new SearchAdapter(SearchPage.this, BookNameList, AuthorNameList, PicList, PublisherList, Shelfnols);
                            recyclerView.setAdapter(searchAdapter);
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });
            }
        });

    }
</code>```

This is my adapter class

```<code>public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchViewHolder> {
public static final String id="key";
    Context context;
    ArrayList<String> BookNameList;
    ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
LinearLayout booklayout;

class SearchViewHolder extends RecyclerView.ViewHolder{
    ImageView bookimage;
    TextView bookname, authorname,publisher,shelfno;

    public SearchViewHolder(@NonNull View itemView) {
        super(itemView);
        bookimage =  itemView.findViewById(R.id.Bookimg);
        bookname =  itemView.findViewById(R.id.BookName);
        authorname =  itemView.findViewById(R.id.AuthorName);
        publisher =  itemView.findViewById(R.id.Publications);
        shelfno =  itemView.findViewById(R.id.Shelfno);
        booklayout=itemView.findViewById(R.id.LinLayout);
    }
}

public SearchAdapter(Context context, ArrayList<String> bookNameList, ArrayList<String> authorNameList, ArrayList<String> picList,ArrayList<String> publisherList,ArrayList<String> shelfnols) {
    this.context = context;
    BookNameList = bookNameList;
    AuthorNameList = authorNameList;
    PicList = picList;
    PublisherList=publisherList;
    Shelfnols=shelfnols;
}

@NonNull
@Override
public SearchAdapter.SearchViewHolder  onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.activity_search_layout,parent,false);
     return new SearchAdapter.SearchViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull SearchViewHolder holder, final int position) {
    holder.bookname.setText(BookNameList.get(position));
    holder.authorname.setText(AuthorNameList.get(position));
    holder.publisher.setText(PublisherList.get(position));
    holder.shelfno.setText(Shelfnols.get(position));
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                String t=String.valueOf(position);
            Toast.makeText(v.getContext(), "Item is clicked" + t, Toast.LENGTH_SHORT).show();

        }
    });

   booklayout.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {

       }

   });
</code>```

this the new activity where i want the book details to be shown

```<code>public class Bookdetailslayout extends SearchPage {

DatabaseReference reference;
TextView bookname,author,publisher,desc,location;
ImageView image;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bookdetailslayout);

    bookname = (TextView)findViewById(R.id.bkname);
    author = (TextView) findViewById(R.id.aname);
    publisher = (TextView) findViewById(R.id.pname);
    desc = (TextView) findViewById(R.id.bkdescription);
    location = (TextView) findViewById(R.id.bklocation);
    String s = getIntent().getStringExtra("key");

    DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference().child("books");
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            Bookdeets bookdeets=dataSnapshot.getValue(Bookdeets.class);

            bookname.setText(bookdeets.getBookname());

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}

    Glide.with(context).asBitmap().load(PicList.get(position)).placeholder(R.mipmap.ic_launcher_round).into(holder.bookimage);

}

@Override
public int getItemCount() {
    return BookNameList.size();
}
</code>```

答:
```<code>      holder.itemView.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           Intent i = new Intent(context,BookdetailsActivity.class);
           i.putExtra("bookname",bookname);
           context.startActivity(i);
       }
   });
</code>```

above code start new activity for showing details on new activity at the same time pass unique key for retrieving data from firebase.

inside BookDetailsActivity
get key value by using

String name = getIntent().getStringExtra("bookname");

then do your stuff for getting data from firebase.

Body:
It's an app that retrieves book data from firebase, I want to know how to retrieve specific data into a new activity. Like, retrieve specific book data on click RecyclerView. I am able to get the onclick position on the RecyclerView but I don't know how to use that with firebase

Here is my code:

public class SearchPage extends AppCompatActivity {
    EditText searchbar;

    RecyclerView recyclerView;
    DatabaseReference reference;

    ArrayList <String> BookNameList;
    ArrayList <String> AuthorNameList;
    ArrayList <String> PicList;
    ArrayList <String> PublisherList;
    ArrayList <String> Shelfnols;
    ArrayList <String> Desc;
    SearchAdapter searchAdapter;

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

        searchbar = (EditText) findViewById(R.id.searchbar);
        reference = FirebaseDatabase.getInstance().getReference();
        reference.keepSynced(true);
        recyclerView = (RecyclerView) findViewById(R.id.rv);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        BookNameList = new ArrayList <> ();
        PublisherList = new ArrayList <> ();
        AuthorNameList = new ArrayList <> ();
        Shelfnols = new ArrayList <> ();
        PicList = new ArrayList <> ();
        Desc = new ArrayList <> ();
        final ArrayList <String> uidlist = new ArrayList <String> ();

        searchbar.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().isEmpty()) {
                    setAdapter(s.toString());

                } else {
                    BookNameList.clear();
                    AuthorNameList.clear();
                    PicList.clear();
                    PublisherList.clear();
                    Shelfnols.clear();
                    Desc.clear();
                    uidlist.clear();

                }
            }

            private void setAdapter(final String searchedString) {
                reference.child("books").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                        BookNameList.clear();
                        AuthorNameList.clear();
                        PicList.clear();
                        PublisherList.clear();
                        Shelfnols.clear();
                        Desc.clear();
                        uidlist.clear();

                        int counter = 0;
                        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                            String uid = snapshot.getKey();

                            String desc = snapshot.child("Desc").getValue(String.class);
                            String bookname = snapshot.child("bookname").getValue(String.class);
                            String author = snapshot.child("author").getValue(String.class);
                            String image = snapshot.child("image").getValue(String.class);
                            String publisher = snapshot.child("Publisher").getValue(String.class);
                            String shelfno = snapshot.child("Shelf_no").getValue(String.class);
                            try {

                                if (bookname.toLowerCase().contains(searchedString.toLowerCase())) {
                                    BookNameList.add(bookname);
                                    AuthorNameList.add(author);
                                    PublisherList.add(publisher);
                                    Shelfnols.add(shelfno);
                                    PicList.add(image);
                                    Desc.add(desc);

                                    counter++;
                                } else if (author.toLowerCase().contains(searchedString.toLowerCase())) {
                                    BookNameList.add(bookname);
                                    AuthorNameList.add(author);
                                    PublisherList.add(publisher);
                                    Shelfnols.add(shelfno);
                                    PicList.add(image);
                                    Desc.add(desc);
                                    counter++;
                                }
                            } catch (Exception e) {
                                Toast.makeText(getApplicationContext(), "not found", Toast.LENGTH_LONG).show();
                            }

                            if (counter == 15) {
                                break;
                            }
                            SearchAdapter searchAdapter = new SearchAdapter(SearchPage.this, BookNameList, AuthorNameList, PicList, PublisherList, Shelfnols);
                            recyclerView.setAdapter(searchAdapter);
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });
            }
        });

    }

This is my adapter class

public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchViewHolder> {
public static final String id="key";
    Context context;
    ArrayList<String> BookNameList;
    ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
LinearLayout booklayout;

class SearchViewHolder extends RecyclerView.ViewHolder{
    ImageView bookimage;
    TextView bookname, authorname,publisher,shelfno;

    public SearchViewHolder(@NonNull View itemView) {
        super(itemView);
        bookimage =  itemView.findViewById(R.id.Bookimg);
        bookname =  itemView.findViewById(R.id.BookName);
        authorname =  itemView.findViewById(R.id.AuthorName);
        publisher =  itemView.findViewById(R.id.Publications);
        shelfno =  itemView.findViewById(R.id.Shelfno);
        booklayout=itemView.findViewById(R.id.LinLayout);
    }
}

public SearchAdapter(Context context, ArrayList<String> bookNameList, ArrayList<String> authorNameList, ArrayList<String> picList,ArrayList<String> publisherList,ArrayList<String> shelfnols) {
    this.context = context;
    BookNameList = bookNameList;
    AuthorNameList = authorNameList;
    PicList = picList;
    PublisherList=publisherList;
    Shelfnols=shelfnols;
}

@NonNull
@Override
public SearchAdapter.SearchViewHolder  onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.activity_search_layout,parent,false);
     return new SearchAdapter.SearchViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull SearchViewHolder holder, final int position) {
    holder.bookname.setText(BookNameList.get(position));
    holder.authorname.setText(AuthorNameList.get(position));
    holder.publisher.setText(PublisherList.get(position));
    holder.shelfno.setText(Shelfnols.get(position));
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                String t=String.valueOf(position);
            Toast.makeText(v.getContext(), "Item is clicked" + t, Toast.LENGTH_SHORT).show();

        }
    });

   booklayout.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {

       }

   });

this the new activity where i want the book details to be shown

public class Bookdetailslayout extends SearchPage {

DatabaseReference reference;
TextView bookname,author,publisher,desc,location;
ImageView image;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bookdetailslayout);

    bookname = (TextView)findViewById(R.id.bkname);
    author = (TextView) findViewById(R.id.aname);
    publisher = (TextView) findViewById(R.id.pname);
    desc = (TextView) findViewById(R.id.bkdescription);
    location = (TextView) findViewById(R.id.bklocation);
    String s = getIntent().getStringExtra("key");

    DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference().child("books");
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            Bookdeets bookdeets=dataSnapshot.getValue(Bookdeets.class);

            bookname.setText(bookdeets.getBookname());

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}

    Glide.with(context).asBitmap().load(PicList.get(position)).placeholder(R.mipmap.ic_launcher_round).into(holder.bookimage);

}

@Override
public int getItemCount() {
    return BookNameList.size();
}

Body:
      holder.itemView.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           Intent i = new Intent(context,BookdetailsActivity.class);
           i.putExtra("bookname",bookname);
           context.startActivity(i);
       }
   });

above code start new activity for showing details on new activity at the same time pass unique key for retrieving data from firebase.

inside BookDetailsActivity
get key value by using

String name = getIntent().getStringExtra("bookname");

then do your stuff for getting data from firebase.


问:
C++ including a ".h" file, function duplication confusion
I'm currently writing a program, and couldn't figure out why I got an error (note: I already fixed it, I'm curious about WHY the error was there and what this implies about including .h files).

Basically, my program was structured as follows:

The current file I'm working with, I'll call Current.cc (which is an implementation of Current.h).

Current.cc included a header file, named CalledByCurrent.h (which has an associated implementation called CalledByCurrent.cc).  CalledByCurrent.h contains a class definition.

There was a non-class function defined in CalledByCurrent.cc called thisFunction().  thisFunction() was not declared in CalledByCurrent.h since it was not actually a member function of the class (just a little helper function).  In Current.cc, I needed to use this function, so I just redefined thisFunction() at the top of Current.cc.  However, when I did this, I got an error saying that the function was duplicated.  Why is this, when myFunction() wasn't even declared in CalledByCurrent.h?

Thus, I just removed the function from Current.cc, now assuming that Current.cc had access to thisFunction() from CalledByCurrent.cc.  However, when I did this, I found that Current.cc did not know what function I was talking about.  What the heck?  I then copied the function definition for thisFunction() to the top of my CalledByCurrent.h file and this resolved the problem.  Could you help me understand this behavior?  Particularly, why would it think there was a duplicate, yet it didn't know how to use the original?

p.s - I apologize for how confusing this post is.  Please let me know if there's anything I can clear up.

答:
You can't have two global functions with the same name (even in 2 different translation units). To avoid getting the linker error define the function as static so that it is not visible outside the translation unit.

EDIT

You can use the function in the other .cpp file by using extern keyword. See this example:

```<code>//Test.cpp

void myfunc()
{

}

//Main.cpp
extern void myfunc();
int main()
{
    myfunc();
}
</code>```

It will call myfunc() defined in test.cpp.

Body:
You can't have two global functions with the same name (even in 2 different translation units). To avoid getting the linker error define the function as static so that it is not visible outside the translation unit.

EDIT

You can use the function in the other .cpp file by using extern keyword. See this example:

//Test.cpp

void myfunc()
{

}

//Main.cpp
extern void myfunc();
int main()
{
    myfunc();
}

It will call myfunc() defined in test.cpp.


问:
Somehow my value never equals 1, is there a reason for that?
I can't ever get guessLimit to equal 1, in the system log when I enter the limit of guesses as 5 and start guessing, the guessLimit will go down all the way to 2 and it will give me the "You Lose" message without letting me do my final guess...
 is there a reason for that?

```<code>public static void Main(string[] args){
    string guess = "";
    bool outOfguesses = false;
    int guessCount = 0;
    Console.Clear();
    Console.Write("Enter the amount of guesses you want: ");
    int guessLimit = Convert.ToInt32(Console.ReadLine());
    Console.Clear();
    Console.Write("Enter a word that will be guessed...: ");
    string secretWord = Console.ReadLine();
    Console.Clear();
    Console.Write("You have " + guessLimit + " guesses" + "\nEnter a guess: ");
    guess = Console.ReadLine();
    while(guess.ToLower() != secretWord.ToLower() && !outOfguesses){
      if(guessLimit >= guessCount || guessLimit == 1){
        guessCount++;
        guessLimit--;
        Console.Write("\nWRONG! You have " + guessLimit + " guesses left." + "\nEnter another guess: ");
        guess = Console.ReadLine();
      } else{
        outOfguesses = true;
      }
    }
    if(outOfguesses == true){
      Console.WriteLine("\nSorry...\nYou lose!");
    } else{
      Console.WriteLine("\nGood Job.\nYou Win!!");
    }
    Console.ReadLine();
  }
</code>```

答:
When your if statement reaches
(Is 2 >= 3) this is false so it will skip over the if and go to the else
Which is why it stops there.
Also change your guesslimit ==1 to <1</p>

Body:
I can't ever get guessLimit to equal 1, in the system log when I enter the limit of guesses as 5 and start guessing, the guessLimit will go down all the way to 2 and it will give me the "You Lose" message without letting me do my final guess...
 is there a reason for that?

public static void Main(string[] args){
    string guess = "";
    bool outOfguesses = false;
    int guessCount = 0;
    Console.Clear();
    Console.Write("Enter the amount of guesses you want: ");
    int guessLimit = Convert.ToInt32(Console.ReadLine());
    Console.Clear();
    Console.Write("Enter a word that will be guessed...: ");
    string secretWord = Console.ReadLine();
    Console.Clear();
    Console.Write("You have " + guessLimit + " guesses" + "\nEnter a guess: ");
    guess = Console.ReadLine();
    while(guess.ToLower() != secretWord.ToLower() && !outOfguesses){
      if(guessLimit >= guessCount || guessLimit == 1){
        guessCount++;
        guessLimit--;
        Console.Write("\nWRONG! You have " + guessLimit + " guesses left." + "\nEnter another guess: ");
        guess = Console.ReadLine();
      } else{
        outOfguesses = true;
      }
    }
    if(outOfguesses == true){
      Console.WriteLine("\nSorry...\nYou lose!");
    } else{
      Console.WriteLine("\nGood Job.\nYou Win!!");
    }
    Console.ReadLine();
  }


问:
Create a new column based on condition on other two columns in Pandas
I have a data frame as shown below

```<code>ID     PRICE      DURATION
1      10         30
2      200        730
3      40         60
4      300        400
5      100        180
</code>```

From the above data, I would like to create a new column PRICE_PER_YEAR based on below condition.

```<code>if DURATION < 370, then df['PRICE_PER_YEAR'] = df['PRICE']/ df['DURATION'] * 365

else df['PRICE_PER_YEAR'] = df['PRICE']
</code>```

Expected Output:

```<code>ID     PRICE      DURATION      PRICE_PER_YEAR
1      10         30            121.66
2      200        730           200
3      40         60            243.33
4      300        400           300
5      100        180           202.77
</code>```

答:
```<code>df['PRICE_PER_YEAR'] = df.apply(lambda x : x['PRICE']/ x['DURATION'] * 365 if x['DURATION'] < 370
     else x['PRICE'], axis = 1)
</code>```

Body:
I have a data frame as shown below

ID     PRICE      DURATION
1      10         30
2      200        730
3      40         60
4      300        400
5      100        180

From the above data, I would like to create a new column PRICE_PER_YEAR based on below condition.

if DURATION < 370, then df['PRICE_PER_YEAR'] = df['PRICE']/ df['DURATION'] * 365

else df['PRICE_PER_YEAR'] = df['PRICE']

Expected Output:

ID     PRICE      DURATION      PRICE_PER_YEAR
1      10         30            121.66
2      200        730           200
3      40         60            243.33
4      300        400           300
5      100        180           202.77


问:
Saving a list of ScriptableObject into json
My Item script

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(fileName ="Newitems",menuName ="Inventory/Items")]
[Serializable]
public class Item : ScriptableObject
{

  new public string name = "New items";
  //public Sprite Icon = null;      dealt with this later
  public bool isDefaulet = false;
  ...}
</code>```

And here is my inventory script:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
[Serializable]
public class Inventory : MonoBehaviour
{
   [SerializeField]
public List<Item> items = new List<Item>();
 void Save()
    {
        string json = JsonUtility.ToJson(items);
        Debug.Log(json);
        File.WriteAllText(Application.dataPath + "/saveFile.json", json);
    }
    public void Load()
    {
        string json = File.ReadAllText(Application.dataPath + "/saveFile.json");
        List<Item> List = JsonUtility.FromJson<List<Item>>(json);
        Debug.Log(List);
    }
...
 }
</code>```

Ok, i will try with the sprite later, but when saving, the console return {}, i have no idea now, please help.

答:
The first things to save your scriptable in json is to add the class attribute Serializable on each scriptable you want to serialize in json.

But here I think it will be hard to serialize the Icon field. In a json you really can save only number or string and there is a reference.

A way to serialize a Sprite ( or any reference) is to serialize the name or the id of the object. If you look how unity serialize a scene it’s exactly how it’s done.
And then when you read your json you replace that id by your asset.

Some json library can help on that, NewtonSoft Json.Net can help, specially on the special serialization for reference I describe.

Try it without the Sprite first and add complexity after ;)

EDIT

To be more precise, I think the better way to do what your try, is to not serialize a ScriptableObject, but instead a class hold by the scriptable.

```<code>class MyScriptable : ScriptableObject
{
    private MySerializableClass data;
}

[Serializable]
class MySerializableClass
{
    private string name;
    private float data1;
    private float data2;
}
</code>```

Then serialize the MySerializableClass, and use the name, or some id field to link each instance of scriptable with the good MySerializableClass :)

Body:
My Item script

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(fileName ="Newitems",menuName ="Inventory/Items")]
[Serializable]
public class Item : ScriptableObject
{

  new public string name = "New items";
  //public Sprite Icon = null;      dealt with this later
  public bool isDefaulet = false;
  ...}

And here is my inventory script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
[Serializable]
public class Inventory : MonoBehaviour
{
   [SerializeField]
public List<Item> items = new List<Item>();
 void Save()
    {
        string json = JsonUtility.ToJson(items);
        Debug.Log(json);
        File.WriteAllText(Application.dataPath + "/saveFile.json", json);
    }
    public void Load()
    {
        string json = File.ReadAllText(Application.dataPath + "/saveFile.json");
        List<Item> List = JsonUtility.FromJson<List<Item>>(json);
        Debug.Log(List);
    }
...
 }

Ok, i will try with the sprite later, but when saving, the console return {}, i have no idea now, please help.

Body:
The first things to save your scriptable in json is to add the class attribute Serializable on each scriptable you want to serialize in json.

But here I think it will be hard to serialize the Icon field. In a json you really can save only number or string and there is a reference.

A way to serialize a Sprite ( or any reference) is to serialize the name or the id of the object. If you look how unity serialize a scene it’s exactly how it’s done.
And then when you read your json you replace that id by your asset.

Some json library can help on that, NewtonSoft Json.Net can help, specially on the special serialization for reference I describe.

Try it without the Sprite first and add complexity after ;)

EDIT

To be more precise, I think the better way to do what your try, is to not serialize a ScriptableObject, but instead a class hold by the scriptable.

class MyScriptable : ScriptableObject
{
    private MySerializableClass data;
}

[Serializable]
class MySerializableClass
{
    private string name;
    private float data1;
    private float data2;
}

Then serialize the MySerializableClass, and use the name, or some id field to link each instance of scriptable with the good MySerializableClass :)


Title: Create a new column based on condition on other two columns in Pandas

Body:
Use np.where

>>> df['PRICE_PER_YEAR'] = np.where(df.DURATION < 370, df['PRICE']/ df['DURATION']*365, df['PRICE'])
>>> df
   ID  PRICE  DURATION  PRICE_PER_YEAR
0   1     10        30      121.666667
1   2    200       730      200.000000
2   3     40        60      243.333333
3   4    300       400      300.000000
4   5    100       180      202.777778


问:
Visual studio ask me to clone the same project which is already in the DevOps
I am new to DevOps and Git.
(time ago was using VisualSVN)

I wanted to commit a project's new changes to it's DevOps repository which I created earlier.
For some days repeatedly I made changes, commit, push to the repository.
Don't know why now after some days I am not able to do so.
Maybe a time-out thing, a disconnection from the repo.

By the way, after that seems I needed to reconnect to the repo, but after the connection, it repeatedly asks me to clone the same project, which I am working on it.

How can I tell Azure DevOps and Visual Studio that this project is the same project in the repo and sync them.

Guess the question and issue should be a simple one.

答:
Running that command said : "fatal: not a git repository (or any of the parent directories): .git"

That is the case if you run that command inside the .git folder itself.

You should run git remote -v in the parent folder of .git.

Then you can see if it references the Azure DevOps Git repository.

See "Azure Repos / Clone an existing Git repo" for more.

Actually, after discussion, it appears the .git folder was somehow corrupted.

Deleting it, re-creating it with a git init ., and re-importing it to Visual Studio was a workaround.

But that also means the commit created in it would differ from the existing history of the remote repo.

I would then, after creating a commit in the new local repo, do:

```<code>git fetch origin
git reset --hard origin/master
git cherry-pick <the commit created before>
</code>```

That would apply any modification done locally on top of the remote history.

Body:
Running that command said : "fatal: not a git repository (or any of the parent directories): .git"

That is the case if you run that command inside the .git folder itself.

You should run git remote -v in the parent folder of .git.

Then you can see if it references the Azure DevOps Git repository.

See "Azure Repos / Clone an existing Git repo" for more.

Actually, after discussion, it appears the .git folder was somehow corrupted.

Deleting it, re-creating it with a git init ., and re-importing it to Visual Studio was a workaround.

But that also means the commit created in it would differ from the existing history of the remote repo.

I would then, after creating a commit in the new local repo, do:

git fetch origin
git reset --hard origin/master
git cherry-pick <the commit created before>

That would apply any modification done locally on top of the remote history.


问:
Cannot complie xquery : err:XPST0003 the ':=' notation is no longer accepted in map expression
I'm trying eXist-db replication with ActiveMQ. When I configure for the consumer instance, it needs to execute a XQuery like this to register JMS receiver:

```<code>xquery version "3.0";
import module namespace replication="http://exist-db.org/xquery/replication" at "java:org.exist.jms.xquery.ReplicationModule";
let $jmsConfiguration := map {
    "java.naming.factory.initial"
            := "org.apache.activemq.jndi.ActiveMQInitialContextFactory",
    "java.naming.provider.url" := "tcp://localhost:61616",
    "connection-factory" := "ConnectionFactory",
    "destination" := "dynamicTopics/eXistdb-replication-example",
    "subscriber.name" := "SubscriptionId",
    "connection.client-id" := "ClientId"
}

return
    replication:register($jmsConfiguration)
</code>```

When I run this query, it returns an error like the title. I'm new to XQuery, so can you help me to check it ?

答:
= is redandunt, the declaration should be like this:

```<code>let $jmsConfiguration := map {
    "java.naming.factory.initial" : "org.apache.activemq.jndi.ActiveMQInitialContextFactory",
    "java.naming.provider.url" : "tcp://localhost:61616",
    "connection-factory" : "ConnectionFactory",
    "destination" : "dynamicTopics/eXistdb-replication-example",
    "subscriber.name" : "SubscriptionId",
    "connection.client-id" : "ClientId"
}
</code>```

Body:
I'm trying eXist-db replication with ActiveMQ. When I configure for the consumer instance, it needs to execute a XQuery like this to register JMS receiver:

xquery version "3.0";
import module namespace replication="http://exist-db.org/xquery/replication" at "java:org.exist.jms.xquery.ReplicationModule";
let $jmsConfiguration := map {
    "java.naming.factory.initial"
            := "org.apache.activemq.jndi.ActiveMQInitialContextFactory",
    "java.naming.provider.url" := "tcp://localhost:61616",
    "connection-factory" := "ConnectionFactory",
    "destination" := "dynamicTopics/eXistdb-replication-example",
    "subscriber.name" := "SubscriptionId",
    "connection.client-id" := "ClientId"
}

return
    replication:register($jmsConfiguration)

When I run this query, it returns an error like the title. I'm new to XQuery, so can you help me to check it ?

Body:
= is redandunt, the declaration should be like this:

let $jmsConfiguration := map {
    "java.naming.factory.initial" : "org.apache.activemq.jndi.ActiveMQInitialContextFactory",
    "java.naming.provider.url" : "tcp://localhost:61616",
    "connection-factory" : "ConnectionFactory",
    "destination" : "dynamicTopics/eXistdb-replication-example",
    "subscriber.name" : "SubscriptionId",
    "connection.client-id" : "ClientId"
}


问:
c# generics, passing class
I just can't figure out how to write an equivalent interface in c#.

Java:

```<code>public interface DAO {
    <T> T find(Class<T> c, Object key);

    <T> List<T> get(Class<T> c);

    <T> void persist(T object);
}
</code>```

This is my attempt so far in c#, problem is i need the Class to call the  dataclassesdatacontext.GetTable<Class here>().ToList();:

```<code>interface IDAO
{
    T Find<T>(object key);

    List<T> Get<T>(T c);

    void Persist<T>(T obj);
}
</code>```

I want to implement it like this:

public List<T> Get<T>()
        {
            return _dbx.GetTable<T>().ToList();
        }

where _dbx is the dataclassdatacontext (linq to sql).
But i get a red line under T which says:
The type 'T' must be a reference type in order to use it as a parameter.

答:
What you are looking for are Generic constraints. Namely you need to add where T : class to methods with T parameter.

And like Darin Dimitrov said, it might be good idea to set type for whole interface, not every method. This will result in cleaner desing.

Title: c# generics, passing class

Body:
I just can't figure out how to write an equivalent interface in c#.

Java:

public interface DAO {
    <T> T find(Class<T> c, Object key);

    <T> List<T> get(Class<T> c);

    <T> void persist(T object);
}

This is my attempt so far in c#, problem is i need the Class to call the  dataclassesdatacontext.GetTable<Class here>().ToList();:

interface IDAO
{
    T Find<T>(object key);

    List<T> Get<T>(T c);

    void Persist<T>(T obj);
}

I want to implement it like this:

public List<T> Get<T>()
        {
            return _dbx.GetTable<T>().ToList();
        }

where _dbx is the dataclassdatacontext (linq to sql).
But i get a red line under T which says:
The type 'T' must be a reference type in order to use it as a parameter.


问:
How to define NOT is sanity.io structure builder?
I'm trying to filter all products without categories (which is array of references) and can't find how to do it.

```<code>S.listItem()
  .title('Without category')
  .id('productsWithoutCategories')
    .child(
      S.documentList()
        .title('Without categories')
        .menuItems(S.documentTypeList('product').getMenuItems())
        .filter('_type == $type && !category')
        .params({ type: 'product' })
      )
</code>```

!category not working.
 I will be grateful for the help.

答:
Finded answer with Vision (really pleasant tool)

https://www.sanity.io/docs/the-vision-plugin

```<code> .filter('_type == $type && !defined(categories)')
 .params({ type: 'product' })
</code>```

Body:
I'm trying to filter all products without categories (which is array of references) and can't find how to do it.

S.listItem()
  .title('Without category')
  .id('productsWithoutCategories')
    .child(
      S.documentList()
        .title('Without categories')
        .menuItems(S.documentTypeList('product').getMenuItems())
        .filter('_type == $type && !category')
        .params({ type: 'product' })
      )

!category not working.
 I will be grateful for the help.

Body:
Finded answer with Vision (really pleasant tool)

https://www.sanity.io/docs/the-vision-plugin

 .filter('_type == $type && !defined(categories)')
 .params({ type: 'product' })


问:
Magento PHP check if user is logged in
I have the following code to see if a user is logged in. It sort of works as in it works within the customer area (user logged in) but doesn't work outside of the customer area even though the customer is still logged in.</p>

```<code><?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) { ?>
   <li class="link wishlist" data-bind="scope: 'wishlist'">
    <a <?php /* @escapeNotVerified */ echo $block->getLinkAttributes() ?>><?php echo $block->escapeHtml($block->getLabel()) ?>
        <!-- ko if: wishlist().counter -->
        <span data-bind="text: wishlist().counter" class="counter qty"></span>
        <!-- /ko -->
    </a>
</li>
<li>Hello World</li>
?>
<?php
}
else {
?>
    <li>Not logged in</li>
<?php
}
?>

<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "wishlist": {
                        "component": "Magento_Wishlist/js/view/wishlist"
                    }
                }
            }
        }
    }
</script>
</code>```

答:
In Magento 2.x PHP check if user is logged in (phtml file), you can use below code:

```<code>     $authorizationLink = $block->getLayout()->createBlock('Magento\Customer\Block\Account\AuthorizationLink');

    <?php if($authorizationLink->isLoggedIn()){
        // Customer is logged In
     }else{
        // Customer is not logged In
    }
?>
</code>```

Title: Magento PHP check if user is logged in

Body:
I have the following code to see if a user is logged in. It sort of works as in it works within the customer area (user logged in) but doesn't work outside of the customer area even though the customer is still logged in.

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) { ?>

    <a <?php /* @escapeNotVerified */ echo $block->getLinkAttributes() ?>><?php echo $block->escapeHtml($block->getLabel()) ?>

Hello World

?>
<?php
}
else {
?>

Not logged in

<?php
}
?>

Body:
In Magento 2.x PHP check if user is logged in (phtml file), you can use below code:

     $authorizationLink = $block->getLayout()->createBlock('Magento\Customer\Block\Account\AuthorizationLink');

    <?php if($authorizationLink->isLoggedIn()){
        // Customer is logged In
     }else{
        // Customer is not logged In
    }
?>


问:
Why does data import in R with fread function cause a peculiar datatype comparison bug, leading to further filtering issues
I am using data.table::fread to import a large dataset with 7.5 million rows and 56 columns.
I specify variable classes for certain variables to be read as character using colClasses argument.
Data looks fine after importing, and column classes are correctly made.

However, issues start to occur when I filter the data. Unfortunately, I can't construct an example here because I don't know exactly what the problem is.

But basically bugs occur when I use binary logic to filter some rows.

Below codes show the bug:

First of all 'id' column is read as character and str/glimpse/class/mode all confirm it. Then why does this happen:

```<code>mydata[mydata$id == 01005845, year]
[1] 2015 2014 2013 2012

mydata[mydata$id == "01005845", year]
[1] 2011 2010 2009 2008 2007 2006 2005
</code>```

To further test I rechecked the data class for these specific observations, which still shows as character:

```<code>typeof(mydata[mydata$id == 01005845, id])
[1] "character"

glimpse(mydata[mydata$id == 01005845, id])
chr [1:4] "01005845" "01005845" "01005845" "01005845"

mydata[mydata$id == 01005845, id] == 01005845
TRUE TRUE TRUE TRUE
</code>```

This does not make any sense to me because for some other id's all types are character and I don't get this weird result.

All in all this character - integer comparison inconsistency messes up all my analysis. My filterings do not work out correctly and the output gets affected badly.

I appreciate all your help.
Take care :)

答:
My guess is that is because 01005845 != "01005845"

If you type 01005845 in the console, you get

```<code>>01005845
#[1] 1005845
</code>```

01005845 is a number and the 0's at the beginning of the number do not hold any significance, hence it is stripped off. This issue is not related to data.table or fread but a general issue on how numbers are handled.

Since id column is character, you should use

```<code>mydata[id == "01005845", year]
</code>```

This small example demonstrates the issue

```<code>library(data.table)
df <- data.table(a = c('2011', '02011', '2011', '2012', '02011'), b = letters[1:5])

df[a == 02011, ]
#      a b
#1: 2011 a
#2: 2011 c

df[a == "02011", ]
#       a b
#1: 02011 b
#2: 02011 e
</code>```

Body:
I am using data.table::fread to import a large dataset with 7.5 million rows and 56 columns.
I specify variable classes for certain variables to be read as character using colClasses argument.
Data looks fine after importing, and column classes are correctly made.

However, issues start to occur when I filter the data. Unfortunately, I can't construct an example here because I don't know exactly what the problem is.

But basically bugs occur when I use binary logic to filter some rows.

Below codes show the bug:

First of all 'id' column is read as character and str/glimpse/class/mode all confirm it. Then why does this happen:

mydata[mydata$id == 01005845, year]
[1] 2015 2014 2013 2012

mydata[mydata$id == "01005845", year]
[1] 2011 2010 2009 2008 2007 2006 2005

To further test I rechecked the data class for these specific observations, which still shows as character:

typeof(mydata[mydata$id == 01005845, id])
[1] "character"

glimpse(mydata[mydata$id == 01005845, id])
chr [1:4] "01005845" "01005845" "01005845" "01005845"

mydata[mydata$id == 01005845, id] == 01005845
TRUE TRUE TRUE TRUE

This does not make any sense to me because for some other id's all types are character and I don't get this weird result.

All in all this character - integer comparison inconsistency messes up all my analysis. My filterings do not work out correctly and the output gets affected badly.

I appreciate all your help.
Take care :)

Body:
My guess is that is because 01005845 != "01005845"

If you type 01005845 in the console, you get

>01005845
#[1] 1005845

01005845 is a number and the 0's at the beginning of the number do not hold any significance, hence it is stripped off. This issue is not related to data.table or fread but a general issue on how numbers are handled.

Since id column is character, you should use

mydata[id == "01005845", year]

This small example demonstrates the issue

library(data.table)
df <- data.table(a = c('2011', '02011', '2011', '2012', '02011'), b = letters[1:5])

df[a == 02011, ]
#      a b
#1: 2011 a
#2: 2011 c

df[a == "02011", ]
#       a b
#1: 02011 b
#2: 02011 e


问:
Why the BufferedGraphics is slow in drawing?
I am using BufferedGraphics on Form_Paint event. It draws my required graphic but its too slow. Kindly give me the hints to solve this problem or any suggestions for better drawing techniques for the quick response.

```<code>BufferedGraphicsContext currentContext;
BufferedGraphics myBuffer;
// Gets a reference to the current BufferedGraphicsContext
currentContext = BufferedGraphicsManager.Current;
// Creates a BufferedGraphics instance associated with Form1, and with
// dimensions the same size as the drawing surface of Form1.
myBuffer = currentContext.Allocate(this.CreateGraphics(),
this.DisplayRectangle);
// Draws an ellipse to the graphics buffer.

myBuffer.Graphics.DrawImage(new Bitmap("C:\\Documents and Settings\\Administrator\\My Documents\\My Pictures\\Pics\\Pic.jpg"), 0, 0);
myBuffer.Graphics.DrawEllipse(Pens.Blue, 5, 90, 10, 10);
myBuffer.Graphics.DrawRectangle(Pens.Gold, 0, 7, 500, 500);
myBuffer.Graphics.DrawLine(Pens.Chartreuse, 0, 0, 800, 800);

myBuffer.Render();
</code>```

This is a small example of the BufferedGraphics, this works fine, but when the load increases, it slows down.

答:
As noted you should use:

```<code>e.Graphics
</code>```

Instead of:

```<code>this.CreateGraphics()
</code>```

And about this line:

```<code>new Bitmap("C:\\Documents and Settings\\Administrator\\My Documents\\My Pictures\\Pics\\Pic.jpg")
</code>```

You are reading the image on every frame render, you should create a Bitmap outside Paint and just refer to it.

Body:
I am using BufferedGraphics on Form_Paint event. It draws my required graphic but its too slow. Kindly give me the hints to solve this problem or any suggestions for better drawing techniques for the quick response.

BufferedGraphicsContext currentContext;
BufferedGraphics myBuffer;
// Gets a reference to the current BufferedGraphicsContext
currentContext = BufferedGraphicsManager.Current;
// Creates a BufferedGraphics instance associated with Form1, and with
// dimensions the same size as the drawing surface of Form1.
myBuffer = currentContext.Allocate(this.CreateGraphics(),
this.DisplayRectangle);
// Draws an ellipse to the graphics buffer.

myBuffer.Graphics.DrawImage(new Bitmap("C:\\Documents and Settings\\Administrator\\My Documents\\My Pictures\\Pics\\Pic.jpg"), 0, 0);
myBuffer.Graphics.DrawEllipse(Pens.Blue, 5, 90, 10, 10);
myBuffer.Graphics.DrawRectangle(Pens.Gold, 0, 7, 500, 500);
myBuffer.Graphics.DrawLine(Pens.Chartreuse, 0, 0, 800, 800);

myBuffer.Render();

This is a small example of the BufferedGraphics, this works fine, but when the load increases, it slows down.

Body:
As noted you should use:

e.Graphics

Instead of:

this.CreateGraphics()

And about this line:

new Bitmap("C:\\Documents and Settings\\Administrator\\My Documents\\My Pictures\\Pics\\Pic.jpg")

You are reading the image on every frame render, you should create a Bitmap outside Paint and just refer to it.