问:
Get Count of Sequelize BelongsToMany Association
I have two models, project and user that are associated with each other in a few ways.

First, a project is owned by a user with the following association:

```<code>Project.belongsTo(models.User, { as: 'Owner', foreignKey: 'userId' });
</code>```

Secondly, a project and user are associated by way of a user liking a project.

```<code>Project.belongsToMany(models.User, { as: 'UserLikes', through: models.ProjectLikes, foreignKey: 'projectId' });

User.belongsToMany(models.Project, { as: 'LikedProjects', through: models.ProjectLikes, foreignKey: 'userId' });
</code>```

Thirdly, a project and user can also be associated by way of a user being part of a project via a Role.

```<code>Project.belongsToMany(models.User, { as: 'Users', through: models.ProjectRoles, foreignKey: 'projectId' });

User.belongsToMany(models.Project, { as: 'Roles', through: models.ProjectRoles, foreignKey: 'userId' });
</code>```

What I am trying to achieve is to find all projects and along with them return the associated "like" count. However I am really struggling to figure out how to do this.

I have read that I should be able to do something like:

```<code>models.Project.findAll({
    limit: 5,
    attributes: ['Project.*', [models.sequelize.fn('COUNT', models.sequelize.col('UserLikes.id')), 'totalLikes']],
    include: [ { model: models.User, as: 'UserLikes' }],
    group: [ models.Project.rawAttributes.id, models.sequelize.col('UserLikes.id') ]
  })
  .then(function (projects) {
    return res.json(projects);
  });
</code>```

But I get a missing FROM-clause entry for table "UserLikes error.

I've tried changing the associations on both sides to hasMany using a specific joining-table model and then doing:

```<code>models.Project.findAll({
    limit: 5,
    attributes: ['Project.*', 'ProjectLikes.id', [models.sequelize.fn('COUNT', models.sequelize.col('ProjectLikes.id')), 'totalLikes']],
    include: [ { model: models.ProjectLikes }],
    group: [ models.Project.rawAttributes.id ]
  })
  .then(function (projects) {
    return res.json(projects);
  });
</code>```

But I get the same error, or errors about Ids being ambiguous or errors about Project.id needing to be in the GROUP BY clause (even though it is?!).

I am tearing my hair out trying to figure out something that should be really straight forward... I am almost considering switching back to MongoDB!

Please help... Thanks!

答: I have the same problem for belongsToMany, but I managed to solve it for hasMany. You have to put attributes: [] for models.ProjectLikes (inside the include) and for fixing the limit bug you have to put subQuery: false in the findAll options.

Body:
I have two models, project and user that are associated with each other in a few ways.

First, a project is owned by a user with the following association:

Project.belongsTo(models.User, { as: 'Owner', foreignKey: 'userId' });

Secondly, a project and user are associated by way of a user liking a project.

Project.belongsToMany(models.User, { as: 'UserLikes', through: models.ProjectLikes, foreignKey: 'projectId' });

User.belongsToMany(models.Project, { as: 'LikedProjects', through: models.ProjectLikes, foreignKey: 'userId' });

Thirdly, a project and user can also be associated by way of a user being part of a project via a Role.

Project.belongsToMany(models.User, { as: 'Users', through: models.ProjectRoles, foreignKey: 'projectId' });

User.belongsToMany(models.Project, { as: 'Roles', through: models.ProjectRoles, foreignKey: 'userId' });

What I am trying to achieve is to find all projects and along with them return the associated "like" count. However I am really struggling to figure out how to do this.

I have read that I should be able to do something like:

models.Project.findAll({
    limit: 5,
    attributes: ['Project.*', [models.sequelize.fn('COUNT', models.sequelize.col('UserLikes.id')), 'totalLikes']],
    include: [ { model: models.User, as: 'UserLikes' }],
    group: [ models.Project.rawAttributes.id, models.sequelize.col('UserLikes.id') ]
  })
  .then(function (projects) {
    return res.json(projects);
  });

But I get a missing FROM-clause entry for table "UserLikes error.

I've tried changing the associations on both sides to hasMany using a specific joining-table model and then doing:

models.Project.findAll({
    limit: 5,
    attributes: ['Project.*', 'ProjectLikes.id', [models.sequelize.fn('COUNT', models.sequelize.col('ProjectLikes.id')), 'totalLikes']],
    include: [ { model: models.ProjectLikes }],
    group: [ models.Project.rawAttributes.id ]
  })
  .then(function (projects) {
    return res.json(projects);
  });

But I get the same error, or errors about Ids being ambiguous or errors about Project.id needing to be in the GROUP BY clause (even though it is?!).

I am tearing my hair out trying to figure out something that should be really straight forward... I am almost considering switching back to MongoDB!

Please help... Thanks!


来源: stackexchange

问:
Python CSV DictReader with UTF-8 data
AFAIK, the Python (v2.6) csv module can't handle unicode data by default, correct? In the Python docs there's an example on how to read from a UTF-8 encoded file. But this example only returns the CSV rows as a list.
I'd like to access the row columns by name as it is done by csv.DictReader but with UTF-8 encoded CSV input file.

Can anyone tell me how to do this in an efficient way? I will have to process CSV files in 100's of MByte in size.

答:
That's easy with the unicodecsv package.

# pip install unicodecsv
import unicodecsv as csv

with open('your_file.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row)
```

ContentLicense: CC BY-SA 3.0

Title: Python CSV DictReader with UTF-8 data

ContentLicense: CC BY-SA 4.0


问:
Display validation messages in struts 2
I have a form in my application in which I want to validate the user inputs. It has a combo box which is populated from db table. So I have to go to the action class first to populate it(for eg: populateFormAction). Then it will go to form.jsp page.

But the problem is at the time of validation. I have set populateFormAction as input result as follows

```<code><result name="input" type="redirect">/populateFormAction</result>
</code>```

But when it returned to form.jsp, it doesn't show the validation errors. I think it is because of the use of populateFormAction in between Action handler and form.jsp.

答:
There are two solutions to your problem

Call the method which is populating
the combo, efore returning INPUT (if
there is any validation error). And
then dont use type redirect, instead
directly move to your form.jsp. Of
course, this would be possible if
you have the populate combo and
validate methods in the same action
class.

Pass your action errors as parameters to the populateFormAction
as follows.Take a look here

I m not sure whether there will be 's' after actionError or not, so try both

Title: Display validation messages in struts 2

Body:
I have a form in my application in which I want to validate the user inputs. It has a combo box which is populated from db table. So I have to go to the action class first to populate it(for eg: populateFormAction). Then it will go to form.jsp page.

But the problem is at the time of validation. I have set populateFormAction as input result as follows

<result name="input" type="redirect">/populateFormAction</result>

But when it returned to form.jsp, it doesn't show the validation errors. I think it is because of the use of populateFormAction in between Action handler and form.jsp.


问:
Why is httr not reading a response-class object?
I'm trying to update a project from March 2018. Previously, I had used

library("httr")
library("rjson")
api.url <- "http://api.tvmaze.com/lookup/shows?imdb=tt1325113"
response <- GET(api.url)
response.list <- fromJSON(content(response))
```

<p>Previously, this returned a list containing the parsed json information that I used sapply to extract the relevant information from. Now, it's showing</p>

<pre class="lang-r prettyprint-override"><code>Error in UseMethod("content", x) :
  no applicable method for 'content' applied to an object of class "response"
</code>```

There appears to be some kind of change in the httr package but I can't figure out what it is. Any ideas of what might be different and how to get around it?

答:
You have to specify the as argument of content, the code below should do the trick.

```<code>library("httr")
library("rjson")
api.url <- "http://api.tvmaze.com/lookup/shows?imdb=tt1325113"
response <- GET(api.url)

response.list <-
  fromJSON(content(response, as = "text"))
</code>```

Body:
I'm trying to update a project from March 2018. Previously, I had used

library("httr")
library("rjson")
api.url <- "http://api.tvmaze.com/lookup/shows?imdb=tt1325113"
response <- GET(api.url)
response.list <- fromJSON(content(response))

Previously, this returned a list containing the parsed json information that I used sapply to extract the relevant information from. Now, it's showing

Error in UseMethod("content", x) :
  no applicable method for 'content' applied to an object of class "response"

There appears to be some kind of change in the httr package but I can't figure out what it is. Any ideas of what might be different and how to get around it?

Body:
You have to specify the as argument of content, the code below should do the trick.

library("httr")
library("rjson")
api.url <- "http://api.tvmaze.com/lookup/shows?imdb=tt1325113"
response <- GET(api.url)

response.list <-
  fromJSON(content(response, as = "text"))


问:
Comparing a datetime dataframe with a period dataframe
I have been stuck with a simple pandas dataframe problem and maybe someone faced this situation before...

Thank you in advance :)

Hi have two dataframes, df1 and df2:

df1

```<code>unique_id    timestamp
1            2019-01-21
2            2019-02-01
3            2019-04-05
4            2019-05-01
5            2019-05-12
...          ...
</code>```

df2

```<code>classification     from            to
A                  2019-01-05      2019-02-02
B                  2019-02-03      2019-02-28
C                  2019-03-01      2019-04-05
D                  2019-04-06      2019-05-03
E                  2019-05-04      2019-05-31
...                ...             ...
</code>```

My goal is to compare each timestamp in df1 with each from to date interval in df2 and be able to classify every unique_id of df1 with the correspondent classification of df2

I was trying something like this:

```<code>df1.loc[(df1['timestamp'] > df2['from]) & (df1['timestamp'] < df2['to']), 'class'] = df2['classification']´
</code>```

always get a ValueError: Can only compare identically-labeled Series objects despite both datetime dtypes are the exact same, datetime64[ns]...

Expected Output:

```<code>unique_id         timestamp        classification
1                 2019-01-21       A
2                 2019-02-01       A
3                 2019-04-05       C
4                 2019-05-01       D
5                 2019-05-12       E
...               ...              ...
</code>```

答:
what i would personally do is convert timestamp to unix timestamp.

```<code>for row in df1['timestamp']:
    row = int(mktime(row.timetuple())
</code>```

do the same for df2 to get your start and end timestamps and so then you can use the df1.loc[(df1['timestamp'] > df2['from]) & (df1['timestamp'] < df2['to']), 'class'] = df2['classification']´ you wrote w/o getting error message

Body:
I have been stuck with a simple pandas dataframe problem and maybe someone faced this situation before...

Thank you in advance :)

Hi have two dataframes, df1 and df2:

df1

unique_id    timestamp
1            2019-01-21
2            2019-02-01
3            2019-04-05
4            2019-05-01
5            2019-05-12
...          ...

df2

classification     from            to
A                  2019-01-05      2019-02-02
B                  2019-02-03      2019-02-28
C                  2019-03-01      2019-04-05
D                  2019-04-06      2019-05-03
E                  2019-05-04      2019-05-31
...                ...             ...

My goal is to compare each timestamp in df1 with each from to date interval in df2 and be able to classify every unique_id of df1 with the correspondent classification of df2

I was trying something like this:

df1.loc[(df1['timestamp'] > df2['from]) & (df1['timestamp'] < df2['to']), 'class'] = df2['classification']´

always get a ValueError: Can only compare identically-labeled Series objects despite both datetime dtypes are the exact same, datetime64[ns]...

Expected Output:

unique_id         timestamp        classification
1                 2019-01-21       A
2                 2019-02-01       A
3                 2019-04-05       C
4                 2019-05-01       D
5                 2019-05-12       E
...               ...              ...

Body:
what i would personally do is convert timestamp to unix timestamp.

for row in df1['timestamp']:
    row = int(mktime(row.timetuple())

do the same for df2 to get your start and end timestamps and so then you can use the df1.loc[(df1['timestamp'] > df2['from]) & (df1['timestamp'] < df2['to']), 'class'] = df2['classification']´ you wrote w/o getting error message


问:
How to merge multiple single-page TIFFs into a PDF with PHP?
I have a massive number of TIFF images which are single scanned pages. They are each a page of multi-page documents.

I need to be able to deliver this multi-page document to my users as a PDF. Nothing special is required except combining the images into one document, in the right order.

The images locations are provided via the result of a MySQL query in PHP as an array, i.e:

```<code>c:\images\04\DUDDSDFF.tif,c:\images\04\EDFRTOFN.tif,c:\images\04\EFSDOSDG.tif
</code>```

The current dev environment I am working in uses XAMPP running on Win Server 2K3.

Any suggestions/solutions would be most appreciated.

Cheers

答:
The answer from @chariothy is close but doesn't actually work. I just had a need to combine multiple tif files into a single pdf file and this is my solution, tested and working.</p>

```<code>$pdf = new \Imagick();

foreach ($tif_file_paths as $file_path){

    $pdf->addImage(new \Imagick($file_path));
}

$pdf->writeImages('path/to/save/file/test-combined.pdf', true);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a massive number of TIFF images which are single scanned pages. They are each a page of multi-page documents.

I need to be able to deliver this multi-page document to my users as a PDF. Nothing special is required except combining the images into one document, in the right order.

The images locations are provided via the result of a MySQL query in PHP as an array, i.e:

c:\images\04\DUDDSDFF.tif,c:\images\04\EDFRTOFN.tif,c:\images\04\EFSDOSDG.tif

The current dev environment I am working in uses XAMPP running on Win Server 2K3.

Any suggestions/solutions would be most appreciated.

Cheers

Body:
The answer from @chariothy is close but doesn't actually work. I just had a need to combine multiple tif files into a single pdf file and this is my solution, tested and working.

$pdf = new \Imagick();

foreach ($tif_file_paths as $file_path){

    $pdf->addImage(new \Imagick($file_path));
}

$pdf->writeImages('path/to/save/file/test-combined.pdf', true);


问:
copying and pasting information between datasets
How to copy data fully from one dataset to another dataset when one of the dataset consists of dots as shown bllow ?

答:
It's not clear to me what question you're asking, or why you'd do such a thing by hand.  I'd instead suggest using one of the built in z/OS tools.  Specifically, IEBCOPY.

```<code>//COPYLIKE JOB MSGCLASS=H,TIME=1440
//COPYREP  EXEC PGM=IEBCOPY
//SYSPRINT DD SYSOUT=*
//SYSUT1   DD DSN=SYS1.LPALIB,DISP=SHR,UNIT=3390,VOL=SER=D83RL2
//SYSUT2   DD DSN=SYS1.LPALIB.ORIG,
//        LIKE=SYS1.LPALIB,
//        DISP=(NEW,KEEP),VOL=SER=D83RL2,UNIT=3390
//SYSIN    DD *
/*
</code>```

Also, as a note, the source dataset doesn't consist of dots, it consists of undisplayable data.

Body:
It's not clear to me what question you're asking, or why you'd do such a thing by hand.  I'd instead suggest using one of the built in z/OS tools.  Specifically, IEBCOPY.

//COPYLIKE JOB MSGCLASS=H,TIME=1440
//COPYREP  EXEC PGM=IEBCOPY
//SYSPRINT DD SYSOUT=*
//SYSUT1   DD DSN=SYS1.LPALIB,DISP=SHR,UNIT=3390,VOL=SER=D83RL2
//SYSUT2   DD DSN=SYS1.LPALIB.ORIG,
//        LIKE=SYS1.LPALIB,
//        DISP=(NEW,KEEP),VOL=SER=D83RL2,UNIT=3390
//SYSIN    DD *
/*

Also, as a note, the source dataset doesn't consist of dots, it consists of undisplayable data.


问:
ActiveResource "NoMethodError (undefined method `path' for nil:NilClass):" intermittent error
I'm encountering an intermittent error where an ActiveResource resource call like:

Cart.where(session_id: get_guid, status: 1)
```

<p>Raises an error:</p>

```NoMethodError (undefined method `path' for nil:NilClass)
```

But only intermittently. Restarting the Rails server temporarily solves the problem, but some indeterminate time later, it breaks again.

答:
The source of the issue was due to Rails' autoloading feature. A few realizations led me to this solution.

We had many ActiveResource resources, so in order to easily initialize the resources we placed the setup in an initializer (which is only run during Rails server startup):

# config/initializers/active_resource_setup.rb

Cart.site = ENV["ROOT_URL"]
```

<p>I also realized that this was not an issue in a production environment. This wasn't as clear before because this issue appeared during a significant Rails upgrade, so I assumed I had broken it to begin with.</p>

<p>However, the source of the issue was Rails automatically reloading the resource class definition files whenever a change was made to the source. It would reload the class definition:</p>

<pre class="lang-rb prettyprint-override"><code># app/models/resources/cart.rb

class Cart < ActiveResource::Base
  validates :session_id, presence: true
end
</code>```

And because the Cart.site definition was not in this file as intended, the resource was effectively reset, and the site configuration clobbered by the auto-reload process.

The solution is to move the Cart.site definition into the resource definition:

# app/models/resources/cart.rb

class Cart < ActiveResource::Base
  self.site = ENV["ROOT_URL"]

  validates :session_id, presence: true
end
```

Body:
I'm encountering an intermittent error where an ActiveResource resource call like:

Cart.where(session_id: get_guid, status: 1)

Raises an error:

NoMethodError (undefined method `path' for nil:NilClass)

But only intermittently. Restarting the Rails server temporarily solves the problem, but some indeterminate time later, it breaks again.

Body:
The source of the issue was due to Rails' autoloading feature. A few realizations led me to this solution.

We had many ActiveResource resources, so in order to easily initialize the resources we placed the setup in an initializer (which is only run during Rails server startup):

# config/initializers/active_resource_setup.rb

Cart.site = ENV["ROOT_URL"]

I also realized that this was not an issue in a production environment. This wasn't as clear before because this issue appeared during a significant Rails upgrade, so I assumed I had broken it to begin with.

However, the source of the issue was Rails automatically reloading the resource class definition files whenever a change was made to the source. It would reload the class definition:

# app/models/resources/cart.rb

class Cart < ActiveResource::Base
  validates :session_id, presence: true
end

And because the Cart.site definition was not in this file as intended, the resource was effectively reset, and the site configuration clobbered by the auto-reload process.

The solution is to move the Cart.site definition into the resource definition:

# app/models/resources/cart.rb

class Cart < ActiveResource::Base
  self.site = ENV["ROOT_URL"]

  validates :session_id, presence: true
end


问:
Unexpected result when displaying static html table in Shiny
I want to display a html-table in a shiny page. The table is generated by a function and uses the following data:

```<code>rep_loop <- data.frame(Activity = LETTERS[1:3], ID_resource_rep = sample(1:10, 3),
  Div_resource_rep = sample(1:10, 3),
  ID_resource_loop = sample(1:10, 3),
  Div_resource_loop = sample(1:10, 3))

build_table <- function(data){
  html.table <-
    tags$table(style = "border:1px solid black; padding: 3%; width: 80%",
      tags$tr(
        tags$th(" "),
        tags$th(colspan = 2, "Repeat (Act-X-Act)"),
        tags$th(colspan = 2, "Selfloop (Act-Act)")
      ),
      tags$tr(
        tags$th(" "),
        tags$th("Same Resource"),
        tags$th("Other Resource"),
        tags$th("Same Resource"),
        tags$th("Other Resource")
      ),
      tags$tr(
        tags$td(data$Activity),
        tags$td(data$ID_resource_rep),
        tags$td(data$Div_resource_rep),
        tags$td(data$ID_resource_loop),
        tags$td(data$Div_resource_loop)
      )
  )
  return(html.table)
}
</code>```

This is the result from

```<code>test <- build_table(rep_loop)

<table style="border:1px solid black; padding: 5%; width: 80%">
  <tr>
    <th> </th>
    <th colspan="2">Repeat (Act-X-Act)</th>
    <th colspan="2">Selfloop (Act-Act)</th>
  </tr>
  <tr>
    <th> </th>
    <th>Same Resource</th>
    <th>Other Resource</th>
    <th>Same Resource</th>
    <th>Other Resource</th>
  </tr>
  <tr>
    <td>A</td>
    <td>1</td>
    <td>1</td>
    <td>4</td>
    <td>6</td>
  </tr>
</table>
Warning messages:
1: In charToRaw(enc2utf8(text)) :
  argument should be a character vector of length 1
  all but the first element will be ignored
2: In charToRaw(enc2utf8(text)) :
  argument should be a character vector of length 1
  all but the first element will be ignored
3: In charToRaw(enc2utf8(text)) :
  argument should be a character vector of length 1
  all but the first element will be ignored
4: In charToRaw(enc2utf8(text)) :
  argument should be a character vector of length 1
  all but the first element will be ignored
5: In charToRaw(enc2utf8(text)) :
  argument should be a character vector of length 1
  all but the first element will be ignored
</code>```

I would expect that build_table would return a table with a header, followed by data-lines. The header is as expected but instead of using all the rows from the data.frame, it shows only the first line, followed by 5 warnings.

Where did I make a mistake?

Ben

答:
That's because you can't have a vector in a tags$td. Do:

```<code>rep_loop <- data.frame(Activity = LETTERS[1:3], ID_resource_rep = sample(1:10, 3),
                       Div_resource_rep = sample(1:10, 3),
                       ID_resource_loop = sample(1:10, 3),
                       Div_resource_loop = sample(1:10, 3))

build_table <- function(data){
  html.table <-
    tags$table(style = "border:1px solid black; padding: 3%; width: 80%",
               tags$tr(
                 tags$th(" "),
                 tags$th(colspan = 2, "Repeat (Act-X-Act)"),
                 tags$th(colspan = 2, "Selfloop (Act-Act)")
               ),
               tags$tr(
                 tags$th(" "),
                 tags$th("Same Resource"),
                 tags$th("Other Resource"),
                 tags$th("Same Resource"),
                 tags$th("Other Resource")
               ),
               mapply(function(x1,x2,x3,x4,x5){
                 tags$tr(
                   tags$td(x1),
                   tags$td(x2),
                   tags$td(x3),
                   tags$td(x4),
                   tags$td(x5)
                 )
               }, data$Activity,
                  data$ID_resource_rep,
                  data$Div_resource_rep,
                  data$ID_resource_loop,
                  data$Div_resource_loop,
               SIMPLIFY = FALSE)
    )
  return(html.table)
}

build_table(rep_loop)
</code>```

```<code><table style="border:1px solid black; padding: 3%; width: 80%">
  <tr>
    <th> </th>
    <th colspan="2">Repeat (Act-X-Act)</th>
    <th colspan="2">Selfloop (Act-Act)</th>
  </tr>
  <tr>
    <th> </th>
    <th>Same Resource</th>
    <th>Other Resource</th>
    <th>Same Resource</th>
    <th>Other Resource</th>
  </tr>
  <tr>
    <td>A</td>
    <td>5</td>
    <td>10</td>
    <td>4</td>
    <td>2</td>
  </tr>
  <tr>
    <td>B</td>
    <td>6</td>
    <td>8</td>
    <td>3</td>
    <td>3</td>
  </tr>
  <tr>
    <td>C</td>
    <td>3</td>
    <td>7</td>
    <td>2</td>
    <td>5</td>
  </tr>
</table>
</code>```

Body:
I want to display a html-table in a shiny page. The table is generated by a function and uses the following data:

rep_loop <- data.frame(Activity = LETTERS[1:3], ID_resource_rep = sample(1:10, 3),
  Div_resource_rep = sample(1:10, 3),
  ID_resource_loop = sample(1:10, 3),
  Div_resource_loop = sample(1:10, 3))

build_table <- function(data){
  html.table <-
    tags$table(style = "border:1px solid black; padding: 3%; width: 80%",
      tags$tr(
        tags$th(" "),
        tags$th(colspan = 2, "Repeat (Act-X-Act)"),
        tags$th(colspan = 2, "Selfloop (Act-Act)")
      ),
      tags$tr(
        tags$th(" "),
        tags$th("Same Resource"),
        tags$th("Other Resource"),
        tags$th("Same Resource"),
        tags$th("Other Resource")
      ),
      tags$tr(
        tags$td(data$Activity),
        tags$td(data$ID_resource_rep),
        tags$td(data$Div_resource_rep),
        tags$td(data$ID_resource_loop),
        tags$td(data$Div_resource_loop)
      )
  )
  return(html.table)
}

This is the result from

test <- build_table(rep_loop)

    Repeat (Act-X-Act)
    Selfloop (Act-Act)

    Same Resource
    Other Resource
    Same Resource
    Other Resource

    A
    1
    1
    4
    6

Warning messages:
1: In charToRaw(enc2utf8(text)) :
  argument should be a character vector of length 1
  all but the first element will be ignored
2: In charToRaw(enc2utf8(text)) :
  argument should be a character vector of length 1
  all but the first element will be ignored
3: In charToRaw(enc2utf8(text)) :
  argument should be a character vector of length 1
  all but the first element will be ignored
4: In charToRaw(enc2utf8(text)) :
  argument should be a character vector of length 1
  all but the first element will be ignored
5: In charToRaw(enc2utf8(text)) :
  argument should be a character vector of length 1
  all but the first element will be ignored

I would expect that build_table would return a table with a header, followed by data-lines. The header is as expected but instead of using all the rows from the data.frame, it shows only the first line, followed by 5 warnings.

Where did I make a mistake?

Ben

Body:
That's because you can't have a vector in a tags$td. Do:

rep_loop <- data.frame(Activity = LETTERS[1:3], ID_resource_rep = sample(1:10, 3),
                       Div_resource_rep = sample(1:10, 3),
                       ID_resource_loop = sample(1:10, 3),
                       Div_resource_loop = sample(1:10, 3))

build_table <- function(data){
  html.table <-
    tags$table(style = "border:1px solid black; padding: 3%; width: 80%",
               tags$tr(
                 tags$th(" "),
                 tags$th(colspan = 2, "Repeat (Act-X-Act)"),
                 tags$th(colspan = 2, "Selfloop (Act-Act)")
               ),
               tags$tr(
                 tags$th(" "),
                 tags$th("Same Resource"),
                 tags$th("Other Resource"),
                 tags$th("Same Resource"),
                 tags$th("Other Resource")
               ),
               mapply(function(x1,x2,x3,x4,x5){
                 tags$tr(
                   tags$td(x1),
                   tags$td(x2),
                   tags$td(x3),
                   tags$td(x4),
                   tags$td(x5)
                 )
               }, data$Activity,
                  data$ID_resource_rep,
                  data$Div_resource_rep,
                  data$ID_resource_loop,
                  data$Div_resource_loop,
               SIMPLIFY = FALSE)
    )
  return(html.table)
}

build_table(rep_loop)

<table style="border:1px solid black; padding: 3%; width: 80%">
  <tr>
    <th> </th>
    <th colspan="2">Repeat (Act-X-Act)</th>
    <th colspan="2">Selfloop (Act-Act)</th>
  </tr>
  <tr>
    <th> </th>
    <th>Same Resource</th>
    <th>Other Resource</th>
    <th>Same Resource</th>
    <th>Other Resource</th>
  </tr>
  <tr>
    <td>A</td>
    <td>5</td>
    <td>10</td>
    <td>4</td>
    <td>2</td>
  </tr>
  <tr>
    <td>B</td>
    <td>6</td>
    <td>8</td>
    <td>3</td>
    <td>3</td>
  </tr>
  <tr>
    <td>C</td>
    <td>3</td>
    <td>7</td>
    <td>2</td>
    <td>5</td>
  </tr>
</table>


问:
how do i set a dynamic object in JS?
I want to keep a value from a form by a js function
with document.getElementById("form1")

but in the form there are dynamic inputs amount1 , amount2 ect... (i dont know how many - its from database)

how do i reach form1.amount (p)

when p is the index of the amount ?

thanks

答:
You can retrieve it like this:

```<code> var frm = document.getElementById("form1");
 if (frm) {
     var valueA = frm["amount" + 1].value;
 }
</code>```

A more complete example:

```<code><html>
    <form id="f1">
        <input name="input1" value="text" type="text" />
    </form>

    <script>
        var f = document.getElementById("f1");
        if(f)
        {
            alert(f["input"+1]);
            alert(f["input"+1].value);
        }
    </script>
</html>
</code>```

Title: how do i set a dynamic object in JS?

Body:
You can retrieve it like this:

 var frm = document.getElementById("form1");
 if (frm) {
     var valueA = frm["amount" + 1].value;
 }

A more complete example:

<html>
    <form id="f1">
        <input name="input1" value="text" type="text" />
    </form>

    <script>
        var f = document.getElementById("f1");
        if(f)
        {
            alert(f["input"+1]);
            alert(f["input"+1].value);
        }
    </script>
</html>


问:
Understanding default queue channel / capacity behavior
I'm having a strange issue with spring integration priority channel (or that's at least where I think things go wrong). I have the following flow:

```<code>IntegrationFlows
                .from(fileReadingMessageSource,
                        c -> c.poller(Pollers.fixedDelay(period)
                                             .taskExecutor(Executors.newFixedThreadPool(poolSize))
                                             .maxMessagesPerPoll(maxMessagesPerPoll)))
                .channel("alphabetically")
                .bridge(s -> s.poller(Pollers.fixedDelay(100)))
                .channel(ApplicationConfiguration.INBOUND_CHANNEL)
                .get();
</code>```

And the priority channel with capacity 1'000:

```<code>@Bean
    public PriorityChannel alphabetically(@Value("${inbound.sort.queue-capacity}") int capacity) {
        return new PriorityChannel(capacity, Comparator.comparing(left -> ((File) left.getPayload()).getName()));
    }
</code>```

I'm using this flow to read about 20'000 files from the input directory. Everything works fine but after around 2'000 files the flow stops working and it's not picking up any new files.

I thought that the default behavior of the queue channel is that when it reaches the capacity, it will simply wait for the capacity to be released and accept the next files that would be queued? But I might got it wrong... If it's not the case and there is some timeout for the files that would be picked up by the poller and wouldn't have enough space in the priority channel, what would be your suggestion to work around it?

答:
Add some logging to see what's going on; this works fine for me...

@SpringBootApplication
public class So56259801Application {

    public static void main(String[] args) {
        SpringApplication.run(So56259801Application.class, args);
    }

    private int i;

    @Bean
    public IntegrationFlow flow() {
        return IntegrationFlows.from(() -> "foo" + i++, e -> e.poller(Pollers.fixedDelay(5_000)
                    .taskExecutor(Executors.newFixedThreadPool(1))))
                .log()
                .channel(MessageChannels.queue(3))
                .bridge(b -> b.poller(Pollers.fixedDelay(10_000)))
                .log()
                .get();
    }

}
```

<p>and</p>

```2019-05-28 13:43:59.719  INFO 75315 --- [pool-1-thread-1] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo0, headers={id=d87cba1d-dc6b-fdf4-56ed-61f08048851b, timestamp=1559065439718}]
2019-05-28 13:43:59.719  INFO 75315 --- [ask-scheduler-2] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo0, headers={id=d87cba1d-dc6b-fdf4-56ed-61f08048851b, timestamp=1559065439718}]
2019-05-28 13:43:59.724  INFO 75315 --- [           main] com.example.So56259801Application        : Started So56259801Application in 0.832 seconds (JVM running for 1.242)
2019-05-28 13:44:04.719  INFO 75315 --- [pool-1-thread-1] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo1, headers={id=8b7676e6-9bac-cdf0-4f4c-38513267b666, timestamp=1559065444719}]
2019-05-28 13:44:09.721  INFO 75315 --- [pool-1-thread-1] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo2, headers={id=3b5346f8-d007-dd33-bee3-28eed4cfbd00, timestamp=1559065449721}]
2019-05-28 13:44:10.727  INFO 75315 --- [ask-scheduler-3] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo1, headers={id=8b7676e6-9bac-cdf0-4f4c-38513267b666, timestamp=1559065444719}]
2019-05-28 13:44:10.727  INFO 75315 --- [ask-scheduler-3] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo2, headers={id=3b5346f8-d007-dd33-bee3-28eed4cfbd00, timestamp=1559065449721}]
2019-05-28 13:44:14.723  INFO 75315 --- [pool-1-thread-1] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo3, headers={id=84df8665-1aa9-df90-2037-4dd1781b1bf3, timestamp=1559065454723}]
2019-05-28 13:44:19.727  INFO 75315 --- [pool-1-thread-1] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo4, headers={id=4e81897b-a19c-4789-529a-46266762ccc6, timestamp=1559065459727}]
2019-05-28 13:44:21.733  INFO 75315 --- [ask-scheduler-2] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo3, headers={id=84df8665-1aa9-df90-2037-4dd1781b1bf3, timestamp=1559065454723}]
2019-05-28 13:44:21.733  INFO 75315 --- [ask-scheduler-2] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo4, headers={id=4e81897b-a19c-4789-529a-46266762ccc6, timestamp=1559065459727}]
2019-05-28 13:44:24.730  INFO 75315 --- [pool-1-thread-1] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo5, headers={id=3fb96f4a-7d25-f94a-23d2-d4a121932554, timestamp=1559065464730}]
```

Body:
I'm having a strange issue with spring integration priority channel (or that's at least where I think things go wrong). I have the following flow:

IntegrationFlows
                .from(fileReadingMessageSource,
                        c -> c.poller(Pollers.fixedDelay(period)
                                             .taskExecutor(Executors.newFixedThreadPool(poolSize))
                                             .maxMessagesPerPoll(maxMessagesPerPoll)))
                .channel("alphabetically")
                .bridge(s -> s.poller(Pollers.fixedDelay(100)))
                .channel(ApplicationConfiguration.INBOUND_CHANNEL)
                .get();

And the priority channel with capacity 1'000:

@Bean
    public PriorityChannel alphabetically(@Value("${inbound.sort.queue-capacity}") int capacity) {
        return new PriorityChannel(capacity, Comparator.comparing(left -> ((File) left.getPayload()).getName()));
    }

I'm using this flow to read about 20'000 files from the input directory. Everything works fine but after around 2'000 files the flow stops working and it's not picking up any new files.

I thought that the default behavior of the queue channel is that when it reaches the capacity, it will simply wait for the capacity to be released and accept the next files that would be queued? But I might got it wrong... If it's not the case and there is some timeout for the files that would be picked up by the poller and wouldn't have enough space in the priority channel, what would be your suggestion to work around it?

Body:
Add some logging to see what's going on; this works fine for me...

@SpringBootApplication
public class So56259801Application {

    public static void main(String[] args) {
        SpringApplication.run(So56259801Application.class, args);
    }

    private int i;

    @Bean
    public IntegrationFlow flow() {
        return IntegrationFlows.from(() -> "foo" + i++, e -> e.poller(Pollers.fixedDelay(5_000)
                    .taskExecutor(Executors.newFixedThreadPool(1))))
                .log()
                .channel(MessageChannels.queue(3))
                .bridge(b -> b.poller(Pollers.fixedDelay(10_000)))
                .log()
                .get();
    }

}

and

2019-05-28 13:43:59.719  INFO 75315 --- [pool-1-thread-1] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo0, headers={id=d87cba1d-dc6b-fdf4-56ed-61f08048851b, timestamp=1559065439718}]
2019-05-28 13:43:59.719  INFO 75315 --- [ask-scheduler-2] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo0, headers={id=d87cba1d-dc6b-fdf4-56ed-61f08048851b, timestamp=1559065439718}]
2019-05-28 13:43:59.724  INFO 75315 --- [           main] com.example.So56259801Application        : Started So56259801Application in 0.832 seconds (JVM running for 1.242)
2019-05-28 13:44:04.719  INFO 75315 --- [pool-1-thread-1] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo1, headers={id=8b7676e6-9bac-cdf0-4f4c-38513267b666, timestamp=1559065444719}]
2019-05-28 13:44:09.721  INFO 75315 --- [pool-1-thread-1] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo2, headers={id=3b5346f8-d007-dd33-bee3-28eed4cfbd00, timestamp=1559065449721}]
2019-05-28 13:44:10.727  INFO 75315 --- [ask-scheduler-3] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo1, headers={id=8b7676e6-9bac-cdf0-4f4c-38513267b666, timestamp=1559065444719}]
2019-05-28 13:44:10.727  INFO 75315 --- [ask-scheduler-3] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo2, headers={id=3b5346f8-d007-dd33-bee3-28eed4cfbd00, timestamp=1559065449721}]
2019-05-28 13:44:14.723  INFO 75315 --- [pool-1-thread-1] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo3, headers={id=84df8665-1aa9-df90-2037-4dd1781b1bf3, timestamp=1559065454723}]
2019-05-28 13:44:19.727  INFO 75315 --- [pool-1-thread-1] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo4, headers={id=4e81897b-a19c-4789-529a-46266762ccc6, timestamp=1559065459727}]
2019-05-28 13:44:21.733  INFO 75315 --- [ask-scheduler-2] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo3, headers={id=84df8665-1aa9-df90-2037-4dd1781b1bf3, timestamp=1559065454723}]
2019-05-28 13:44:21.733  INFO 75315 --- [ask-scheduler-2] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo4, headers={id=4e81897b-a19c-4789-529a-46266762ccc6, timestamp=1559065459727}]
2019-05-28 13:44:24.730  INFO 75315 --- [pool-1-thread-1] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=foo5, headers={id=3fb96f4a-7d25-f94a-23d2-d4a121932554, timestamp=1559065464730}]


问:
NaN when adding two numbers
Why explosion.pdi can be (and is) NaN after adding a number (explosion.ppsd) to it ?

Console logs : (you can see the two are Number and not NaN before the addition, and explosion.pdi is NaN after)

```<code>console.log('before: pdi = ' + explosion.pdi + ' | ppsd = ' + explosion.ppsd);
console.log('typeof pdi = ' + typeof(explosion.pdi) + ' | typeof ppsd = ' + typeof(explosion.ppsd));

explosion.pdi += explosion.ppsp; // Here :

console.log('after: pdi = ' + explosion.pdi + ' | ppsd = ' + explosion.ppsd);
console.log('typeof pdi = ' + typeof(explosion.pdi) + ' | typeof ppsd = ' + typeof(explosion.ppsd));
</code>```

Edit: Sorry, typo problem (ppsp => ppsd)

答:
You don't have any property such as ppsp

```<code>explosion.pdi += explosion.ppsp   <----
                           ^^^^
</code>```

so you end up with

```<code>explosion.pdi += undefined   // NaN
</code>```

it should be

```<code>explosion.pdi += explosion.ppsd
</code>```

Title: NaN when adding two numbers

Body:
Why explosion.pdi can be (and is) NaN after adding a number (explosion.ppsd) to it ?

Console logs : (you can see the two are Number and not NaN before the addition, and explosion.pdi is NaN after)

console.log('before: pdi = ' + explosion.pdi + ' | ppsd = ' + explosion.ppsd);
console.log('typeof pdi = ' + typeof(explosion.pdi) + ' | typeof ppsd = ' + typeof(explosion.ppsd));

explosion.pdi += explosion.ppsp; // Here :

console.log('after: pdi = ' + explosion.pdi + ' | ppsd = ' + explosion.ppsd);
console.log('typeof pdi = ' + typeof(explosion.pdi) + ' | typeof ppsd = ' + typeof(explosion.ppsd));

Edit: Sorry, typo problem (ppsp => ppsd)

Body:
You don't have any property such as ppsp

explosion.pdi += explosion.ppsp   <----
                           ^^^^

so you end up with

explosion.pdi += undefined   // NaN

it should be

explosion.pdi += explosion.ppsd


问:
Dynamic query (in stored procedure) based on params provided (SQL Server 2016)
I have an employee table that has over 30 columns. This table is exposed by a web service via a stored procedure that returns all users.

I need to create a new stored procedure that allows you to search on 6 specific columns. I have those columns as input params for the stored procedure, but I am unsure how to create a query that only uses the params that were passed.

For example:

```<code>exec SearchUsers @firstName = 'John', @department = 'Admin'
</code>```

should perform a query only those columns. However, there are 5 available params that can be passed in.

Here are my parameters

```<code>@lastName nvarchar(255) = '',
@firstName nvarchar(255)  = '',
@office nvarchar(50)  = '',
@department nvarchar(50)  = '',
@language nvarchar(255)  = '',
@jobTitle nvarchar(255) = '',
</code>```

I want to build a query that is dynamic enough to only query the values provided.

答: On the where clause, beyond your normal condition, for each param you just have to add a condition OR @param1 IS NULL. So if the param is null, the whole condition will be "ignored" since it will always be true.

Body:
I have an employee table that has over 30 columns. This table is exposed by a web service via a stored procedure that returns all users.

I need to create a new stored procedure that allows you to search on 6 specific columns. I have those columns as input params for the stored procedure, but I am unsure how to create a query that only uses the params that were passed.

For example:

exec SearchUsers @firstName = 'John', @department = 'Admin'

should perform a query only those columns. However, there are 5 available params that can be passed in.

Here are my parameters

@lastName nvarchar(255) = '',
@firstName nvarchar(255)  = '',
@office nvarchar(50)  = '',
@department nvarchar(50)  = '',
@language nvarchar(255)  = '',
@jobTitle nvarchar(255) = '',

I want to build a query that is dynamic enough to only query the values provided.


问:
How to print only the last match using itertools in python?
I have the following code:

```<code>p = ['a','b','c','d']
q = ['a','a','x','y','z']

for (p, q) in itertools.product(p, q):
    if p == q:
        print(q)
</code>```

it prints:

```<code>a
a
</code>```

After adding some additional logs it seems that the first item of p is compared with the first item of q, then first item of p with second item of q, first item of p with third item of q etc.

How can I modify this code so that it will only print the last match? So I only want the output a once (because of the comparison of the first item of p and the second item in q in this case)

答:
If you can't afford to turn p and q into sets first because they're exorbitantly large, you can add the already matched values to a set as you go and check for inclusion:

```<code>p = ['a','b','c','d']
q = ['a','a','x','y','z']
seen = set([])

for a, b in itertools.product(p, q):
    if a == b and b not in seen:
        print(b)
        seen.add(b)
</code>```

Body:
I have the following code:

p = ['a','b','c','d']
q = ['a','a','x','y','z']

for (p, q) in itertools.product(p, q):
    if p == q:
        print(q)

it prints:

a
a

After adding some additional logs it seems that the first item of p is compared with the first item of q, then first item of p with second item of q, first item of p with third item of q etc.

How can I modify this code so that it will only print the last match? So I only want the output a once (because of the comparison of the first item of p and the second item in q in this case)

Body:
If you can't afford to turn p and q into sets first because they're exorbitantly large, you can add the already matched values to a set as you go and check for inclusion:

p = ['a','b','c','d']
q = ['a','a','x','y','z']
seen = set([])

for a, b in itertools.product(p, q):
    if a == b and b not in seen:
        print(b)
        seen.add(b)


答:
In order to do so I would simply reverse both lists that is:

```<code>import itertools
p = ['a','b','c','d']
q = ['a','a','x','y','z']

for (x, y) in itertools.product(p[::-1], q[::-1]):
    if x == y:
        print(y)
        break
</code>```

Output:

```<code>a
</code>```

Title: How to print only the last match using itertools in python?

Body:
In order to do so I would simply reverse both lists that is:

import itertools
p = ['a','b','c','d']
q = ['a','a','x','y','z']

for (x, y) in itertools.product(p[::-1], q[::-1]):
    if x == y:
        print(y)
        break

Output:

a


问:
Validation with input[type="radio"] return always false
I have an input[type="radio"], with no checked option by default, and i need to return false if none of these options are checked.

I'm exploring javascript only, so a jquery, angular or any other will be useles (at this moment).
I'm able to iterate over a radioObj and select its value, but i can't return false if no option is checked (actually, i can't return true)

not exactly what i have, but...

```<code><input type="radio" id="rd1" name="radioGrp">opt1
<br>
<input type="radio" id="rd2" name="radioGrp">opt2
</code>```

and in JS i have...

```<code>var rdObj = document.getElementByName("radioGrp");
var selectedValue;

for (var i = 0, length = rdObj.length; i < length; i++){
if(!rdObj[i].checked){
        alert("Select one option");
        return false;
    }else{
        //do something with value of radio checked value
    }
}
</code>```

This code always gives me the alert("Select one option"), no matter if i select one option or not.
Need for validation.

Any hel will be very appreciated

答:
You probably want to wait for an event before you do any sort of value checking, otherwise your script will only run once, and at this point in time, nothing would have ever had the chance be checked.

You can attach a change event listener to each of your radios...

var myRadios = document.querySelectorAll('[name=radioGrp]');
var selectedValue;

myRadios.forEach(radio => {
  radio.addEventListener('change', changeHandler);
})

function changeHandler(evt) {
  // do some check in here
  console.log(evt.target.value)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" id="rd1" name="radioGrp" value='opt1'>opt1
<br>
<input type="radio" id="rd2" name="radioGrp" value='opt2'>opt2</code>```

...or you can attach a submit event handler to your form and do some checking of your data then.

const myForm = document.querySelector('form');
myForm.addEventListener('submit', submitHandler);

function submitHandler(evt) {
  evt.preventDefault();
  const data = new FormData(evt.target);
  const optionVal = data.get('radioGrp');
  // do some check in here
  if (!optionVal) {
    console.log(`Please select a value`)
  } else {
    console.log(`Thanks for selecting ${optionVal}`)
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type="radio" id="rd1" name="radioGrp" value='opt1'>opt1
  <br>
  <input type="radio" id="rd2" name="radioGrp" value='opt2'>opt2
  <input type="submit">
</form></code>```

Body:
I have an input[type="radio"], with no checked option by default, and i need to return false if none of these options are checked.

I'm exploring javascript only, so a jquery, angular or any other will be useles (at this moment).
I'm able to iterate over a radioObj and select its value, but i can't return false if no option is checked (actually, i can't return true)

not exactly what i have, but...

<input type="radio" id="rd1" name="radioGrp">opt1

<input type="radio" id="rd2" name="radioGrp">opt2

and in JS i have...

var rdObj = document.getElementByName("radioGrp");
var selectedValue;

for (var i = 0, length = rdObj.length; i < length; i++){
if(!rdObj[i].checked){
        alert("Select one option");
        return false;
    }else{
        //do something with value of radio checked value
    }
}

This code always gives me the alert("Select one option"), no matter if i select one option or not.
Need for validation.

Any hel will be very appreciated

Body:
You probably want to wait for an event before you do any sort of value checking, otherwise your script will only run once, and at this point in time, nothing would have ever had the chance be checked.

You can attach a change event listener to each of your radios...

var myRadios = document.querySelectorAll('[name=radioGrp]');
var selectedValue;

myRadios.forEach(radio => {
  radio.addEventListener('change', changeHandler);
})

function changeHandler(evt) {
  // do some check in here
  console.log(evt.target.value)
}

<input type="radio" id="rd1" name="radioGrp" value='opt1'>opt1
<br>
<input type="radio" id="rd2" name="radioGrp" value='opt2'>opt2

...or you can attach a submit event handler to your form and do some checking of your data then.

const myForm = document.querySelector('form');
myForm.addEventListener('submit', submitHandler);

function submitHandler(evt) {
  evt.preventDefault();
  const data = new FormData(evt.target);
  const optionVal = data.get('radioGrp');
  // do some check in here
  if (!optionVal) {
    console.log(`Please select a value`)
  } else {
    console.log(`Thanks for selecting ${optionVal}`)
  }
}

<form>
  <input type="radio" id="rd1" name="radioGrp" value='opt1'>opt1
  <br>
  <input type="radio" id="rd2" name="radioGrp" value='opt2'>opt2
  <input type="submit">
</form>


问:
Using booleans with set and get methods
To summarize I am making a program for a metro ticket system. and I am using set and get methods for it, when it comes to boolean values (since I need to validate that the person enters enough money for the ticket) how am i supposed to put in the main class( it is defined in brain) using the set method and an if statement.Here is a little fraction of the entire code and the rest is on github(https://github.com/alexxei4/subwayticket). The main is basically the class that will be used for interaction with the user and the brain is where alot of the actions are defined.All help is appreciated, please and thank you.</p>

```<code> if (Choice1a == 10){
            if(subway1.ticketcounter1(true);){
                System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
            }
            if(subway1.ticketcounter1(false);){
                System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
            }
</code>```

答:
This is not how you evaluate boolean values, you just place the value in an if statement and it will proceed if true and refuse if false, also there is no need to duplicate the statement when you can just place an else block to handle situations that are not true:

```<code>    if(subway1.ticketcounter1) {
        System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
    }
    else {
        System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
    }
</code>```

Also do not include semicolons in if statements, that's incorrect syntax. Read more about how to use use boolean values here: https://codingbat.com/doc/java-if-boolean-logic.html

EDIT:

After reading through your Github code I see that ticketcounter1 indeed is a method, but what it's doing is trying to change the value of ticketcounter1 like it's a referenced object, but boolean are primitive data types and can't be referenced, and even if they could it still wouldn't work because Java is a pass-by-value language. Read here for more information on that.

```<code>public void ticketcounter1(boolean ticketcounter1){
    if (credit1 > total1){
        ticketcounter1 = true;
    }
    else {
        ticketcounter1 = false;
    }
}
public void ticketcounter2(boolean ticketcounter2){
    if (credit2 > total2){
        ticketcounter2 = true;
    }
    else {
        ticketcounter2= false;
    }
</code>```

Like the other answer said you should be returning the value as boolean instead of trying to change it:

```<code>public boolean ticketcounter1(){
    if (credit1 > total1){
        return true;
    }
    else {
        return false;
    }
}
public boolean ticketcounter2(){
    if (credit2 > total2){
       return true;
    }
    else {
        return false;
    }
}
</code>```

But all in all your code demonstrated fundamental flaws in understanding how the language works, I would suggest picking up a good Java for beginners kind of book or do some introductory online tutorials. Here is a good place to start your learning journey: https://docs.oracle.com/javase/tutorial/java/index.html

Title: Using booleans with set and get methods

Body:
To summarize I am making a program for a metro ticket system. and I am using set and get methods for it, when it comes to boolean values (since I need to validate that the person enters enough money for the ticket) how am i supposed to put in the main class( it is defined in brain) using the set method and an if statement.Here is a little fraction of the entire code and the rest is on github(https://github.com/alexxei4/subwayticket). The main is basically the class that will be used for interaction with the user and the brain is where alot of the actions are defined.All help is appreciated, please and thank you.

 if (Choice1a == 10){
            if(subway1.ticketcounter1(true);){
                System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
            }
            if(subway1.ticketcounter1(false);){
                System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
            }

Body:
This is not how you evaluate boolean values, you just place the value in an if statement and it will proceed if true and refuse if false, also there is no need to duplicate the statement when you can just place an else block to handle situations that are not true:

    if(subway1.ticketcounter1) {
        System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
    }
    else {
        System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
    }

Also do not include semicolons in if statements, that's incorrect syntax. Read more about how to use use boolean values here: https://codingbat.com/doc/java-if-boolean-logic.html

EDIT:

After reading through your Github code I see that ticketcounter1 indeed is a method, but what it's doing is trying to change the value of ticketcounter1 like it's a referenced object, but boolean are primitive data types and can't be referenced, and even if they could it still wouldn't work because Java is a pass-by-value language. Read here for more information on that.

public void ticketcounter1(boolean ticketcounter1){
    if (credit1 > total1){
        ticketcounter1 = true;
    }
    else {
        ticketcounter1 = false;
    }
}
public void ticketcounter2(boolean ticketcounter2){
    if (credit2 > total2){
        ticketcounter2 = true;
    }
    else {
        ticketcounter2= false;
    }

Like the other answer said you should be returning the value as boolean instead of trying to change it:

public boolean ticketcounter1(){
    if (credit1 > total1){
        return true;
    }
    else {
        return false;
    }
}
public boolean ticketcounter2(){
    if (credit2 > total2){
       return true;
    }
    else {
        return false;
    }
}

But all in all your code demonstrated fundamental flaws in understanding how the language works, I would suggest picking up a good Java for beginners kind of book or do some introductory online tutorials. Here is a good place to start your learning journey: https://docs.oracle.com/javase/tutorial/java/index.html


问:
Opening app from email link in NativeScript vue iOS
Edit For more explanation on how to use this plugin with vue, please see NativeScript vue, vuex and urlhandler

I'm trying to make it so that a link in an email can open an app I'm building (its a test app I'm building to learn NativeScript). I am using https://www.npmjs.com/package/nativescript-urlhandler with NativeScript vue on iOS.

In platforms/ios/######/app/App_Resources/iOS/Info.plist I have added

```<code><key>CFBundleURLTypes</key>
<array>
   <dict>
       <key>CFBundleURLName</key>
       <string>com.#######.######</string>
   </dict>
   <dict>
       <key>CFBundleURLSchemes</key>
       <array>
           <string>mycustomappfoobar</string>
       </array>
   </dict>
</array>
</code>```

And within app.js, I have added:

```<code>const handleOpenURL = require("nativescript-urlhandler").handleOpenURL;

handleOpenURL(function(appURL) {
    console.log('Got the following appURL', appURL);
  });
</code>```

When tapping on mycustomappfoobar://test (link in email) nothing happens...

I looked at the Angular example, and handleOpenURL is being called on initialisation... So I tried putting handleOpenURL within vues mounted hook - but this doesn't work either. Really stumped...

```<code>new Vue({
    mounted() {
      handleOpenURL(function(appURL) {
        console.log('Got the following appURL', appURL);
      });
    },
    render: h => h("frame", [h(Home)]),
    store: Store
}).$start();
</code>```

答: You are updating wrong info.plist. Basically anything inside platforms folder is auto generated. Use the one within your App_Resources/iOS/info.plist.

Body:
Edit For more explanation on how to use this plugin with vue, please see NativeScript vue, vuex and urlhandler

I'm trying to make it so that a link in an email can open an app I'm building (its a test app I'm building to learn NativeScript). I am using https://www.npmjs.com/package/nativescript-urlhandler with NativeScript vue on iOS.

In platforms/ios/######/app/App_Resources/iOS/Info.plist I have added

<key>CFBundleURLTypes</key>
<array>
   <dict>
       <key>CFBundleURLName</key>
       <string>com.#######.######</string>
   </dict>
   <dict>
       <key>CFBundleURLSchemes</key>
       <array>
           <string>mycustomappfoobar</string>
       </array>
   </dict>
</array>

And within app.js, I have added:

const handleOpenURL = require("nativescript-urlhandler").handleOpenURL;

handleOpenURL(function(appURL) {
    console.log('Got the following appURL', appURL);
  });

When tapping on mycustomappfoobar://test (link in email) nothing happens...

I looked at the Angular example, and handleOpenURL is being called on initialisation... So I tried putting handleOpenURL within vues mounted hook - but this doesn't work either. Really stumped...

new Vue({
    mounted() {
      handleOpenURL(function(appURL) {
        console.log('Got the following appURL', appURL);
      });
    },
    render: h => h("frame", [h(Home)]),
    store: Store
}).$start();


问:
Javascript, draw window with text over
I am more into the simpler desktop programming scene (when it comes to this sort of stuff it is a hell of a lot simpler to deal with).

I have a large .png file I wish to display in the browser which is effectively a map with icons and when a user hovers over the icon I want to draw (preferably) a graphical window of sorts (can be another image pre-designed) and put styled text on this window (a basic display).

The .png is to be used in  tag using <map> and <area>, so <canvas> and applicable javascript functions are out of the question, it does not work, not ever with transparent double trickery (already tried it).

On a side note, why on earth has such a simple task that my 8 year old sister can do in an old IDE and Language on Windows and I can't get close in a browsers LOL!

答:
There are fancy ways of doing this using canvas or even as a custom layer to a Google Map, but if you don't need advanced panning and zooming, basic HTML should do.

What I would do:

Show the large image in an img tag

Put it into a div container with position: relative

Put each icon onto the map with absolute positioning, e.g.  position: absolute; left: 100px; top: 100px

Link every every icon's onclick event to a jQuery UI dialog.

Rough example CSS:

```<code>div.map { position: relative; width: 400px; height: 400px }
div.map .marker1 { position: absolute; left: 100px; top: 120px }
</code>```

HTML:

```<code><div class="map">
  <img src="image.png">

  <img class="marker1" onclick="$( '#dialog' ).dialog();" src="marker.png">

</div>

<!-- jQuery UI dialog -->

<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information.
       The dialog window can be moved, resized and closed with the 'x' icon.</p>
 </div>
</code>```

Title: Javascript, draw window with text over <img>

Body:
There are fancy ways of doing this using canvas or even as a custom layer to a Google Map, but if you don't need advanced panning and zooming, basic HTML should do.

What I would do:

Show the large image in an img tag

Put it into a div container with position: relative

Put each icon onto the map with absolute positioning, e.g.  position: absolute; left: 100px; top: 100px

Link every every icon's onclick event to a jQuery UI dialog.

Rough example CSS:

div.map { position: relative; width: 400px; height: 400px }
div.map .marker1 { position: absolute; left: 100px; top: 120px }

HTML:

<div class="map">
  <img src="image.png">

  <img class="marker1" onclick="$( '#dialog' ).dialog();" src="marker.png">

</div>

<!-- jQuery UI dialog -->

<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information.
       The dialog window can be moved, resized and closed with the 'x' icon.</p>
 </div>


问:
Passing the EXPOSE argument in Dockerfile as user input
Passing the argument in Dockerfile as user input while building the docker image.

Created a sample Dockerfile that would build a image.

```<code>### sample dockerfile
    COPY . .
    EXPOSE 7017

# ENV VAR'S
    ENV ELASTIC_APM_CONFIG_FILE=elastic-apm-node.js
    ENV ELASTIC_APM_SERVICE_NAME=abc
    ENV ELASTIC_APM_SERVER_URLS=http://abc:1234
</code>```

Specifying the EXPOSE Argument in Dockerfile as user input.

答:
Docker build uses arguments (defined with ARG). Environment variables (defined with ENV) are used by running containers and are not available at build time.

Change your Dockerfile to:

```<code>FROM ....

ARG EXPOSE_PORT=<some default value>

EXPOSE $EXPOSE_PORT
</code>```

and then pass the value you need in your docker build command:

```<code>docker build --build-arg EXPOSE_PORT=7017 ....
</code>```

Body:
Passing the argument in Dockerfile as user input while building the docker image.

Created a sample Dockerfile that would build a image.

### sample dockerfile
    COPY . .
    EXPOSE 7017

# ENV VAR'S
    ENV ELASTIC_APM_CONFIG_FILE=elastic-apm-node.js
    ENV ELASTIC_APM_SERVICE_NAME=abc
    ENV ELASTIC_APM_SERVER_URLS=http://abc:1234

Specifying the EXPOSE Argument in Dockerfile as user input.

Body:
Docker build uses arguments (defined with ARG). Environment variables (defined with ENV) are used by running containers and are not available at build time.

Change your Dockerfile to:

FROM ....

ARG EXPOSE_PORT=<some default value>

EXPOSE $EXPOSE_PORT

and then pass the value you need in your docker build command:

docker build --build-arg EXPOSE_PORT=7017 ....


问:
Change the background of a label when acting as checkbox
I have labels with images nested inside that is acting as a checkbox. What I can't figure out is how to change the background behind the image when that specific checkbox is selected (label clicked).

It appears as if one of the checkboxes is getting the background to show, but not both and the height element is not working.

Does anyone see what I am doing wrong?

.notificationImgs {
 width: 70px;
 height: auto;
 margin: 0 20px;
 cursor: pointer;
}
.notifCheck {
 display: none;
}
.notifCheck:checked + label {
 background: #CCC;
}
.notifCheck:checked .notificationImgs {
 background-color: #CCC;
 width: 100%;
 height: 70px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="checkText">
   <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Text Notifications" class="notificationImgs">
  </label>
  <input type="checkbox" name="checkText" class="notifCheck" id="checkText" value="text">
  <label for="checkEmail">
   <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Email Notifications" class="notificationImgs">
  </label></code>```

答:
Here's the altered HTML/code for you. You were missing checkbox and your CSS is + selector which is looking for checked + label so for first checkbox it was targeting second label.

.notificationImgs {
  width: 70px;
  height: 70px;
  margin: 0 20px;
  cursor: pointer;
}

.notifCheck {
  display: none;
}

.notifCheck:checked+label {
  background: #CCC;
}

.notifCheck:checked .notificationImgs {
  background-color: #CCC;
  width: 100%;
  height: 70px;
}

label{
  display:inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" name="checkText" class="notifCheck" id="checkText" value="text">
<label for="checkText">
  <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Text Notifications" class="notificationImgs"/>
</label>

<input type="checkbox" name="checkText" class="notifCheck" id="checkEmail" value="text">
<label for="checkEmail">
  <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Email Notifications" class="notificationImgs"/>
</label></code>```

Body:
I have labels with images nested inside that is acting as a checkbox. What I can't figure out is how to change the background behind the image when that specific checkbox is selected (label clicked).

It appears as if one of the checkboxes is getting the background to show, but not both and the height element is not working.

Does anyone see what I am doing wrong?

.notificationImgs {
 width: 70px;
 height: auto;
 margin: 0 20px;
 cursor: pointer;
}
.notifCheck {
 display: none;
}
.notifCheck:checked + label {
 background: #CCC;
}
.notifCheck:checked .notificationImgs {
 background-color: #CCC;
 width: 100%;
 height: 70px;
}

  <input type="checkbox" name="checkText" class="notifCheck" id="checkText" value="text">

Body:
Here's the altered HTML/code for you. You were missing checkbox and your CSS is + selector which is looking for checked + label so for first checkbox it was targeting second label.

.notificationImgs {
  width: 70px;
  height: 70px;
  margin: 0 20px;
  cursor: pointer;
}

.notifCheck {
  display: none;
}

.notifCheck:checked+label {
  background: #CCC;
}

.notifCheck:checked .notificationImgs {
  background-color: #CCC;
  width: 100%;
  height: 70px;
}

label{
  display:inline-block;
}

<input type="checkbox" name="checkText" class="notifCheck" id="checkText" value="text">
<label for="checkText">
  <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Text Notifications" class="notificationImgs"/>
</label>

<input type="checkbox" name="checkText" class="notifCheck" id="checkEmail" value="text">
<label for="checkEmail">
  <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Email Notifications" class="notificationImgs"/>
</label>


问:
How do I disable or prevent the use of Hibernate proxies after session is closed?
So I am working now on a RESTful API that acts as a layer between the client and our databases, I'm currently using Hibernate for ORM and I've been trying for days now to find a solution to my problem, searching everywhere to no avail.

I can't post the actual code I'm using because its too big, but picture this:

I have a class Employee mapped as an Hibernate entity that looks like this

@Entity
public class Employee {
    @Id
    Integer id;
    String name;
    Double salary;
    String department;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id")
    Company company;

//    Getters/Setters ommitted

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                ", department='" + department + '\'' +
                ", company=" + company +
                '}';
    }
}
```

<p>And another entity class <code>Company</code> that looks like this:</p>

<pre class="lang-java prettyprint-override"><code>@Entity
public class Company {

    @Id
    Integer id;
    String name;
    String address;
    @OneToMany(mappedBy = "company", fetch = FetchType.LAZY)
    List<Employee> employees;

//    Getters and setters ommited

    @Override
    public String toString() {
        return "Company{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", employees=" + employees +
                '}';
    }
}
</code>```

The database looks something like this:

```<code>Employee:
| id | name     | salary | department | company_id |
|----|----------|--------|------------|------------|
| 1  | john doe | 3000   | Finance    | 1          |
| 2  | mary sue | 3300   | HR         | 1          |

Company:
| id | name | address    |
|----|------|------------|
| 1  | ACME | St. Sesame |
</code>```

Now lets say I want to get data from a certain employee, I want only the employee data + the ID of the company (and only the ID) as a reference if I need the company data later. It would look something like this:

Session session = SessionManager.openSession();

Employee emp = session.get(Employee.class, 1);

session.close();
```

<p>Now I want to show the employee data</p>

<pre class="lang-java prettyprint-override"><code>System.out.println(emp);
</code>```

The output that is expected (or at least, that I expected) here is something like this:

```<code>Employee{id=1,name='john doe',salary=3000.0,department='Finance',company=Company{id=1,name=null,address=null,employees=null}}
</code>```

That's simple enough, the problem is that it will throw an LazyInitializationException, because Hibernate tried to use a proxy object to fetch de Company data when it was required on the toString() call of Employee, but the session is already closed.

The thing is if I closed the session without fetching any more data, then THATS IT, no more data needed, HIBERNATE! If I open a session, I will fetch all the data that I need, and ONLY the data that I need, and after I close it, it means that I dont need any more data, thank you hibernate, but Hibernate's proxy objects keep active even after the session is closed.

I've searched all around the net, even here on StackOverflow, and there are some so called "solutions" or "workarounds", like:

Why don't you use HQL with constructors?

Well I actually use those, on many use cases, when the query is simple enough to use HQL. The problem is many use cases require complex querys, with lots of joins and calculations that even use tables that are not mapped to Hibernate Entities, so I need an Native Query to do so.

You could use HQL with constructors, and create entities for every database table you need to access on the query

That would mean mapping dozens of entities that I would use on one, maybe two use cases, and never again, just so I could use HQL with Constructors. Besides, some of those queries use native functions and other complex calculations HQL simply does not support.

Then use an Native Query, and you can put NULL as columnName when you dont want that column data

I do that too on some use cases, the problem is when that column is a join column on an entity relationship, Hibernate sets a proxy object, and I don't want an proxy object, just the data of the join column if, AND ONLY IF, that data is needed on another part of the code, where I can open a new session and retrieve the required data.

Why don't you just keep the session open using that open session on view pattern?

No can't do, thats a RESTful API, what if the client asks for the employee data on a first request, and then later makes another request for the company data of that previous employee, passing the company ID on the body of the request? Thats a common use case.

session.detach()?

Doesn't work.

Stateless sessions?

Still creates proxy objects, it only disables first and second level caches for the current session.

Why don't you use DTOs?

And create a new class for each use-case of partial data request of my API? HAHAHA!

You see, the only reason I use an ORM solution like Hibernate is because I dread manual handling of ResultSets do DEATH. Forget about HQL, Criteria API, etc. I don't mind creating native queries from Strings if I can only have Hibernate to map the ResultSet to an Object (Or list of objects) for me. And I want Hibernate to know that if there is an entity relation that I did not fetch before the session is closed, that means that I do NOT want to fetch it, so no proxy objects.

I know that there probably is another ORM solution out there that does not have this issue, but I can't give the time to learn it because DEADLINES, so someone help me please.

EDIT

So some of you marked my question as a duplicate of Converting Hibernate proxy to a real entity object, but there are differences:

That question revolves around how to "Unproxy" an object, as in how to trigger the initialization of an Hibernate proxy.

My question is about how to make Hibernate NOT use a proxy for an unfetched relation object, and instead just use an instance of the relation's class with only the ID of it.

In my previous example, instead of using a proxy to lazy fetch the Company object related to the Employee later when needed, I would like for hibernate to just create a new Company(company_id) and leave it like that, NO PROXY.

EDIT 2

I just found out that the Jackson project (which I use for reading/writing data as JSON in my API) has a module that ignores Hibernate proxies when serializing objects.

Maven dependency:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-hibernate5</artifactId>
    <version>${jackson-version}</version>
</dependency>
```

<p>Then just register the module on you <code>Object Mapper</code> instance:</p>

<pre class="lang-java prettyprint-override"><code>ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new Hibernate5Module());
</code>```

答:
So it seems my EDIT 2 turned out to be a "kind of" solution to my problem.

The jackson-datatype-hibernate5 initially ignores unfetched proxies, setting them as null when serializing objects, but the class Hibernate5Module (or whatever Hibernate module version you want to use) has an really handy configuration that makes Jackson serialize only the ID for unfetched proxies, which is what I was looking for.

// Configuring `ObjectMapper` and module:
ObjectMapper mapper = new ObjectMapper();
Hibernate5Module module = new Hibernate5Module()
    .configure(Hibernate5Module.Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS, true);

mapper.registerModule(module);
```

This way you can use that ObjectMapper to create ObjectReaders for your classes that will NOT try to initialize proxy objects on serialization, but only serialize the ID of the object (if its a OneToOne or ManyToOne relation, of course).

And I said its a "kind of" solution because Hibernate is still using proxy objects for unfetched relations (when I wanted just the ID value of the proxy object for later use), the only thing is that I have configured Jackson to persist the ID value and ignore the proxy object.

Body:
So I am working now on a RESTful API that acts as a layer between the client and our databases, I'm currently using Hibernate for ORM and I've been trying for days now to find a solution to my problem, searching everywhere to no avail.

I can't post the actual code I'm using because its too big, but picture this:

I have a class Employee mapped as an Hibernate entity that looks like this

@Entity
public class Employee {
    @Id
    Integer id;
    String name;
    Double salary;
    String department;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id")
    Company company;

//    Getters/Setters ommitted

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                ", department='" + department + '\'' +
                ", company=" + company +
                '}';
    }
}

And another entity class Company that looks like this:

@Entity
public class Company {

    @Id
    Integer id;
    String name;
    String address;
    @OneToMany(mappedBy = "company", fetch = FetchType.LAZY)
    List<Employee> employees;

//    Getters and setters ommited

    @Override
    public String toString() {
        return "Company{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", employees=" + employees +
                '}';
    }
}

The database looks something like this:

Employee:
| id | name     | salary | department | company_id |
|----|----------|--------|------------|------------|
| 1  | john doe | 3000   | Finance    | 1          |
| 2  | mary sue | 3300   | HR         | 1          |

Company:
| id | name | address    |
|----|------|------------|
| 1  | ACME | St. Sesame |

Now lets say I want to get data from a certain employee, I want only the employee data + the ID of the company (and only the ID) as a reference if I need the company data later. It would look something like this:

Session session = SessionManager.openSession();

Employee emp = session.get(Employee.class, 1);

session.close();

Now I want to show the employee data

System.out.println(emp);

The output that is expected (or at least, that I expected) here is something like this:

Employee{id=1,name='john doe',salary=3000.0,department='Finance',company=Company{id=1,name=null,address=null,employees=null}}

That's simple enough, the problem is that it will throw an LazyInitializationException, because Hibernate tried to use a proxy object to fetch de Company data when it was required on the toString() call of Employee, but the session is already closed.

The thing is if I closed the session without fetching any more data, then THATS IT, no more data needed, HIBERNATE! If I open a session, I will fetch all the data that I need, and ONLY the data that I need, and after I close it, it means that I dont need any more data, thank you hibernate, but Hibernate's proxy objects keep active even after the session is closed.

I've searched all around the net, even here on StackOverflow, and there are some so called "solutions" or "workarounds", like:

Why don't you use HQL with constructors?

Well I actually use those, on many use cases, when the query is simple enough to use HQL. The problem is many use cases require complex querys, with lots of joins and calculations that even use tables that are not mapped to Hibernate Entities, so I need an Native Query to do so.

You could use HQL with constructors, and create entities for every database table you need to access on the query

That would mean mapping dozens of entities that I would use on one, maybe two use cases, and never again, just so I could use HQL with Constructors. Besides, some of those queries use native functions and other complex calculations HQL simply does not support.

Then use an Native Query, and you can put NULL as columnName when you dont want that column data

I do that too on some use cases, the problem is when that column is a join column on an entity relationship, Hibernate sets a proxy object, and I don't want an proxy object, just the data of the join column if, AND ONLY IF, that data is needed on another part of the code, where I can open a new session and retrieve the required data.

Why don't you just keep the session open using that open session on view pattern?

No can't do, thats a RESTful API, what if the client asks for the employee data on a first request, and then later makes another request for the company data of that previous employee, passing the company ID on the body of the request? Thats a common use case.

session.detach()?

Doesn't work.

Stateless sessions?

Still creates proxy objects, it only disables first and second level caches for the current session.

Why don't you use DTOs?

And create a new class for each use-case of partial data request of my API? HAHAHA!

You see, the only reason I use an ORM solution like Hibernate is because I dread manual handling of ResultSets do DEATH. Forget about HQL, Criteria API, etc. I don't mind creating native queries from Strings if I can only have Hibernate to map the ResultSet to an Object (Or list of objects) for me. And I want Hibernate to know that if there is an entity relation that I did not fetch before the session is closed, that means that I do NOT want to fetch it, so no proxy objects.

I know that there probably is another ORM solution out there that does not have this issue, but I can't give the time to learn it because DEADLINES, so someone help me please.

EDIT

So some of you marked my question as a duplicate of Converting Hibernate proxy to a real entity object, but there are differences:

That question revolves around how to "Unproxy" an object, as in how to trigger the initialization of an Hibernate proxy.

My question is about how to make Hibernate NOT use a proxy for an unfetched relation object, and instead just use an instance of the relation's class with only the ID of it.

In my previous example, instead of using a proxy to lazy fetch the Company object related to the Employee later when needed, I would like for hibernate to just create a new Company(company_id) and leave it like that, NO PROXY.

EDIT 2

I just found out that the Jackson project (which I use for reading/writing data as JSON in my API) has a module that ignores Hibernate proxies when serializing objects.

Maven dependency:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-hibernate5</artifactId>
    <version>${jackson-version}</version>
</dependency>

Then just register the module on you Object Mapper instance:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new Hibernate5Module());

Body:
So it seems my EDIT 2 turned out to be a "kind of" solution to my problem.

The jackson-datatype-hibernate5 initially ignores unfetched proxies, setting them as null when serializing objects, but the class Hibernate5Module (or whatever Hibernate module version you want to use) has an really handy configuration that makes Jackson serialize only the ID for unfetched proxies, which is what I was looking for.

// Configuring `ObjectMapper` and module:
ObjectMapper mapper = new ObjectMapper();
Hibernate5Module module = new Hibernate5Module()
    .configure(Hibernate5Module.Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS, true);

mapper.registerModule(module);

This way you can use that ObjectMapper to create ObjectReaders for your classes that will NOT try to initialize proxy objects on serialization, but only serialize the ID of the object (if its a OneToOne or ManyToOne relation, of course).

And I said its a "kind of" solution because Hibernate is still using proxy objects for unfetched relations (when I wanted just the ID value of the proxy object for later use), the only thing is that I have configured Jackson to persist the ID value and ignore the proxy object.


答:
So you can change your parameters to be 'null' by default

```<code>@lastName nvarchar(255) = null,
@firstName nvarchar(255)  = null,
@office nvarchar(50)  = null,
@department nvarchar(50)  = null,
@language nvarchar(255)  = null,
@jobTitle nvarchar(255) = null,
</code>```

Then in your where clause, check for the existence of NULL before comparing the value to the corresponding field.

```<code>where (@lastName is null or lastname = @lastName)
and (@firstName is null or firstName = @firstName)
and (@office is null or office = @office)
and (@department is null or department = @department)
and (@language is null or language = @language)
and (@jobTitle is null or jobTitle = @jobTitle)
</code>```

Title: Dynamic query (in stored procedure) based on params provided (SQL Server 2016)

Body:
So you can change your parameters to be 'null' by default

@lastName nvarchar(255) = null,
@firstName nvarchar(255)  = null,
@office nvarchar(50)  = null,
@department nvarchar(50)  = null,
@language nvarchar(255)  = null,
@jobTitle nvarchar(255) = null,

Then in your where clause, check for the existence of NULL before comparing the value to the corresponding field.

where (@lastName is null or lastname = @lastName)
and (@firstName is null or firstName = @firstName)
and (@office is null or office = @office)
and (@department is null or department = @department)
and (@language is null or language = @language)
and (@jobTitle is null or jobTitle = @jobTitle)


问:
VBA: Protecting Shape Objects only
I read quite a few posts but didn't find anything similar to what I'm trying to achieve. I basically have a few Shape objects in my worksheet which have macros assigned to them. I would like to protect these objects using VBA so users can interact with them but not edit them in any way. I however, would like the users(and my VBA) to be able to freely manipulate the rest of the workbook as they like.

I tried ActiveSheet.Protect DrawingObjects:=True but the problem is that the usability of the rest of the application is quite limited as well. For example I have a checkbox that hides/unhides a range of cells but when the sheet is protected, I cannot execute the macro and I get an exception. Is there a way to protect the Shape objects only and basically leave the rest of the workbook unrestricted as if the sheet was unprotected?

Thanks,
Dimitar

答:
In Review -> Protect sheet -> You want everything except "Edit Objects" checked (So users can still do everything), then create a password. This lets people do everything except edit objects - which IIRC, shapes are.

If you're hellbent on doing this with VBA, you can quickly record a macro with a similar lock, see what it looks like, and edit from there.

Edit: I just realized there are other objects you're trying to allow. In that case, I'd consider an on-change event, and when one of the shapes you're trying to protect get changed, hit undo

Title: VBA: Protecting Shape Objects only


问:
Why I cannot create a class object inside a function?
I have my main code that contains several functions and I tested it and it works perfectly fine. I then create a class for tkinter window, and test it separately and it also works fine. When I incorporate the both of them together, by creating a class object inside a function, I get this error message:

"TclError: can't invoke "frame" command: application has been destroyed"

```<code>import tkinter

class InputFromForm():
    def __init__(self, root, values):
        self.field = []
        self.fieldStrings = values
        self.temp = self.makeform(self.fieldStrings)

    def makeform(self, fields):
        entries = []
        for i in fields:
            row = tkinter.Frame(root)
            lab = tkinter.Label(row, width=15, text=i, anchor='w')
            ent = tkinter.Entry(row)
            ent.insert(tkinter.END, fields[i])
            ent.bind("<FocusIn>", lambda event, e=ent: e.selection_range(0, tkinter.END))
            row.pack(side=tkinter.TOP, fill=tkinter.X, padx=5, pady=10)
            lab.pack(side=tkinter.LEFT)
            ent.pack(side=tkinter.RIGHT, expand=tkinter.YES, fill=tkinter.X)
            entries.append((i, ent))

        return entries

    def fetch(self, entries):
        for entry in entries:
            string = entry[0]
            text  = entry[1].get()
            self.field.append(text)
        return self.field

    def close(self, root):
        root.destroy()

def extractData(dOfValues):
    root = tkinter.Tk()
    root.title('Test')
    userInput = InputFromForm(root, dOfValues)
    root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    b1 = tkinter.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    b1.config(width=25)
    b1.pack(anchor=tkinter.CENTER, padx=5, pady=20)

    root.mainloop()

if __name__ == '__main__':

    dOfValues = {'Customer No.': '',
            'PO #':'020202',
            'Order Date': '2/3/2012',
            'Zip to code':'92182'}

    #root = tkinter.Tk()
    #root.title('Test')

    #userInput = InputFromForm(root, dOfValues)

    #root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    #b1 = tkinter.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    #b1.config(width=25)
    #b1.pack(anchor=tkinter.CENTER, padx=5, pady=20)

    #root.mainloop()
    extractData(dOfValues)  # Adding this, creates the error. If I put the code
                            # from this function into main, it works.
</code>```

Can someone explain what is going on?

答:
I am not quite sure what the problem is, however I've do some change

on your script. First I import tkinter as tk then I've inherit  your

class from Tk, see below.

```<code>import tkinter as tk

class InputFromForm(tk.Tk):
    def __init__(self, root, values):
        self.field = []
        self.fieldStrings = values
        self.temp = self.makeform(self.fieldStrings)

    def makeform(self, fields):
        entries = []
        for i in fields:
            row = tk.Frame()
            lab = tk.Label(row, width=15, text=i, anchor='w')
            ent = tk.Entry(row)
            ent.insert(tk.END, fields[i])
            ent.bind("<FocusIn>", lambda event, e=ent: e.selection_range(0, tk.END))
            row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=10)
            lab.pack(side=tk.LEFT)
            ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)
            entries.append((i, ent))

        return entries

    def fetch(self, entries):
        for entry in entries:
            string = entry[0]
            text  = entry[1].get()
            self.field.append(text)
        return self.field

    def close(self, root):
        root.destroy()

def extractData(dOfValues):
    root = tk.Tk()
    root.title('Test')
    userInput = InputFromForm(root, dOfValues)
    root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    b1 = tk.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    b1.config(width=25)
    b1.pack(anchor=tk.CENTER, padx=5, pady=20)

    root.mainloop()

if __name__ == '__main__':

    dOfValues = {'Customer No.': '',
            'PO #':'020202',
            'Order Date': '2/3/2012',
            'Zip to code':'92182'}

    #root = tk.Tk()
    #root.title('Test')

    #userInput = InputFromForm(root, dOfValues)

    #root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    #b1 = tk.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    #b1.config(width=25)
    #b1.pack(anchor=tk.CENTER, padx=5, pady=20)

    #root.mainloop()
    extractData(dOfValues)  # Adding this, creates the error. If I put the code
                            # from this function into main, it works.
</code>```

I got this

Body:
I have my main code that contains several functions and I tested it and it works perfectly fine. I then create a class for tkinter window, and test it separately and it also works fine. When I incorporate the both of them together, by creating a class object inside a function, I get this error message:

"TclError: can't invoke "frame" command: application has been destroyed"

import tkinter

class InputFromForm():
    def __init__(self, root, values):
        self.field = []
        self.fieldStrings = values
        self.temp = self.makeform(self.fieldStrings)

    def makeform(self, fields):
        entries = []
        for i in fields:
            row = tkinter.Frame(root)
            lab = tkinter.Label(row, width=15, text=i, anchor='w')
            ent = tkinter.Entry(row)
            ent.insert(tkinter.END, fields[i])
            ent.bind("<FocusIn>", lambda event, e=ent: e.selection_range(0, tkinter.END))
            row.pack(side=tkinter.TOP, fill=tkinter.X, padx=5, pady=10)
            lab.pack(side=tkinter.LEFT)
            ent.pack(side=tkinter.RIGHT, expand=tkinter.YES, fill=tkinter.X)
            entries.append((i, ent))

        return entries

    def fetch(self, entries):
        for entry in entries:
            string = entry[0]
            text  = entry[1].get()
            self.field.append(text)
        return self.field

    def close(self, root):
        root.destroy()

def extractData(dOfValues):
    root = tkinter.Tk()
    root.title('Test')
    userInput = InputFromForm(root, dOfValues)
    root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    b1 = tkinter.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    b1.config(width=25)
    b1.pack(anchor=tkinter.CENTER, padx=5, pady=20)

    root.mainloop()

if __name__ == '__main__':

    dOfValues = {'Customer No.': '',
            'PO #':'020202',
            'Order Date': '2/3/2012',
            'Zip to code':'92182'}

    #root = tkinter.Tk()
    #root.title('Test')

    #userInput = InputFromForm(root, dOfValues)

    #root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    #b1 = tkinter.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    #b1.config(width=25)
    #b1.pack(anchor=tkinter.CENTER, padx=5, pady=20)

    #root.mainloop()
    extractData(dOfValues)  # Adding this, creates the error. If I put the code
                            # from this function into main, it works.

Can someone explain what is going on?

Body:
I am not quite sure what the problem is, however I've do some change

on your script. First I import tkinter as tk then I've inherit  your

class from Tk, see below.

import tkinter as tk

class InputFromForm(tk.Tk):
    def __init__(self, root, values):
        self.field = []
        self.fieldStrings = values
        self.temp = self.makeform(self.fieldStrings)

    def makeform(self, fields):
        entries = []
        for i in fields:
            row = tk.Frame()
            lab = tk.Label(row, width=15, text=i, anchor='w')
            ent = tk.Entry(row)
            ent.insert(tk.END, fields[i])
            ent.bind("<FocusIn>", lambda event, e=ent: e.selection_range(0, tk.END))
            row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=10)
            lab.pack(side=tk.LEFT)
            ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)
            entries.append((i, ent))

        return entries

    def fetch(self, entries):
        for entry in entries:
            string = entry[0]
            text  = entry[1].get()
            self.field.append(text)
        return self.field

    def close(self, root):
        root.destroy()

def extractData(dOfValues):
    root = tk.Tk()
    root.title('Test')
    userInput = InputFromForm(root, dOfValues)
    root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    b1 = tk.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    b1.config(width=25)
    b1.pack(anchor=tk.CENTER, padx=5, pady=20)

    root.mainloop()

if __name__ == '__main__':

    dOfValues = {'Customer No.': '',
            'PO #':'020202',
            'Order Date': '2/3/2012',
            'Zip to code':'92182'}

    #root = tk.Tk()
    #root.title('Test')

    #userInput = InputFromForm(root, dOfValues)

    #root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    #b1 = tk.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    #b1.config(width=25)
    #b1.pack(anchor=tk.CENTER, padx=5, pady=20)

    #root.mainloop()
    extractData(dOfValues)  # Adding this, creates the error. If I put the code
                            # from this function into main, it works.

I got this


问:
Question about using Terraform deploying to Azure
Is there a way to pass the URN of an Azure image to storage_image_reference instead of using Publisher, Offer, and SKU separately?

For example. passing this

```<code>OpenLogic:CentOS:7.5:latest
</code>```

instead of

```<code>storage_image_reference {
  publisher = "OpenLogic"
  offer     = "CentOS"
  sku       = "7.5"
  version   = "latest"
}
</code>```

答:
Assuming terraform 0.11</p>

```<code>variable "urn" {
  type = "list"
}

urn = split(":", "OpenLogic:CentOS:7.5:latest")

...

storage_image_reference {
  publisher = "${urn[0]}"
  offer     = "${urn[1]}"
  sku       = "${urn[2]}"
  version   = "${urn[3]}"
}

</code>```

Body:
Is there a way to pass the URN of an Azure image to storage_image_reference instead of using Publisher, Offer, and SKU separately?

For example. passing this

OpenLogic:CentOS:7.5:latest

instead of

storage_image_reference {
  publisher = "OpenLogic"
  offer     = "CentOS"
  sku       = "7.5"
  version   = "latest"
}

Body:
Assuming terraform 0.11

variable "urn" {
  type = "list"
}

urn = split(":", "OpenLogic:CentOS:7.5:latest")

...

storage_image_reference {
  publisher = "${urn[0]}"
  offer     = "${urn[1]}"
  sku       = "${urn[2]}"
  version   = "${urn[3]}"
}