问:
Simplifying Javascript array of images
what is the best way to simplify this javascript array?
     I am asked to create a page that slide shows 4 pictures it will use the
     onMouseOver and onMouseOut events. I haven't attached that part of the
     code in here. This is where I started but it looks too long. Can
     someone please simplify this for me? Thanks in Advance.  </p>

```<code> var season = Array();
 var start = 0;
 var timeDelay=3000;

season[0]=new Image();
season[0].src="winter.jpg";
season[1]=new Image();
season[1].src="spring.jpg";
season[2]=new Image();
season[2].src="summer.jpg";
season[3]=new Image();
season[3].src="fall.jpg";

function changeSeason(){
    var size= season.length - 1;
    if( start < size ) {
         start++;
    }
    else {
         start = 0;
    }
    document.times.src= season[start].src;
    timeout=setTimeout('changeSeason()', timeDelay);
}
</code>```

答:
Here's a simpler version that does the exact same thing...

```<code>var season = ["winter.jpg", "spring.jpg", "summer.jpg", "fall.jpg"];
var timeDelay=3000;
var seasonCount = 0;

function changeSeason(){
    document.times.src = season[++seasonCount % season.length];
    setTimeout(changeSeason, timeDelay);
}
</code>```

Firstly you don't need an array of images - you're just changing the src attribute so you just need an array of strings.  I also simplified the changeSeason() function so that it increments seasonCount and % season.length means that it will be reset to 0 when it reaches the array length.

This assumes that you start the slideshow on winter, as in your example.

Title: Simplifying Javascript array of images

Body:
what is the best way to simplify this javascript array?
     I am asked to create a page that slide shows 4 pictures it will use the
     onMouseOver and onMouseOut events. I haven't attached that part of the
     code in here. This is where I started but it looks too long. Can
     someone please simplify this for me? Thanks in Advance.

 var season = Array();
 var start = 0;
 var timeDelay=3000;

season[0]=new Image();
season[0].src="winter.jpg";
season[1]=new Image();
season[1].src="spring.jpg";
season[2]=new Image();
season[2].src="summer.jpg";
season[3]=new Image();
season[3].src="fall.jpg";

function changeSeason(){
    var size= season.length - 1;
    if( start < size ) {
         start++;
    }
    else {
         start = 0;
    }
    document.times.src= season[start].src;
    timeout=setTimeout('changeSeason()', timeDelay);
}

Body:
Here's a simpler version that does the exact same thing...

var season = ["winter.jpg", "spring.jpg", "summer.jpg", "fall.jpg"];
var timeDelay=3000;
var seasonCount = 0;

function changeSeason(){
    document.times.src = season[++seasonCount % season.length];
    setTimeout(changeSeason, timeDelay);
}

Firstly you don't need an array of images - you're just changing the src attribute so you just need an array of strings.  I also simplified the changeSeason() function so that it increments seasonCount and % season.length means that it will be reset to 0 when it reaches the array length.

This assumes that you start the slideshow on winter, as in your example.


来源: stackexchange

答:
To reduce the code you could use Array.prototype.map to iterate over a list of image sources, then convert them to HTMLImage elements with the source set

var sources = ['winter.jpg', 'spring.jpg', 'summer.jpg', 'fall.jpg']

var seasons = sources.map(function(src) {
  var img = new Image()
  img.src = src
  return img
})

console.log(seasons)```

ContentLicense: CC BY-SA 3.0

Title: Simplifying Javascript array of images


问:
Cannot find module '@types/mongodb'
I'm currently building a Node JS application using Typescript with a backing MongoDb database. But today I ran into a problem regarding import of the type definitions of MongoDb.

This line:

```<code>import { Db } from "@types/mongodb";
</code>```

throws an error:

MODULE_NOT_FOUND: Cannot find module '@types/mongodb'

However the MongoDb type definitions are installed in node_modules and available in the folder @types/mongodb as can be seen here.

Visual Studio Code is not complaining compile time, but of some reason Node JS can't find the definitions runtime.

I'm quite desperate, so any hints or guidelines are highly appreciated  Thanks in advance.

答: You just need to do import {Db} from 'mongodb';. The module @types/mongodb only contains only your typings and not actual code. Actual code will be in the the mongodb module -- provided you have installed the mongodb package. That is why you get a runtime error.

Title: Cannot find module '@types/mongodb'

Body:
I'm currently building a Node JS application using Typescript with a backing MongoDb database. But today I ran into a problem regarding import of the type definitions of MongoDb.

This line:

import { Db } from "@types/mongodb";

throws an error:

MODULE_NOT_FOUND: Cannot find module '@types/mongodb'

However the MongoDb type definitions are installed in node_modules and available in the folder @types/mongodb as can be seen here.

Visual Studio Code is not complaining compile time, but of some reason Node JS can't find the definitions runtime.

I'm quite desperate, so any hints or guidelines are highly appreciated  Thanks in advance.


问:
c# ensure all operations to complete or none
I have following code:

```<code>File.Copy(pathSource, pathDestination);   //copy file
ID3v2TagToDB(pathSource, pathDestination); //read his tags and save them to DB
ID3v2TagToTXT(pathSource, pathDestination); //read his tags and save them to txt
dgv.Rows[chosen[i]].DefaultCellStyle.BackColor = Color.GreenYellow; //color green datagridview row if copy and read successfull
</code>```

I want to ensure that each operation is successfull. If any of them failed, I need to rollback all previous ones.

And also, warn user about error that ocurred, and operation that ocurred in.

答:
I suggest you to implement a .NET Two Phase Commit Resource Manager. You RM could save a backup file for each change you made it to the filesystem, when the DTC components invokes the logic to rollback your changes. You could restore the backups files you made previously.

Check out this documentation

Using the TxF and KTM would help you as described here and here, because is already implemented in Vista+ windows versions.

TxF (Transactional Filesystem) works with NTFS format. The Win32 API contract wasn't changed, this is a great option for you. Because all the API  of IO, exposed throught .NET Framework are the same. You only need to call a few Win32 API directly and you got all the benefits of this new feature included in Windows. Using the DTC will allows you to do the transactional work across filesystem and database too. So In case of error throw, all the changes are rollback across the database and the filesystem.

Body:
I have following code:

File.Copy(pathSource, pathDestination);   //copy file
ID3v2TagToDB(pathSource, pathDestination); //read his tags and save them to DB
ID3v2TagToTXT(pathSource, pathDestination); //read his tags and save them to txt
dgv.Rows[chosen[i]].DefaultCellStyle.BackColor = Color.GreenYellow; //color green datagridview row if copy and read successfull

I want to ensure that each operation is successfull. If any of them failed, I need to rollback all previous ones.

And also, warn user about error that ocurred, and operation that ocurred in.


问:
Is there an advantange/disadvantage to creating multiple FormViews in a single .aspx page?
I am developing an asp.net web application in c# for asset management.  Currently, I'm working on the functionality to insert records to 18 different tables.  Example: Adding a new Manufacturer to the Manufacturer table, or adding a new building to the building table.

I'm thinking of two options, having 18 different FormViews in one page, each with insert/edit templates, or having 18 different pages, a page with a form for each table.

Is there any advantage or disadvantage to having that many FormViews in one page?

Thank You!

答:
Yes, That's an obvious thing. if you're handling 18 formviews on one single page which will be maintained by server then it will obviously decrease your performance. as each will have to intialize at some time. Performance will be decreased for sure. So I'll suggest you to do the work in smart way by creating 18 separate pages.

Hope it Helps.


问:
Error in installing opencv3 with homebrew and python3
I'm using homebrew installing opencv3 on OSX(EI Captain),

```<code>brew install opencv3 --with-contrib --with-python3 --HEAD
</code>```

and an error occurred:

```<code>Updating Homebrew...
==> Installing opencv3 from homebrew/science
==> Cloning https://github.com/opencv/opencv.git
Updating /Users/ksun/Library/Caches/Homebrew/opencv3--git
==> Checking out branch master
==> Cloning https://github.com/opencv/opencv_contrib.git
Updating /Users/ksun/Library/Caches/Homebrew/opencv3--contrib--git
> ==> Checking out branch master
Error: No such file or directory - /private/tmp/opencv3-20170330-14255-bxsn05/3rdparty/ippicv/downloader.cmake
</code>```

Can u guys help me find out how to fix it?

答:
I do brew edit opencv3, then comment the following line

```<code>inreplace buildpath/"3rdparty/ippicv/downloader.cmake",
  "${OPENCV_ICV_PLATFORM}-${OPENCV_ICV_PACKAGE_HASH}",
  "${OPENCV_ICV_PLATFORM}"
</code>```

then you can reinstall again with --HEAD

The opencv repository has fix some issue also removed file 3rdparty/ippicv/downloader.cmake, so no need to patch it any more. But they didn't issue a new release, so to install --with-contrib, you have to install with --HEAD, but disable the patch of file 3rdparty/ippicv/downloader.cmake

Body:
I'm using homebrew installing opencv3 on OSX(EI Captain),

brew install opencv3 --with-contrib --with-python3 --HEAD

and an error occurred:

Updating Homebrew...
==> Installing opencv3 from homebrew/science
==> Cloning https://github.com/opencv/opencv.git
Updating /Users/ksun/Library/Caches/Homebrew/opencv3--git
==> Checking out branch master
==> Cloning https://github.com/opencv/opencv_contrib.git
Updating /Users/ksun/Library/Caches/Homebrew/opencv3--contrib--git
> ==> Checking out branch master
Error: No such file or directory - /private/tmp/opencv3-20170330-14255-bxsn05/3rdparty/ippicv/downloader.cmake

Can u guys help me find out how to fix it?

Body:
I do brew edit opencv3, then comment the following line

inreplace buildpath/"3rdparty/ippicv/downloader.cmake",
  "${OPENCV_ICV_PLATFORM}-${OPENCV_ICV_PACKAGE_HASH}",
  "${OPENCV_ICV_PLATFORM}"

then you can reinstall again with --HEAD

The opencv repository has fix some issue also removed file 3rdparty/ippicv/downloader.cmake, so no need to patch it any more. But they didn't issue a new release, so to install --with-contrib, you have to install with --HEAD, but disable the patch of file 3rdparty/ippicv/downloader.cmake


问:
alternative to sub query in join
I have a SQL query that I'm trying to optimize.

Is there a better way to avoid using subquery here?
Got a suggestion on using Row_number(),
posting this with some corrections

```<code>DECLARE @curdate DATETIME
SET @curdate = GETDATE()

SELECT DISTINCT
    SIS.StudentID, StudentCoverage.StudentCoverageDataID,
    Student.FirstName, Student.LastName,
    Student.DateOfBirth, Student.Gender,
    ASMT.AssessmentDate
FROM
    SIS (NOLOCK)
INNER JOIN
    SISMaster (NOLOCK) ON SISMaster.SISID = SIS.SISID
INNER JOIN
    Assessment ASMT ON SIS.StudentID = ASMT.StudentId
INNER JOIN
    StudentCoverage (NOLOCK) ON StudentCoverage.StudentID = SIS.StudentID
INNER JOIN
    Organization (NOLOCK) ON StudentCoverage.OrgID = Organization.OrganizationID
INNER JOIN
    Student (NOLOCK) ON Student.StudentID = SIS.StudentID
INNER JOIN
    StudentCoverageData (NOLOCK) ON StudentCoverageData.StudentCoverageID = StudentCoverage.StudentCoverageID
           AND StudentCoverageData.StudentCoverageDataID = (SELECT TOP 1 StudentCoverageData.StudentCoverageDataID
                                                            FROM StudentCoverage
                                                            INNER JOIN StudentCoverageData ON StudentCoverageData.StudentCoverageID = StudentCoverage.StudentCoverageID
                                                            WHERE StudentCoverage.StudentId = SIS.StudentID
                                                              AND StudentCoverageData.Active = 1
                                                              AND StudentCoverageData.EffectiveDate <= @curdate
                                                              AND (StudentCoverageData.ExitDate IS NULL OR StudentCoverageData.ExitDate > @curdate)
                                                           ORDER BY StudentCoverageData.AsOfDate DESC)
</code>```

答:
All Tables in your subquery is exists in inner join clause, so you could rewrite your query like this:</p>

```<code>;WITH temps AS
(
    DECLARE @curdate DATETIME = GETDATE()

    SELECT
        SIS.StudentID, StudentCoverage.StudentCoverageDataID,
        Student.FirstName, Student.LastName,
        Student.DateOfBirth, Student.Gender,
        ASMT.AssessmentDate,
        ROW_NUMBER() OVER (PARTITION BY StudentCoverageData.StudentCoverageDataID ORDER BY StudentCoverageData.AsOfDate) AS RowIndex
    FROM
        SIS (NOLOCK)
    INNER JOIN
        SISMaster (NOLOCK) ON SISMaster.SISID = SIS.SISID
    INNER JOIN
        StudentCoverage (NOLOCK) ON StudentCoverage.StudentID = SIS.StudentID
    INNER JOIN
        Organization (NOLOCK) ON StudentCoverage.OrgID = Organization.OrganizationID
    INNER JOIN
        Student (NOLOCK) ON Student.StudentID = SIS.StudentID
    INNER JOIN
        StudentCoverageData (NOLOCK) ON StudentCoverageData.StudentCoverageID = StudentCoverage.StudentCoverageID
    WHERE StudentCoverageData.Active = 1
    AND StudentCoverageData.EffectiveDate <= @curdate
    AND (StudentCoverageData.ExitDate IS NULL OR StudentCoverageData.ExitDate > @curdate)
)
SELECT  * FROM temps t
WHERE t.RowIndex = 1
</code>```

Title: alternative to sub query in join

Body:
I have a SQL query that I'm trying to optimize.

Is there a better way to avoid using subquery here?
Got a suggestion on using Row_number(),
posting this with some corrections

DECLARE @curdate DATETIME
SET @curdate = GETDATE()

SELECT DISTINCT
    SIS.StudentID, StudentCoverage.StudentCoverageDataID,
    Student.FirstName, Student.LastName,
    Student.DateOfBirth, Student.Gender,
    ASMT.AssessmentDate
FROM
    SIS (NOLOCK)
INNER JOIN
    SISMaster (NOLOCK) ON SISMaster.SISID = SIS.SISID
INNER JOIN
    Assessment ASMT ON SIS.StudentID = ASMT.StudentId
INNER JOIN
    StudentCoverage (NOLOCK) ON StudentCoverage.StudentID = SIS.StudentID
INNER JOIN
    Organization (NOLOCK) ON StudentCoverage.OrgID = Organization.OrganizationID
INNER JOIN
    Student (NOLOCK) ON Student.StudentID = SIS.StudentID
INNER JOIN
    StudentCoverageData (NOLOCK) ON StudentCoverageData.StudentCoverageID = StudentCoverage.StudentCoverageID
           AND StudentCoverageData.StudentCoverageDataID = (SELECT TOP 1 StudentCoverageData.StudentCoverageDataID
                                                            FROM StudentCoverage
                                                            INNER JOIN StudentCoverageData ON StudentCoverageData.StudentCoverageID = StudentCoverage.StudentCoverageID
                                                            WHERE StudentCoverage.StudentId = SIS.StudentID
                                                              AND StudentCoverageData.Active = 1
                                                              AND StudentCoverageData.EffectiveDate <= @curdate
                                                              AND (StudentCoverageData.ExitDate IS NULL OR StudentCoverageData.ExitDate > @curdate)
                                                           ORDER BY StudentCoverageData.AsOfDate DESC)

Body:
All Tables in your subquery is exists in inner join clause, so you could rewrite your query like this:

;WITH temps AS
(
    DECLARE @curdate DATETIME = GETDATE()

    SELECT
        SIS.StudentID, StudentCoverage.StudentCoverageDataID,
        Student.FirstName, Student.LastName,
        Student.DateOfBirth, Student.Gender,
        ASMT.AssessmentDate,
        ROW_NUMBER() OVER (PARTITION BY StudentCoverageData.StudentCoverageDataID ORDER BY StudentCoverageData.AsOfDate) AS RowIndex
    FROM
        SIS (NOLOCK)
    INNER JOIN
        SISMaster (NOLOCK) ON SISMaster.SISID = SIS.SISID
    INNER JOIN
        StudentCoverage (NOLOCK) ON StudentCoverage.StudentID = SIS.StudentID
    INNER JOIN
        Organization (NOLOCK) ON StudentCoverage.OrgID = Organization.OrganizationID
    INNER JOIN
        Student (NOLOCK) ON Student.StudentID = SIS.StudentID
    INNER JOIN
        StudentCoverageData (NOLOCK) ON StudentCoverageData.StudentCoverageID = StudentCoverage.StudentCoverageID
    WHERE StudentCoverageData.Active = 1
    AND StudentCoverageData.EffectiveDate <= @curdate
    AND (StudentCoverageData.ExitDate IS NULL OR StudentCoverageData.ExitDate > @curdate)
)
SELECT  * FROM temps t
WHERE t.RowIndex = 1


问:
How to render table and math in Rmarkdown when called from Shiny App
I have a Rmarkdown file (info.rmd) that looks like this:

```<code>---
title: "Information"
theme: yeti
date: "4/1/2017"
output: html_document
---

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

```{r echo = FALSE, results = 'asis'}
library(knitr)
kable(mtcars[1:5, ], caption = "A knitr kable.")
```

## Formulation

Here is where we formulate
$$\sum_{i=1}^n X_i$$
</code>```

And the ShinyApp that calls Rmarkdown like this:

server.R

contains this

```<code>  output$markdown <- renderUI({
    HTML(markdown::markdownToHTML(knit('info.rmd', quiet = TRUE), fragment.only=TRUE))
  })
</code>```

ui.R

contains this:

```<code> fluidPage(uiOutput('markdown'))
</code>```

But how come the table and math generated looks like this?

What's the right way to do it?

When run independently outside Shiny the info.rmd produces the table properly:

I tried this in ui.R

```<code> includeHTML("info.html")
</code>```

Which shows the file html correctly, but prevent the plotting
and reactivity in other tabPanel() to work.

Update

Here is the new result after @Nice solution:

答:
Editing the shiny server part with the following should help:

```<code>output$markdown <- renderUI({
    markdown::markdownToHTML(knit('info.rmd', quiet = TRUE), fragment.only=TRUE)
    withMathJax(includeHTML("info.html"))
  })
</code>```

Alternatively you can also do the following:

```<code>output$markdown <- renderUI({
    markdown::markdownToHTML(knit('info.rmd', quiet = TRUE), fragment.only=TRUE)
    withMathJax(includeMarkdown("info.md"))
  })
</code>```

Body:
I have a Rmarkdown file (info.rmd) that looks like this:

---
title: "Information"
theme: yeti
date: "4/1/2017"
output: html_document
---

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

```{r echo = FALSE, results = 'asis'}
library(knitr)
kable(mtcars[1:5, ], caption = "A knitr kable.")
```

## Formulation

Here is where we formulate
$$\sum_{i=1}^n X_i$$

And the ShinyApp that calls Rmarkdown like this:

server.R

contains this

  output$markdown <- renderUI({
    HTML(markdown::markdownToHTML(knit('info.rmd', quiet = TRUE), fragment.only=TRUE))
  })

ui.R

contains this:

 fluidPage(uiOutput('markdown'))

But how come the table and math generated looks like this?

What's the right way to do it?

When run independently outside Shiny the info.rmd produces the table properly:

I tried this in ui.R

 includeHTML("info.html")

Which shows the file html correctly, but prevent the plotting
and reactivity in other tabPanel() to work.

Update

Here is the new result after @Nice solution:

Body:
Editing the shiny server part with the following should help:

output$markdown <- renderUI({
    markdown::markdownToHTML(knit('info.rmd', quiet = TRUE), fragment.only=TRUE)
    withMathJax(includeHTML("info.html"))
  })

Alternatively you can also do the following:

output$markdown <- renderUI({
    markdown::markdownToHTML(knit('info.rmd', quiet = TRUE), fragment.only=TRUE)
    withMathJax(includeMarkdown("info.md"))
  })


问:
Transactional Replication Questions
I have the following questions about how transactional replication handles the following. For the sake of example, assume database 'A' is being replicated (via transactional replication) to database 'B'.

If a table in database ‘A’ is dropped, will the table get dropped in ‘B’?

If a table in ‘A’ is renamed, what happens to the table in ‘B’?

If we drop a column in a table in database ‘A’, what will happen to the column in the same table in database ‘B’?

If we rename a column in a table in database ‘A’, what will happen to the column in the same table in database ‘B’?

Is replicating stored procs, views and UDF’s are optional?

Is there any way to avoid all the stored process being created in database ‘B’ as a result of it being the subscriber of a replication?
     a. If not, can we at least dictate what schema they are created in?

答:
Most of your questions are answered here: Frequently asked questions for Replication Administrators

You cannot drop a table that is replicated. You have to first drop the article.

You cannot rename a table that is replicated. You have to first drop the article.

Issuing ALTER TABLE … DROP COLUMN at the Publisher, will result in the command being replicated to the Subscriber.

You cannot rename a column "whilst" it is being replicated. You need to remove it from replication first.

Yes, it's optional.

What do you mean by created?

All of these items can be tested very easily by creating a very simple Replication topology on a test server. I suggest you do so in order to both plan for and practice your changes.

ContentLicense: CC BY-SA 2.5

Title: Transactional Replication Questions


问:
Excel table to Access query connection, [Microsoft][ODBC Microsoft Access Drive] too few parameters. expected 1
I'm trying to create a table in Excel, which takes data from Access Query. I'm unable to find this query listed under Data->From Access. I'm using Data->From Other Sources -> From Data connection Wizard -> ODBC DSN. On final step it throws error [Microsoft][ODBC Microsoft Access Drive]  too few parameters. expected 1.

I will not post full query at this moment, it is long

I will post subquery part (with some formatting) , that already throws this error. Can someone take a look and pinpoint where is the problem.

All queries I have work properly in Access. But I need the results export to Excel, as whole reporting VBA tool is there. (I know I can make SELECT INTO and create table, but it is not as elegant and simple to update) Thank you all for your time. Have a nice day

```<code>SELECT
Employees.PersNo,
Employees.Employee_name,
Employees.Reporting_Month,
Employees.Gender_Key,
Employees.Start_Date,
Employees.Business_Unit,
Employees.Position_ID,
Employees.Position,
Employees.Local_Band,
Employees.PS_Group,
Employees.Wage_Amount,
val(Employees.Bonus) AS [Bonus_%],
val([Employees].[Commissions_(%)]) AS [Commisions_%],
Employees.Wage_type, Employees.Wkhrs,
Q1.Business_Unit,
Q1.Position_ID,
Q1.Position,
Q1.Local_Band,
Q1.PS_Group,
Q1.Wage_Amount,
[Q1].[Bonus_%],
[Q1].[Commisions_%],
Employees.Wage_type,
Employees.Wkhrs,
Employees.Evid_Status

FROM Employees LEFT JOIN (SELECT
Dateadd("m",1,[Employees.Reporting_Month]) AS Reporting_Month,
Employees.PersNo,
Employees.Local_Band,
Employees.PS_Group,
Employees.Wage_Amount,
val(Employees.Bonus) AS [Bonus_%],
val([Employees].[Commissions_(%)]) AS [Commisions_%],
Employees.Wage_type, Employees.Wkhrs,
Employees.Business_Unit,
Employees.Position_ID,
Employees.Position,
Employees.Evid_Status
FROM Employees WHERE Employees.Evid_Status=1 )  AS Q1
ON (Employees.Reporting_Month = [Q1].[Reporting_Month]) AND (Employees.PersNo = [Q1].[PersNo])
WHERE Employees.Evid_Status=1;
</code>```

答:
Because Position is a reserved word in MS Accces, simply escape the word in both outer query and subquery with backticks or square brackets.

Interestingly, while the table alias qualifier works for reserved words inside the MSAccess.exe GUI program, external ODBC calls like from Excel may fail without escaping such reserved words:

```<code>SELECT
...
Employees.[Position],
...

SELECT
...
Employees.`Position`,
...
</code>```

Body:
I'm trying to create a table in Excel, which takes data from Access Query. I'm unable to find this query listed under Data->From Access. I'm using Data->From Other Sources -> From Data connection Wizard -> ODBC DSN. On final step it throws error [Microsoft][ODBC Microsoft Access Drive]  too few parameters. expected 1.

I will not post full query at this moment, it is long

I will post subquery part (with some formatting) , that already throws this error. Can someone take a look and pinpoint where is the problem.

All queries I have work properly in Access. But I need the results export to Excel, as whole reporting VBA tool is there. (I know I can make SELECT INTO and create table, but it is not as elegant and simple to update) Thank you all for your time. Have a nice day

SELECT
Employees.PersNo,
Employees.Employee_name,
Employees.Reporting_Month,
Employees.Gender_Key,
Employees.Start_Date,
Employees.Business_Unit,
Employees.Position_ID,
Employees.Position,
Employees.Local_Band,
Employees.PS_Group,
Employees.Wage_Amount,
val(Employees.Bonus) AS [Bonus_%],
val([Employees].[Commissions_(%)]) AS [Commisions_%],
Employees.Wage_type, Employees.Wkhrs,
Q1.Business_Unit,
Q1.Position_ID,
Q1.Position,
Q1.Local_Band,
Q1.PS_Group,
Q1.Wage_Amount,
[Q1].[Bonus_%],
[Q1].[Commisions_%],
Employees.Wage_type,
Employees.Wkhrs,
Employees.Evid_Status

FROM Employees LEFT JOIN (SELECT
Dateadd("m",1,[Employees.Reporting_Month]) AS Reporting_Month,
Employees.PersNo,
Employees.Local_Band,
Employees.PS_Group,
Employees.Wage_Amount,
val(Employees.Bonus) AS [Bonus_%],
val([Employees].[Commissions_(%)]) AS [Commisions_%],
Employees.Wage_type, Employees.Wkhrs,
Employees.Business_Unit,
Employees.Position_ID,
Employees.Position,
Employees.Evid_Status
FROM Employees WHERE Employees.Evid_Status=1 )  AS Q1
ON (Employees.Reporting_Month = [Q1].[Reporting_Month]) AND (Employees.PersNo = [Q1].[PersNo])
WHERE Employees.Evid_Status=1;

Body:
Because Position is a reserved word in MS Accces, simply escape the word in both outer query and subquery with backticks or square brackets.

Interestingly, while the table alias qualifier works for reserved words inside the MSAccess.exe GUI program, external ODBC calls like from Excel may fail without escaping such reserved words:

SELECT
...
Employees.[Position],
...

SELECT
...
Employees.`Position`,
...


问:
GLSL Vertex Shader Compilation Error
This is my following Error which is ERROR #160 in GLSL.

```<code>#version 330 core

layout (location = 0) in vec3 position;
out vec4 pos;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4(position, 1.0f);
    pos = position;
}
</code>```

and this is the error which was created when trying to compile this GLSL program.

```<code>ERROR: Vertex Shader Program Compilation Failed! Vertex shader failed to compile with the following errors:
ERROR: 0:13: error(#160) Cannot convert from: "in highp 3-component vector of vec3" to: "default out highp 4-component vector of vec4"
ERROR: error(#273) 1 compilation errors.  No code generated
</code>```

I have no knowledge on debugging GLSL so if there is anyone who can help it would e much appreciated.

答:
Well, your error is pretty clear. Since you assign position to pos, and pos is a vec4 while position is a vec3, and there is no implicit conversion for this, the compiler complains. To fix this, simply create a vec4 from you position, e.g.

```<code>pos = vec4(position, 1.0f);
</code>```

However, you should think about why you would need a vec4 for your position down the pipeline, or whether having pos be a vec3 would be sufficient or not.

Title: GLSL Vertex Shader Compilation Error

Body:
This is my following Error which is ERROR #160 in GLSL.

#version 330 core

layout (location = 0) in vec3 position;
out vec4 pos;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4(position, 1.0f);
    pos = position;
}

and this is the error which was created when trying to compile this GLSL program.

ERROR: Vertex Shader Program Compilation Failed! Vertex shader failed to compile with the following errors:
ERROR: 0:13: error(#160) Cannot convert from: "in highp 3-component vector of vec3" to: "default out highp 4-component vector of vec4"
ERROR: error(#273) 1 compilation errors.  No code generated

I have no knowledge on debugging GLSL so if there is anyone who can help it would e much appreciated.

Body:
Well, your error is pretty clear. Since you assign position to pos, and pos is a vec4 while position is a vec3, and there is no implicit conversion for this, the compiler complains. To fix this, simply create a vec4 from you position, e.g.

pos = vec4(position, 1.0f);

However, you should think about why you would need a vec4 for your position down the pipeline, or whether having pos be a vec3 would be sufficient or not.


问:
Passing an array to a GIMP module via Script-Fu

Minimal Working Example

I am attempting to pass an array of integers to a GIMP plugin using the Scheme Script-Fu interface. I have a source code file named main.c with the following content:

#include <libgimp/gimp.h>
#include <stdlib.h>
#include <stdio.h>

static void query (void);

static void run (
    const gchar *name,
    gint nparams,
    const GimpParam *param,
    gint *nreturn_vals,
    GimpParam **return_vals
);

const GimpPlugInInfo PLUG_IN_INFO = {
    NULL,  /* init_proc  */
    NULL,  /* quit_proc  */
    query, /* query_proc */
    run,   /* run_proc   */
};

MAIN ()

static void query (void)
{
    static GimpParamDef args[] = {
    {
      GIMP_PDB_INT32,
      "run-mode",
      "The run mode { RUN-INTERACTIVE (0), RUN-NONINTERACTIVE (1) }"
    },
    {
      GIMP_PDB_INT8ARRAY,
      "an array",
      ""
      "an array"
      }
    };

    gimp_install_procedure (
        "my-test-plugin",
        "My test plug-in",
        "Description",
        "Jane Doe <jane@doe.name>",
        "Copyright (C) Jane Doe\n"
        "http://foo.bar",
        "2017",
        g_strconcat("My test plug-in", "...", NULL),
        "RGB*, GRAY*",
        GIMP_PLUGIN,
        G_N_ELEMENTS (args),
        0,
        args,
        NULL
    );
}

static void run (
    const gchar *name,
    gint nparams,
    const GimpParam *param,
    gint *nreturn_vals,
    GimpParam **return_vals)
{
    static GimpParam value;
    value.type = GIMP_PDB_STATUS;
    value.data.d_status = GIMP_PDB_SUCCESS;
    *nreturn_vals = 1;
    *return_vals = &value;

    FILE* out = fopen("mylog.log", "w");
    fprintf(out, "Parameter #0:\t%d\nParameter #1:\t", param[0].data.d_int32);
    for (int i = 0; i < 16; ++i)
        fprintf(out, "%d ", param[1].data.d_int8array[i]);
    fprintf(out, "\n");
    fclose(out);
}
```

<p>I compile and install the file as a GIMP plugin on as follows:</p>

```sudo apt install libgimp2.0-dev
gcc `gimptool-2.0 --cflags --libs` main.c
gimptool-2.0 --install-bin ./a.out
```

<p>I am doing this on a Debian 9 box.
When I attempt to run the plugin using the Script-Fu interface:</p>

```(my-test-plugin 1 #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))
```

<p><img src="https://i.stack.imgur.com/3DAH8.png" alt="Calling the plugin via Script-Fu"></p>

<p>a file named <code>mylog.log</code> gets created with the following content:</p>

```Parameter #0:   1
Parameter #1:   1 0 0 0 0 0 0 0 64 201 246 126 174 85 0 0
```

<p>whereas the following is the expected content:</p>

```Parameter #0:   1
Parameter #1:   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
```

<h1>The Real-World Version</h1>

<p>I am attempting to use the <code>gimp-plugin-morphop</code> GIMP plugin using the Scheme Script-Fu interface. When I use the GUI, the plugin works as expected:</p>

<p><img src="https://i.stack.imgur.com/6Wypq.png" alt="Hit-or-Miss via GUI #1">
<img src="https://i.stack.imgur.com/WLgkO.png" alt="Hit-or-Miss via GUI #1"></p>

<p>However, when I use the following Script-Fu script:</p>

<pre class="lang-lisp prettyprint-override"><code>(plug-in-morphop RUN-NONINTERACTIVE 1 2 6 7
  #(-1 -1 -1 -1 -1 -1 -1
    -1  1 -1 -1 -1  1 -1
    -1 -1  0  0  0 -1 -1
    -1 -1  0  0  0 -1 -1
    -1 -1  0  0  0 -1 -1
    -1  1 -1 -1 -1  1 -1
    -1 -1 -1 -1 -1 -1 -1) 24 2)
</code>```

the plugin does not produce the expected result:

I modified the plugin to see what the actual difference was:

```<code>diff --git a/src/morphop-algorithms.c b/src/morphop-algorithms.c
index b927ba3..9dff320 100644
--- a/src/morphop-algorithms.c
+++ b/src/morphop-algorithms.c
@@ -166,7 +166,16 @@ void start_operation(GimpDrawable *drawable, GimpPreview *preview, MorphOpSettin
                GimpPixelRgn src_rgn_c, dst_rgn_c;
                guchar* src_preview_c = NULL, *dst_preview_c = NULL;

+               FILE* log = fopen("morphop-operation.log", "w");
                int i, j;
+               for(i = 0; i < STRELEM_DEFAULT_SIZE; i++) {
+                       for(j = 0; j < STRELEM_DEFAULT_SIZE; j++) {
+                               fprintf(log, "%d ", settings.element.matrix[i][j]);
+                       }
+                       fprintf(log, "\n");
+               }
+               fclose(log);
+
                // white structuring element
                for(i = 0; i < STRELEM_DEFAULT_SIZE; i++) {
                        for(j = 0; j < STRELEM_DEFAULT_SIZE; j++) {
</code>```

After using the module through the GUI, the morphop-operation.log file contains the following text:

```<code>-1 -1 -1 -1 -1 -1 -1
-1 1 -1 -1 -1 1 -1
-1 -1 0 0 0 -1 -1
-1 -1 0 0 0 -1 -1
-1 -1 0 0 0 -1 -1
-1 1 -1 -1 -1 1 -1
-1 -1 -1 -1 -1 -1 -1
</code>```

as expected. After running the Script-Fu code, the morphop-operation.log file contains the following text:

```<code>-1 0 0 86 0 103 114
-1 64 0 0 0 45 112
-1 41 64 0 0 105 104
-1 8 42 33 0 110 111
-1 95 8 0 112 45 112
-1 36 95 0 108 109 0
-1 86 36 0 117 111 32
</code>```

where the rightmost six integers on each row appear to be random garbage that changes at every invocation. Since settings.element.matrix is already an internal representation of the received array, I modified the plugin a little further to display the received array directly:

```<code>diff --git a/src/morphop.c b/src/morphop.c
index 3895770..cb814b6 100644
--- a/src/morphop.c
+++ b/src/morphop.c
@@ -150,9 +150,16 @@ static void run (
                                }

                                msettings.operator = param[3].data.d_int32;
-
+
+                               FILE* log = fopen("morphop-init.log", "w");
                                int i;
                                for (i = 0; i < STRELEM_DEFAULT_SIZE * STRELEM_DEFAULT_SIZE; i++) {
+                                       fprintf(log, "%d ", param[5].data.d_int8array[i]);
+                               }
+                               fprintf(log, "\n");
+                               fclose(log);
+
+                               for (i = 0; i < STRELEM_DEFAULT_SIZE * STRELEM_DEFAULT_SIZE; i++) {
                                        msettings.element.matrix[i % STRELEM_DEFAULT_SIZE][(int)ceil((i + 1.0) / STRELEM_DEFAULT_SIZE) - 1] = param[5].data.d_int8array[i];
                                }
</code>```

After running the Script-Fu code, the morphop-init.log file contains the following text:

```<code>255 255 255 255 255 255 255 0 64 169 248 158 193 85 0 0 64 170 248 158 193 85 0 0 33 0 0 0 0 0 0 0 112 108 117 103 45 105 110 45 109 111 114 112 104 111 112 0 32
</code>```

The values beyond the eighth appear to be random garbage, although some retain their value across several runs:

```<code>255 255 255 255 255 255 255 0 64 89 10 89 79 86 0 0 64 90 10 89 79 86 0 0 33 0 0 0 0 0 0 0 112 108 117 103 45 105 110 45 109 111 114 112 104 111 112 0 32
</code>```

```<code>(my-test-plugin 1 #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))
</code>```0

To me this signifies that the array is passed in a different format that the one expected by the plug-in. How do I pass an array into a GIMP plug-in via Script-Fu, so that it stays intact?

答:
Within the API, it is necessary to pass the size of the array before the array.

```<code>--- /tmp/plugin.orig    2017-04-02 16:45:34.902108610 +0200
+++ /tmp/plugin.c   2017-04-02 16:43:26.510105281 +0200
@@ -30,6 +30,11 @@
       "The run mode { RUN-INTERACTIVE (0), RUN-NONINTERACTIVE (1) }"
     },
     {
+      GIMP_PDB_INT32,
+      "array-size",
+      "The array bellow"
+    },
+    {
       GIMP_PDB_INT8ARRAY,
       "an array",
       ""
@@ -69,9 +74,9 @@
     *return_vals = &value;

     FILE* out = fopen("mylog.log", "w");
-    fprintf(out, "Parameter #0:\t%d\nParameter #1:\t", param[0].data.d_int32);
+    fprintf(out, "Parameter #0:\t%d\nParameter #2:\t", param[0].data.d_int32);
     for (int i = 0; i < 16; ++i)
-        fprintf(out, "%d ", param[1].data.d_int8array[i]);
+        fprintf(out, "%d ", param[2].data.d_int8array[i]);
     fprintf(out, "\n");
     fclose(out);
 }
</code>```

Then:

```<code> > (my-test-plugin 1 16 #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))
 (#t)
</code>```

Results in:

```<code>$ cat mylog.log
Parameter #0:   1
Parameter #2:   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
</code>```

And you can verify the parameters are implicitly linked by making the size larger than the length:

```<code>> (my-test-plugin 1 17 #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15))
Error: ( : 1) INT8 vector (argument 3) for function my-test-plugin has
size of 15 but expected size of 17
</code>```

(The preceding parameter being RUN-NONINTERACTIVE (1) or element-size (7), explains the differing amounts of available array contents in your 2 tests.)

Body:
Minimal Working Example

I am attempting to pass an array of integers to a GIMP plugin using the Scheme Script-Fu interface. I have a source code file named main.c with the following content:

#include <libgimp/gimp.h>
#include <stdlib.h>
#include <stdio.h>

static void query (void);

static void run (
    const gchar *name,
    gint nparams,
    const GimpParam *param,
    gint *nreturn_vals,
    GimpParam **return_vals
);

const GimpPlugInInfo PLUG_IN_INFO = {
    NULL,  /* init_proc  */
    NULL,  /* quit_proc  */
    query, /* query_proc */
    run,   /* run_proc   */
};

MAIN ()

static void query (void)
{
    static GimpParamDef args[] = {
    {
      GIMP_PDB_INT32,
      "run-mode",
      "The run mode { RUN-INTERACTIVE (0), RUN-NONINTERACTIVE (1) }"
    },
    {
      GIMP_PDB_INT8ARRAY,
      "an array",
      ""
      "an array"
      }
    };

    gimp_install_procedure (
        "my-test-plugin",
        "My test plug-in",
        "Description",
        "Jane Doe <jane@doe.name>",
        "Copyright (C) Jane Doe\n"
        "http://foo.bar",
        "2017",
        g_strconcat("My test plug-in", "...", NULL),
        "RGB*, GRAY*",
        GIMP_PLUGIN,
        G_N_ELEMENTS (args),
        0,
        args,
        NULL
    );
}

static void run (
    const gchar *name,
    gint nparams,
    const GimpParam *param,
    gint *nreturn_vals,
    GimpParam **return_vals)
{
    static GimpParam value;
    value.type = GIMP_PDB_STATUS;
    value.data.d_status = GIMP_PDB_SUCCESS;
    *nreturn_vals = 1;
    *return_vals = &value;

    FILE* out = fopen("mylog.log", "w");
    fprintf(out, "Parameter #0:\t%d\nParameter #1:\t", param[0].data.d_int32);
    for (int i = 0; i < 16; ++i)
        fprintf(out, "%d ", param[1].data.d_int8array[i]);
    fprintf(out, "\n");
    fclose(out);
}

I compile and install the file as a GIMP plugin on as follows:

sudo apt install libgimp2.0-dev
gcc `gimptool-2.0 --cflags --libs` main.c
gimptool-2.0 --install-bin ./a.out

I am doing this on a Debian 9 box.
When I attempt to run the plugin using the Script-Fu interface:

(my-test-plugin 1 #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))

a file named mylog.log gets created with the following content:

Parameter #0:   1
Parameter #1:   1 0 0 0 0 0 0 0 64 201 246 126 174 85 0 0

whereas the following is the expected content:

Parameter #0:   1
Parameter #1:   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

The Real-World Version

I am attempting to use the gimp-plugin-morphop GIMP plugin using the Scheme Script-Fu interface. When I use the GUI, the plugin works as expected:

However, when I use the following Script-Fu script:

(plug-in-morphop RUN-NONINTERACTIVE 1 2 6 7
  #(-1 -1 -1 -1 -1 -1 -1
    -1  1 -1 -1 -1  1 -1
    -1 -1  0  0  0 -1 -1
    -1 -1  0  0  0 -1 -1
    -1 -1  0  0  0 -1 -1
    -1  1 -1 -1 -1  1 -1
    -1 -1 -1 -1 -1 -1 -1) 24 2)

the plugin does not produce the expected result:

I modified the plugin to see what the actual difference was:

diff --git a/src/morphop-algorithms.c b/src/morphop-algorithms.c
index b927ba3..9dff320 100644
--- a/src/morphop-algorithms.c
+++ b/src/morphop-algorithms.c
@@ -166,7 +166,16 @@ void start_operation(GimpDrawable *drawable, GimpPreview *preview, MorphOpSettin
                GimpPixelRgn src_rgn_c, dst_rgn_c;
                guchar* src_preview_c = NULL, *dst_preview_c = NULL;

+               FILE* log = fopen("morphop-operation.log", "w");
                int i, j;
+               for(i = 0; i < STRELEM_DEFAULT_SIZE; i++) {
+                       for(j = 0; j < STRELEM_DEFAULT_SIZE; j++) {
+                               fprintf(log, "%d ", settings.element.matrix[i][j]);
+                       }
+                       fprintf(log, "\n");
+               }
+               fclose(log);
+
                // white structuring element
                for(i = 0; i < STRELEM_DEFAULT_SIZE; i++) {
                        for(j = 0; j < STRELEM_DEFAULT_SIZE; j++) {

After using the module through the GUI, the morphop-operation.log file contains the following text:

-1 -1 -1 -1 -1 -1 -1
-1 1 -1 -1 -1 1 -1
-1 -1 0 0 0 -1 -1
-1 -1 0 0 0 -1 -1
-1 -1 0 0 0 -1 -1
-1 1 -1 -1 -1 1 -1
-1 -1 -1 -1 -1 -1 -1

as expected. After running the Script-Fu code, the morphop-operation.log file contains the following text:

-1 0 0 86 0 103 114
-1 64 0 0 0 45 112
-1 41 64 0 0 105 104
-1 8 42 33 0 110 111
-1 95 8 0 112 45 112
-1 36 95 0 108 109 0
-1 86 36 0 117 111 32

where the rightmost six integers on each row appear to be random garbage that changes at every invocation. Since settings.element.matrix is already an internal representation of the received array, I modified the plugin a little further to display the received array directly:

diff --git a/src/morphop.c b/src/morphop.c
index 3895770..cb814b6 100644
--- a/src/morphop.c
+++ b/src/morphop.c
@@ -150,9 +150,16 @@ static void run (
                                }

                                msettings.operator = param[3].data.d_int32;
-
+
+                               FILE* log = fopen("morphop-init.log", "w");
                                int i;
                                for (i = 0; i < STRELEM_DEFAULT_SIZE * STRELEM_DEFAULT_SIZE; i++) {
+                                       fprintf(log, "%d ", param[5].data.d_int8array[i]);
+                               }
+                               fprintf(log, "\n");
+                               fclose(log);
+
+                               for (i = 0; i < STRELEM_DEFAULT_SIZE * STRELEM_DEFAULT_SIZE; i++) {
                                        msettings.element.matrix[i % STRELEM_DEFAULT_SIZE][(int)ceil((i + 1.0) / STRELEM_DEFAULT_SIZE) - 1] = param[5].data.d_int8array[i];
                                }

After running the Script-Fu code, the morphop-init.log file contains the following text:

255 255 255 255 255 255 255 0 64 169 248 158 193 85 0 0 64 170 248 158 193 85 0 0 33 0 0 0 0 0 0 0 112 108 117 103 45 105 110 45 109 111 114 112 104 111 112 0 32

The values beyond the eighth appear to be random garbage, although some retain their value across several runs:

255 255 255 255 255 255 255 0 64 89 10 89 79 86 0 0 64 90 10 89 79 86 0 0 33 0 0 0 0 0 0 0 112 108 117 103 45 105 110 45 109 111 114 112 104 111 112 0 32

255 255 255 255 255 255 255 0 64 217 110 172 167 85 0 0 64 218 110 172 167 85 0 0 33 0 0 0 0 0 0 0 112 108 117 103 45 105 110 45 109 111 114 112 104 111 112 0 32

To me this signifies that the array is passed in a different format that the one expected by the plug-in. How do I pass an array into a GIMP plug-in via Script-Fu, so that it stays intact?

Body:
Within the API, it is necessary to pass the size of the array before the array.

--- /tmp/plugin.orig    2017-04-02 16:45:34.902108610 +0200
+++ /tmp/plugin.c   2017-04-02 16:43:26.510105281 +0200
@@ -30,6 +30,11 @@
       "The run mode { RUN-INTERACTIVE (0), RUN-NONINTERACTIVE (1) }"
     },
     {
+      GIMP_PDB_INT32,
+      "array-size",
+      "The array bellow"
+    },
+    {
       GIMP_PDB_INT8ARRAY,
       "an array",
       ""
@@ -69,9 +74,9 @@
     *return_vals = &value;

     FILE* out = fopen("mylog.log", "w");
-    fprintf(out, "Parameter #0:\t%d\nParameter #1:\t", param[0].data.d_int32);
+    fprintf(out, "Parameter #0:\t%d\nParameter #2:\t", param[0].data.d_int32);
     for (int i = 0; i < 16; ++i)
-        fprintf(out, "%d ", param[1].data.d_int8array[i]);
+        fprintf(out, "%d ", param[2].data.d_int8array[i]);
     fprintf(out, "\n");
     fclose(out);
 }

Then:

 > (my-test-plugin 1 16 #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))
 (#t)

Results in:

$ cat mylog.log
Parameter #0:   1
Parameter #2:   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

And you can verify the parameters are implicitly linked by making the size larger than the length:

> (my-test-plugin 1 17 #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15))
Error: ( : 1) INT8 vector (argument 3) for function my-test-plugin has
size of 15 but expected size of 17

(The preceding parameter being RUN-NONINTERACTIVE (1) or element-size (7), explains the differing amounts of available array contents in your 2 tests.)


问:
Iterative MergeSort Time Complexity (Bottom-Up)
I have a problem with finding the time-complexity.

Firtly, speaking about the outer FOR in MergeSort, i think that the repetitions are (1+ Sumation(from i=1, to sizeOfArray)(2*i) = 1+(2+4+8+16+32+...+size) but i also think that i am very wrong.

I also have a problem measuring the inside FOR-loop repetitions.

MergeSort(){     //Iterative Version (Bottom-Up)

```<code>            for(int currentSize = 1; currentSize < length; currentSize *= 2)        {
                for(int low = 0; low < length - currentSize; low += 2*currentSize){

                    int mid = low + currentSize - 1;
                    //min() is used here so if low is very close to the end of the array, high doesn't take outOfBoundries Value.
                    int high = Math.min(low + currentSize*2 -1, length - 1);

                }
            }
</code>```

}

merge(int low, int middle, int high) {

```<code>            // Copy both parts into the helper array
            for (int i = low; i <= high; i++) {
                    helper[i] = arrayForMergeSort[i];
            }

            int i = low;
            int j = middle + 1;
            int k = low;
            // Copy the smallest values from either the left or the right side back
            // to the original array
            while (i <= middle && j <= high) {
                    if (helper[i] <= helper[j]) {

                            arrayForMergeSort[k] = helper[i];
                            i++;
                    } else {

                            arrayForMergeSort[k] = helper[j];
                            j++;
                    }
                    k++;
            }
            // Copy the rest of the left side of the array into the target array
            while (i <= middle) {
                    arrayForMergeSort[k] = helper[i];
                    k++;
                    i++;
            }

    }
</code>```

答:
For the outer loop, the number of iterations is ceil(log2(length)).

For the inner loop, the number of runs to be merged on each iteration is ceil(length / currentSize) or floor((length + currentSize - 1) / currentSize). If this is an even number, then the last run's size may be less than currentSize. If this is an odd number, then the last run has no run to merge with and also may be less than currrentSize. I'm not sure there's a way to calculate the total number of merge operations without using iteration to sum the merge operations per iteration.

In a "production" version of merge sort, a one time allocation of a working array the same (or 1/2) the size of the original array is done, and then the direction of merge (original to working or working to original is changed with each outer loop. If the program pre-caculates the number of outer iterations, and it is an odd number, then a pre-pass can be done to swap elements in place on the initial pass, so that an even number of merge passes are done, with the sorted data ending up in the original array.

Body:
I have a problem with finding the time-complexity.

Firtly, speaking about the outer FOR in MergeSort, i think that the repetitions are (1+ Sumation(from i=1, to sizeOfArray)(2*i) = 1+(2+4+8+16+32+...+size) but i also think that i am very wrong.

I also have a problem measuring the inside FOR-loop repetitions.

MergeSort(){     //Iterative Version (Bottom-Up)

            for(int currentSize = 1; currentSize < length; currentSize *= 2)        {
                for(int low = 0; low < length - currentSize; low += 2*currentSize){

                    int mid = low + currentSize - 1;
                    //min() is used here so if low is very close to the end of the array, high doesn't take outOfBoundries Value.
                    int high = Math.min(low + currentSize*2 -1, length - 1);

                }
            }

}

merge(int low, int middle, int high) {

            // Copy both parts into the helper array
            for (int i = low; i <= high; i++) {
                    helper[i] = arrayForMergeSort[i];
            }

            int i = low;
            int j = middle + 1;
            int k = low;
            // Copy the smallest values from either the left or the right side back
            // to the original array
            while (i <= middle && j <= high) {
                    if (helper[i] <= helper[j]) {

                            arrayForMergeSort[k] = helper[i];
                            i++;
                    } else {

                            arrayForMergeSort[k] = helper[j];
                            j++;
                    }
                    k++;
            }
            // Copy the rest of the left side of the array into the target array
            while (i <= middle) {
                    arrayForMergeSort[k] = helper[i];
                    k++;
                    i++;
            }

    }


问:
Version Suffix not honored when creating NuGet packages with project references
I recently migrated my .NET Core projects from project.json to .csproj. The solution contains multiple projects, some of which references project using ProjectReference.

```<code>    <ItemGroup>
        <ProjectReference Include="..\RawRabbit\RawRabbit.csproj" />
    </ItemGroup>
</code>```

I have a PowerShell script that I've for a long time, that traverses the project folders and creates NuGet packages for each project

```<code>dotnet pack -c Release -o ..\..\artifacts --version-suffix=$buildSuffix
</code>```

Where $buildSuffix is something like beta7. The version suffix is shared between all project dependencies, meaning that all project dependencies are for a pre-release uses the same version suffixed (beta7 in this example).

In order for the package to get the right version suffix, I've updated the csproj so that my projects are using VersionPrefix rather than Version

```<code>    <PropertyGroup>
        <VersionPrefix>2.0.0</VersionPrefix>
    </PropertyGroup>
</code>```

The NuGet package gets the right version number (e.g. 2.0.0-beta7), but the  project dependencies in the nuspec file (within the nupkg file) are referenced without the VersionSuffix used during build.

```<code><dependencies>
  <group targetFramework=".NETStandard1.5">
    <dependency id="RawRabbit" version="2.0.0" exclude="Build,Analyzers" />
  </group>
</dependencies>
</code>```

This is problematic, as my newly created pre-release gets a dependency an release that does not exist (in this case 2.0.0 rather than 2.0.0-beta7).

I'm not really sure if this is the expected behavior, if so: any ideas as how I would configure my build so that it honors the VersionSuffix when creating NuGet package?

答:
Ok, so looks like it is a bug after all:

https://github.com/NuGet/Home/issues/4337
https://github.com/dotnet/cli/issues/6025

Body:
I recently migrated my .NET Core projects from project.json to .csproj. The solution contains multiple projects, some of which references project using ProjectReference.

    <ItemGroup>
        <ProjectReference Include="..\RawRabbit\RawRabbit.csproj" />
    </ItemGroup>

I have a PowerShell script that I've for a long time, that traverses the project folders and creates NuGet packages for each project

dotnet pack -c Release -o ..\..\artifacts --version-suffix=$buildSuffix

Where $buildSuffix is something like beta7. The version suffix is shared between all project dependencies, meaning that all project dependencies are for a pre-release uses the same version suffixed (beta7 in this example).

In order for the package to get the right version suffix, I've updated the csproj so that my projects are using VersionPrefix rather than Version

    <PropertyGroup>
        <VersionPrefix>2.0.0</VersionPrefix>
    </PropertyGroup>

The NuGet package gets the right version number (e.g. 2.0.0-beta7), but the  project dependencies in the nuspec file (within the nupkg file) are referenced without the VersionSuffix used during build.

<dependencies>
  <group targetFramework=".NETStandard1.5">
    <dependency id="RawRabbit" version="2.0.0" exclude="Build,Analyzers" />
  </group>
</dependencies>

This is problematic, as my newly created pre-release gets a dependency an release that does not exist (in this case 2.0.0 rather than 2.0.0-beta7).

I'm not really sure if this is the expected behavior, if so: any ideas as how I would configure my build so that it honors the VersionSuffix when creating NuGet package?


问:
How can I solve removing object that is shared among others
I have this scenario:

```<code>struct B
{
   A * ptr;
}

A * a1 = new A1;

b1.ptr = a1
b2.ptr = a1
b3.ptr = a2
</code>```

Now I delete a1 at some different place, but there are no information about b objects.  How can I automatically set:

```<code>b1.ptr = null
b2.ptr = null
</code>```

Or how is this mechanism called, so I can "google" some more info.

答:
This is basically a copy of the example at cppreference - std::weak_ptr. It assigns shared pointers to the B.ptrs and later checks, if they are still valid. Note that this code doesn't set any ptr to NULL. Also note that the standard smart pointers require a compiler providing C++11.

```<code>#include <iostream>
#include <memory>

struct A {};

struct B {
    std::weak_ptr<A> ptr;
};

int main(int argc, char **argv)
{
    B b1, b2, b3;

    {
        std::shared_ptr<A> a1{new A()};
        std::shared_ptr<A> a2{new A()};

        b1.ptr = a1;
        b2.ptr = a1;
        b3.ptr = a2;
    }

    // a1 and a2 don't exist anymore

    auto tmp = b1.ptr.lock();
    if (tmp) {
        std::cout << "Ok to use\n";
    } else {
        std::cout << "Already deleted\n";
    }

    return 0;
}
</code>```

Body:
I have this scenario:

struct B
{
   A * ptr;
}

A * a1 = new A1;

b1.ptr = a1
b2.ptr = a1
b3.ptr = a2

Now I delete a1 at some different place, but there are no information about b objects.  How can I automatically set:

b1.ptr = null
b2.ptr = null

Or how is this mechanism called, so I can "google" some more info.

Body:
This is basically a copy of the example at cppreference - std::weak_ptr. It assigns shared pointers to the B.ptrs and later checks, if they are still valid. Note that this code doesn't set any ptr to NULL. Also note that the standard smart pointers require a compiler providing C++11.

#include <iostream>
#include <memory>

struct A {};

struct B {
    std::weak_ptr<A> ptr;
};

int main(int argc, char **argv)
{
    B b1, b2, b3;

    {
        std::shared_ptr<A> a1{new A()};
        std::shared_ptr<A> a2{new A()};

        b1.ptr = a1;
        b2.ptr = a1;
        b3.ptr = a2;
    }

    // a1 and a2 don't exist anymore

    auto tmp = b1.ptr.lock();
    if (tmp) {
        std::cout << "Ok to use\n";
    } else {
        std::cout << "Already deleted\n";
    }

    return 0;
}


答:
As far as I see, You use only src property of the element.
What's about keeping paths only?

```<code>var season = ['winter.jpg', 'spring.jpg', 'summer.jpg', 'fall.jpg'];
</code>```

and

```<code>document.times.src = season[start];
</code>```

Title: Simplifying Javascript array of images

Body:
what is the best way to simplify this javascript array?
     I am asked to create a page that slide shows 4 pictures it will use the
     onMouseOver and onMouseOut events. I haven't attached that part of the
     code in here. This is where I started but it looks too long. Can
     someone please simplify this for me? Thanks in Advance.

 var season = Array();
 var start = 0;
 var timeDelay=3000;

season[0]=new Image();
season[0].src="winter.jpg";
season[1]=new Image();
season[1].src="spring.jpg";
season[2]=new Image();
season[2].src="summer.jpg";
season[3]=new Image();
season[3].src="fall.jpg";

function changeSeason(){
    var size= season.length - 1;
    if( start < size ) {
         start++;
    }
    else {
         start = 0;
    }
    document.times.src= season[start].src;
    timeout=setTimeout('changeSeason()', timeDelay);
}

Body:
As far as I see, You use only src property of the element.
What's about keeping paths only?

var season = ['winter.jpg', 'spring.jpg', 'summer.jpg', 'fall.jpg'];

and

document.times.src = season[start];


问:
Can I use MTM to execute my testcases that are wriiten in Selenium Java using Eclipse IDE
I have a application scenario where I am currently executing my test cases(written in selenium C#) using MTM, I want to know whether same can be achieved using selenium java from eclipse? </p>

答:
No

You can't use MTM to execute Java tests, however Microsoft is moving away form that model. This is likely because of this issue and they have already moved to using Team Build with VSTS & TFS 2015+ to execute all sorts of Functional Tests.

https://blogs.msdn.microsoft.com/dgartner/2016/02/23/running-selenium-tests-as-part-of-your-release-with-vsts-release-management/

They have a specific task for this and you can now associate all automated test results with Requirements for reporting without the need for Test Cases in tge middle.


问:
How can I publish to a MQTT topic in a Amazon AWS Lambda function?
I would like to have an easy command like I use in the bash to publish something to a topic on MQTT inside a AWS Lambda function. Along the lines of:
mosquitto_pub -h my.server.com -t "light/set" -m "on"

Background: I would like to turn a lamp on and off with Alexa. Alexa can start a Lambda function, and inside of this Lambda function I would like to start an MQTT publish, because the lamp can listen to a MQTT topic and react on the messages there.(Maybe there are easier solutions, but we are in a complicated (university) network which makes many other approaches more difficult)

答:
The AWS SDK has two classes to work with IoT: Iot and IotData. IotData.publish is the method you are looking for. It looks like the Iot object is for working with things and IotData is for working with MQTT and shadows. This ought to be directly referenced in the documentation on MQTT and shadows, but it isn't.

This service (IotData) is also available in the CLI.


问:
Updating Hudson and plugins
I was wondering which steps are the best to upgrade hudson and the plugins.

I'm running 1.347 at the moment. I once tried to update which resulted into a mess because some plugins were incompatible.

Also i want to delete some plugins is it appropriate to just delete the hpi file? It would be nice to know how other people do this step and in which order.

Should i first upgrade hudson and then plugin by plugin?

And if a plugin breaks something downgrade it again? It seems to be a lot of work.
Or is there any easy way?

Also is it enough to save all the xml configuration files in case something breaks that i can recover?

Thanks in advance.

答:
My solution is overkill, but I was burned twice (once by a Hudson bug and once by plugin incompatibilities) and learned my lesson.

I have Hudson installed on a VM with the same plugins as my production instance and a couple of simple builds. When I feel it's time to upgrade, or want to check out the latest release, I upgrade Hudson on the VM and verify that it starts up and can do builds. I only upgrade the production system that all of our developers use after I've upgraded my test system. I generally don't do exhaustive tests on my test system; it's enough to make sure the combination of upgraded Hudson and plugins starts up properly.

When upgrading either the VM or the main system, I upgrade all the plugins, then upgrade Hudson itself and restart. (Since I have a test system, I'm not particularly worried about doing things step by step.)

I came up with my process before Hudson introduced downgrade support. I still use this process because it's important to me to have confidence that an upgrade is not going to break the system that other developers use. This setup also allows me to have an experimental setup that's separate from the main Hudson system, which I find useful.

Title: Updating Hudson and plugins


问:
Ruby on Rails: Including actions of different controllers into index view of another controller
I am currently into learning Ruby on Rails and I am stuck with a pretty simple thing. I already tried to google it (or look it up here), but I could not find the right answer (due to my RoR-beginnings it might searched with the wrong terms).

I am working on a small learning project to list different items (items_controller). Each of these items belong to a category. But because I want the users to either create, update or delete a category I created a categories_controller. Both controllers and views are working fine, but I want to include the Category of each item on the index-view (which is also the root_path) of my Items Controller. Here I get stuck (with the code and the logic behind it as well). What is the best way to do this?

Somehow I managed to get the category name into the edit.html.erb-form of the items_controller, but I don't really understand how:

items_controller:

```<code>def edit
  @item = Item.find(params[:id])
  @categories = Category.all.map{ |c| [c.name, c.id] }
end
</code>```

edit.html.erb (this is actually in _form.html.erb and rendered in edit.html.erb):

```<code><%= simple_form_for @item, :html => { :multipart => true } do |f| %>
  <%= f.select :category, @categories %>
  <%= f.input :title %>
  <%= f.input :url %>
  <%= f.button :submit %>
<% end %>
</code>```

答:
If you want to include the category of each items, You need to specify which column of categories table you want to display. Example : a column called name:

```<code><% @items.each do |item| %>
 <%= item.category.name %>
<% end %>
</code>```

Body:
I am currently into learning Ruby on Rails and I am stuck with a pretty simple thing. I already tried to google it (or look it up here), but I could not find the right answer (due to my RoR-beginnings it might searched with the wrong terms).

I am working on a small learning project to list different items (items_controller). Each of these items belong to a category. But because I want the users to either create, update or delete a category I created a categories_controller. Both controllers and views are working fine, but I want to include the Category of each item on the index-view (which is also the root_path) of my Items Controller. Here I get stuck (with the code and the logic behind it as well). What is the best way to do this?

Somehow I managed to get the category name into the edit.html.erb-form of the items_controller, but I don't really understand how:

items_controller:

def edit
  @item = Item.find(params[:id])
  @categories = Category.all.map{ |c| [c.name, c.id] }
end

edit.html.erb (this is actually in _form.html.erb and rendered in edit.html.erb):

<%= simple_form_for @item, :html => { :multipart => true } do |f| %>
  <%= f.select :category, @categories %>
  <%= f.input :title %>
  <%= f.input :url %>
  <%= f.button :submit %>
<% end %>

Body:
If you want to include the category of each items, You need to specify which column of categories table you want to display. Example : a column called name:

<% @items.each do |item| %>
 <%= item.category.name %>
<% end %>


问:
how to call array 2D in PHP?
I have array 2d below, the variable ($C00 etc) has value itself.

```<code>   $matriks = array(array($C00, $C01, $C02, $C03),
             array($C10, $C11, $C12, $C13),
             array($C20, $C21, $C22, $C23),
             array($C30, $C31, $C32, $C33));
</code>```

i want to use that array 2d on next page, with submit form method POST:
i dunno this code corret or not :).

```<code>foreach ($matriks as $val) {
foreach ($val as $v) {
echo '<input type="hidden" name="Matriks[][]" value="'.$v.'">';
}}
</code>```

then how to call it in action page? (after submit)
my code like this but still eror.

```<code>$matriks=array();
foreach($_POST['Matriks'] as $key => $val) {
foreach ($val as $k => $v) {
    $matriks[$key][$k] = $v;
}}
</code>```

答:
Update this part of your code as shown:

```<code>foreach ($matriks as $i => $val) {
    foreach ($val as $v) {
        echo '<input type="hidden" name="Matriks[' . $i . '][]" value="'.$v.'">' . "\n";
    }
}
</code>```

Using the $i key ensures that your matrix is well represented in the DOM, else all your values would only overwrite each-other at position [0, 0].

If you var_dump your $_POST on the action page, you'd see your matrix output like this:

```<code>array (size=1)
  'Matriks' =>
    array (size=4)
      0 =>
        array (size=4)
          0 => string '00' (length=2)
          1 => string '01' (length=2)
          2 => string '02' (length=2)
          3 => string '03' (length=2)
      1 =>
        array (size=4)
          0 => string '10' (length=2)
          1 => string '11' (length=2)
          2 => string '12' (length=2)
          3 => string '13' (length=2)
      2 =>
        array (size=4)
          0 => string '20' (length=2)
          1 => string '21' (length=2)
          2 => string '22' (length=2)
          3 => string '23' (length=2)
      3 =>
        array (size=4)
          0 => string '30' (length=2)
          1 => string '31' (length=2)
          2 => string '32' (length=2)
          3 => string '33' (length=2)
</code>```

Title: how to call array 2D in PHP?

Body:
I have array 2d below, the variable ($C00 etc) has value itself.

   $matriks = array(array($C00, $C01, $C02, $C03),
             array($C10, $C11, $C12, $C13),
             array($C20, $C21, $C22, $C23),
             array($C30, $C31, $C32, $C33));

i want to use that array 2d on next page, with submit form method POST:
i dunno this code corret or not :).

foreach ($matriks as $val) {
foreach ($val as $v) {
echo '<input type="hidden" name="Matriks[][]" value="'.$v.'">';
}}

then how to call it in action page? (after submit)
my code like this but still eror.

$matriks=array();
foreach($_POST['Matriks'] as $key => $val) {
foreach ($val as $k => $v) {
    $matriks[$key][$k] = $v;
}}

Body:
Update this part of your code as shown:

foreach ($matriks as $i => $val) {
    foreach ($val as $v) {
        echo '<input type="hidden" name="Matriks[' . $i . '][]" value="'.$v.'">' . "\n";
    }
}

Using the $i key ensures that your matrix is well represented in the DOM, else all your values would only overwrite each-other at position [0, 0].

If you var_dump your $_POST on the action page, you'd see your matrix output like this:

array (size=1)
  'Matriks' =>
    array (size=4)
      0 =>
        array (size=4)
          0 => string '00' (length=2)
          1 => string '01' (length=2)
          2 => string '02' (length=2)
          3 => string '03' (length=2)
      1 =>
        array (size=4)
          0 => string '10' (length=2)
          1 => string '11' (length=2)
          2 => string '12' (length=2)
          3 => string '13' (length=2)
      2 =>
        array (size=4)
          0 => string '20' (length=2)
          1 => string '21' (length=2)
          2 => string '22' (length=2)
          3 => string '23' (length=2)
      3 =>
        array (size=4)
          0 => string '30' (length=2)
          1 => string '31' (length=2)
          2 => string '32' (length=2)
          3 => string '33' (length=2)


问:
Change time string to double
So basically to change string time like "HH:MM:SS", I have to use TimeSpan.Parse. But my professor gave me the string form like this "MM:SS.FF". And surely I tried TimeSpan.Parse, but it threw some exception. So my question is what should i use in this case?</p>

```<code>string aTime = "00:30.19";
</code>```

答: You can convert it to number manually. For example two low value digits for second, next two digits for minutes and so on.</p>

Title: Change time string to double

Body:
So basically to change string time like "HH:MM:SS", I have to use TimeSpan.Parse. But my professor gave me the string form like this "MM:SS.FF". And surely I tried TimeSpan.Parse, but it threw some exception. So my question is what should i use in this case?

string aTime = "00:30.19";


问:
C fscanf reading data from file error
I am new in C and I am trying to write a program that will read data from a file and store them in an array (so I can later work with them).

```<code>#include <stdio.h>
#include <stdlib.h>

int day[3], month[3], year[3], hour[3], minute[3], second[3];
float value[3];

int main()
{
    // Open the file for read
    FILE* file1 = fopen("test.txt", "r");

    // Safety check
    if (file1 == NULL)
    {
        printf("Error: file1 == NULL\n");
        getchar();
        return 0;
    }

    // Open the new file for write
    FILE* file2 = fopen("new.txt", "w");

    // Safety check
    if (file2 == NULL)
    {
        printf("Error: file2 == NULL\n");
        getchar();
        return 0;
    }

    int j = 0;

        for (j = 0; j < 4; j++)
        {
            int count = fscanf(file1, "%d-%d-%d %d:%d:%d %f", &day[j], &month[j], &year[j], &hour[j], &minute[j], &second[j], &value[j]);
            printf("%d-%d-%d %d:%d:%d %f\n", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
            // Check for finising early
            if (count == EOF)
            {
                printf("EOF");
            }
        }

    // Close the original file
    fclose(file1);
    // Close the target file
    fclose(file2);

    getchar();
}
</code>```

The file contains the data in this format:

```<code>20-03-17 08:49:01 28,515
20-03-17 08:49:31 29,1837
20-03-17 08:50:01 27,845
</code>```

EDIT AFTER COMMENTS:

The code now does not crash any more and it works almost perfectly!

This is what comes out:

```<code>20-3-17 8:49:1 28.514999
20-3-17 8:49:31 29.183701
20-3-17 8:50:1 27.844999
1105469112-1-20 17:8:49 0.000000
</code>```

is there a way to fix the decimal problem?
and any idea what is that last line?

Thank you for your time!

答:
This is how i do it, but I'm certainly not a master at programming in C myself.
I think best would be to use stat though, for file size etc.

You could do something like:

```<code>   #include <stdio.h>
   #include <string.h>
   #include <stdlib.h>
   #include <sys/stat.h>
   #define dir "/path/to/file"
   #define MAX_WORDS 32
   int main() {
       FILE *fp;
       struct stat stz;
       stat(dir, &stz);
       int charz;
       char data[4096], buff[8];
       char *words[MAX_WORDS];
       if (stz.st_size > 0) {
            fp = fopen(dir, "r");
            fseek(fp, 0, SEEK_SET);
            for (i = 0; i < stz.st_size; i++) {
                charz = fgetc(fp);
                if (charz == 10) {
                    strcat(data, " ");

                } else {
                    sprintf(buff, "%c", charz);
                    strcat(data, buff);
                }
            }
            fclose(fp);
            words[0] = strtok(data, " ");
            for (i = 0; i < MAX_WORDS; i++) {
                if (!words[i]) {
                    break;
                }
                words[i+1] = strtok(NULL, " ");
            }
       } else {
             printf("No data available in given directory");
       }
       return 0;
   }
</code>```

This puts each byte into variable charz, then to a single character buffer, and concatenates said character onto the end of string data if the character is not equal to 10 (NewLine), otherwise, it adds a space, or delimiter.

Then, you can initialize an array of words by splitting the string.

Title: C fscanf reading data from file error

Body:
I am new in C and I am trying to write a program that will read data from a file and store them in an array (so I can later work with them).

#include <stdio.h>
#include <stdlib.h>

int day[3], month[3], year[3], hour[3], minute[3], second[3];
float value[3];

int main()
{
    // Open the file for read
    FILE* file1 = fopen("test.txt", "r");

    // Safety check
    if (file1 == NULL)
    {
        printf("Error: file1 == NULL\n");
        getchar();
        return 0;
    }

    // Open the new file for write
    FILE* file2 = fopen("new.txt", "w");

    // Safety check
    if (file2 == NULL)
    {
        printf("Error: file2 == NULL\n");
        getchar();
        return 0;
    }

    int j = 0;

        for (j = 0; j < 4; j++)
        {
            int count = fscanf(file1, "%d-%d-%d %d:%d:%d %f", &day[j], &month[j], &year[j], &hour[j], &minute[j], &second[j], &value[j]);
            printf("%d-%d-%d %d:%d:%d %f\n", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
            // Check for finising early
            if (count == EOF)
            {
                printf("EOF");
            }
        }

    // Close the original file
    fclose(file1);
    // Close the target file
    fclose(file2);

    getchar();
}

The file contains the data in this format:

20-03-17 08:49:01 28,515
20-03-17 08:49:31 29,1837
20-03-17 08:50:01 27,845

EDIT AFTER COMMENTS:

The code now does not crash any more and it works almost perfectly!

This is what comes out:

20-3-17 8:49:1 28.514999
20-3-17 8:49:31 29.183701
20-3-17 8:50:1 27.844999
1105469112-1-20 17:8:49 0.000000

is there a way to fix the decimal problem?
and any idea what is that last line?

Thank you for your time!

Body:
This is how i do it, but I'm certainly not a master at programming in C myself.
I think best would be to use stat though, for file size etc.

You could do something like:

   #include <stdio.h>
   #include <string.h>
   #include <stdlib.h>
   #include <sys/stat.h>
   #define dir "/path/to/file"
   #define MAX_WORDS 32
   int main() {
       FILE *fp;
       struct stat stz;
       stat(dir, &stz);
       int charz;
       char data[4096], buff[8];
       char *words[MAX_WORDS];
       if (stz.st_size > 0) {
            fp = fopen(dir, "r");
            fseek(fp, 0, SEEK_SET);
            for (i = 0; i < stz.st_size; i++) {
                charz = fgetc(fp);
                if (charz == 10) {
                    strcat(data, " ");

                } else {
                    sprintf(buff, "%c", charz);
                    strcat(data, buff);
                }
            }
            fclose(fp);
            words[0] = strtok(data, " ");
            for (i = 0; i < MAX_WORDS; i++) {
                if (!words[i]) {
                    break;
                }
                words[i+1] = strtok(NULL, " ");
            }
       } else {
             printf("No data available in given directory");
       }
       return 0;
   }

This puts each byte into variable charz, then to a single character buffer, and concatenates said character onto the end of string data if the character is not equal to 10 (NewLine), otherwise, it adds a space, or delimiter.

Then, you can initialize an array of words by splitting the string.


问:
Hibernate HQL Query Null Columns
I have a simple HQL SELECT query. When the columns are not null, I'm able to retrieve the records. But if one of the columns are null, I don't get that record that has a null column.

Here's a sample HQL query:

```<code>SELECT p.name as name, p.price as price
FROM  Pets p
</code>```

If name or price is null, I don't get any entry for that particular record. I thought Hibernate will just return a null value for that column when it's null?

How can I provide an alternate value when the column is null?

I have tested this with Hibernate Console.

答:
Two things to confirm:

Your model is named Pets, right? Or is it Pet?

Do you really want only those two properties? The usual way is to retrieve the full object, like from Pet.

But even that should work fine (provided that the model is named Pets). Do you get any exceptions, or you just get an empty List? What's the SQL that hibernate is generating (you can see that by setting the property hibernate.show_sql to true). If you run this SQL by hand in your database, do you get any records?

Title: Hibernate HQL Query Null Columns

Body:
I have a simple HQL SELECT query. When the columns are not null, I'm able to retrieve the records. But if one of the columns are null, I don't get that record that has a null column.

Here's a sample HQL query:

SELECT p.name as name, p.price as price
FROM  Pets p

If name or price is null, I don't get any entry for that particular record. I thought Hibernate will just return a null value for that column when it's null?

How can I provide an alternate value when the column is null?

I have tested this with Hibernate Console.


问:
quotation, in bash, does not work for very long string
I have a very long string and i put it in '' in bash. But the bash recognize only a portion of the string ( please see the attached picture) and it is like the rest of string is not in quotations. How many character string should be in bash? How can i fix this?

答:
You can put the strings in a file and use pipe instead.

e.g. cat str | xargs mycmd


问:
CSS tabs with arrows and full background color hovers
I got the following tab bar navigation which I would like to do in CSS only:

On this screen, I have marked the last element "Endergebnis" as .active or :hover.

I thought about creating the arrows as pseudo elements with position: absolute, although about multiple elements using transform: rotate(x deg), but in every solution I do not know how to give each tab a full filling background-color.

Can anybody give me a good hint?

答:
You can use a pseudo and transform :

div {
  margin: 1em;
  border-radius: 0.25em;
  border: solid;
}

h1 {
  margin: 0;
  border-bottom: solid;
}

ul {
  margin: 0;
  ;
  padding: 0;
  list-style-type: none;
  overflow-y: hidden;
  white-space: nowrap;
}

li+li {
  padding: 1em 2em 1em 3em;
}

li {
  padding: 1em 2em;
  position: relative;
  display: inline-block;
  vertical-align: top;
}

li:hover,
li:hover+li:before,
li.active,
li.active+li:before {
  background: lightblue;
}

li:hover:before,
li.active:before {
  background: white;
}

li:last-child:after,
li+li:before {
  content: '';
  position: absolute;
  top: -0.2em;
  bottom: 0;
  border-right: solid;
  border-top: solid;
  pointer-events: none;
  box-sizing: border-box;
  box-shadow: 3px -3px 6px -3px gray;/* a shadow effect can be added too */
  width: 3em;
  transform: rotate(30deg) skewy(30deg);
  z-index: 1;
}

li:last-child:after {
  right: -1.5em;
  background: inherit;
}

li+li:before {
  left: -2em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h1>title</h1>
  <ul>
    <li> one </li>
    <li> two </li>
    <li> three </li>
    <li> four </li>
    <li class="active"> Active </li>
  </ul>
</div></code>```

Body:
You can use a pseudo and transform :

div {
  margin: 1em;
  border-radius: 0.25em;
  border: solid;
}

h1 {
  margin: 0;
  border-bottom: solid;
}

ul {
  margin: 0;
  ;
  padding: 0;
  list-style-type: none;
  overflow-y: hidden;
  white-space: nowrap;
}

li+li {
  padding: 1em 2em 1em 3em;
}

li {
  padding: 1em 2em;
  position: relative;
  display: inline-block;
  vertical-align: top;
}

li:hover,
li:hover+li:before,
li.active,
li.active+li:before {
  background: lightblue;
}

li:hover:before,
li.active:before {
  background: white;
}

li:last-child:after,
li+li:before {
  content: '';
  position: absolute;
  top: -0.2em;
  bottom: 0;
  border-right: solid;
  border-top: solid;
  pointer-events: none;
  box-sizing: border-box;
  box-shadow: 3px -3px 6px -3px gray;/* a shadow effect can be added too */
  width: 3em;
  transform: rotate(30deg) skewy(30deg);
  z-index: 1;
}

li:last-child:after {
  right: -1.5em;
  background: inherit;
}

li+li:before {
  left: -2em;
}

<div>
  <h1>title</h1>
  <ul>
    <li> one </li>
    <li> two </li>
    <li> three </li>
    <li> four </li>
    <li class="active"> Active </li>
  </ul>
</div>


问:
Time complexity of GCD code
I am trying to understand the time complexity for the below code:

```<code>int gcd(int n, int m) {
   if (n%m ==0) return m;
   if (n < m) swap(n, m);
   while (m > 0) {
       n = n%m;
       swap(n, m);
   }
   return n;
}
</code>```

I read the complexity of the above code is  Θ(logn). Can some one please explain me the logic behind it?

答:
Consider any two steps of the algorithm.

At some point, you have the numbers (a, b) with a > b. After the first step these turn to (b, c) with c = a mod b, and after the second step the two numbers will be (c, d) with d = b mod c.

Now think backwards. As d = b mod c, we know that b = kc + d for some k > 0. The smallest possibility is k = 1, therefore b ≥ 1c + d = c + d.

From that result and from a > b we get a > c + d. If we add the last two inequalities we just derived, we get that (a + b) > 2(c + d).
In words, after each two consecutive steps the sum of the two numbers decreases to less than half of its original size.

Now look at the very first step of the algorithm. At the beginning, we have some (a, b) with a > b. After the very first step we have (b, c) with c = a mod b, and clearly b > c. Hence, after the very first step both numbers are at most equal to the smaller of the two input numbers.

Putting those two results together, we may conclude that the number of iterations (recursive calls in other implementations) is at most logarithmic in the smaller input number. In other words, the number of iterations is at most linear in the number of digits in the smaller input number.

Title: Time complexity of GCD code

Body:
I am trying to understand the time complexity for the below code:

int gcd(int n, int m) {
   if (n%m ==0) return m;
   if (n < m) swap(n, m);
   while (m > 0) {
       n = n%m;
       swap(n, m);
   }
   return n;
}

I read the complexity of the above code is  Θ(logn). Can some one please explain me the logic behind it?


问:
Magick.NET to read raw and write lossless JPEG
I am stumped. How do I read a grayscale 8bit raw image and convert to lossless JPEG? This the code I have to read the raw image, but it is failing with a runtime exception of ImageMagick.MagickMissingDelegateErrorException

```<code>MagickReadSettings settings = new MagickReadSettings();
settings.Width = 1000;
settings.Height = 800;
MagickImage image = new MagickImage("c:/users/rfonseka/desktop/image.raw", settings);
</code>```

I am not sure how to convert it to JPEG2000 lossless format. I want to convert it in memory so I can output the bytes out to HTTP.

答:
You need to put the executable dcraw.exe into the directory that contains the Magick.NET dll when you want to read raw files. The zip file ImageMagick-7.X.X-X-Q16-x86-windows.zip that you can download from https://www.imagemagick.org/script/download.php#windows contains this file.

If you are using the AnyCPU version of Magick.NET you will need to configure the cache directory and place dcraw.exe file in that directory.

```<code>MagickAnyCPU.CacheDirectory = @"C:\MyProgram\MyTempDir";
</code>```

If you don't want to do this you will need to add the folder that contains the executable to your %PATH%.

Body:
I am stumped. How do I read a grayscale 8bit raw image and convert to lossless JPEG? This the code I have to read the raw image, but it is failing with a runtime exception of ImageMagick.MagickMissingDelegateErrorException

MagickReadSettings settings = new MagickReadSettings();
settings.Width = 1000;
settings.Height = 800;
MagickImage image = new MagickImage("c:/users/rfonseka/desktop/image.raw", settings);

I am not sure how to convert it to JPEG2000 lossless format. I want to convert it in memory so I can output the bytes out to HTTP.

Body:
You need to put the executable dcraw.exe into the directory that contains the Magick.NET dll when you want to read raw files. The zip file ImageMagick-7.X.X-X-Q16-x86-windows.zip that you can download from https://www.imagemagick.org/script/download.php#windows contains this file.

If you are using the AnyCPU version of Magick.NET you will need to configure the cache directory and place dcraw.exe file in that directory.

MagickAnyCPU.CacheDirectory = @"C:\MyProgram\MyTempDir";

If you don't want to do this you will need to add the folder that contains the executable to your %PATH%.

ContentLicense: CC BY-SA 4.0


问:
Angular 2 CLI variables don't get updated
First of all, I'm totally new to Angular 2 and yesterday I tried using the Angular CLI for my first project ever, and failed. The Angular CLI seems to not be working for me - what I mean, the variables are not getting updated in my views.

I did the standard procedure here:

ng new projectname

cd projectname

npm start

The server at localhost:4200 starts and then I tried adding a new element - a paragraph - to the /src/app/app.component.html template:

```<code>    <p>This text gets displayed</p>
</code>```

The CLI informed me that everything is fine and the browser refreshed automatically, and then I saw the default "app works!" heading and my new paragraph with text inside.

But then, I decided to change the title variable in app.component.ts file, so my new class declaration looked like this:

```<code>    export class AppComponent {
        title = 'New App Title!';
    }
</code>```

The CLI again told me that everything is fine, but no changes were seen in the browser. I refreshed the page manually, but no changes were present - the heading still said "app works!".

So I tried adding a new variable to the file:

```<code>   otherText = "some other text";
</code>```

Then added another paragraph to my template:

```<code>   <p>New text: {{otherText}}</p>
</code>```

The paragraph got shown on the webpage, but the {{otherText}} variable contents were missing. The page looked like this:

```<code>    <h1>app works!</h1>
    <p>this text gets displayed</p>
    <p>New text: </p>
</code>```

Does anyone know what might be the problem here? What can I do to make the variables work? I don't have this kind of problem when I work with the standard quickstart package, only with the CLI.

I'm on a Windows 10 machine, I tried updating Node.js and NPM but that didn't help.

@edit: The variables actually get updated, but I have to start the server with ng serve, and I have to kill it and re-start it every time I make a change to a variable to see the changes.

答:
@angular/cli@1.0.0 has an error for live-reload.

Downgrade to @angular/cli@1.0.0-rc.4.
Then rm -rf node_modeules. Reinstall all of the dependencies.

Body:
First of all, I'm totally new to Angular 2 and yesterday I tried using the Angular CLI for my first project ever, and failed. The Angular CLI seems to not be working for me - what I mean, the variables are not getting updated in my views.

I did the standard procedure here:

ng new projectname

cd projectname

npm start

The server at localhost:4200 starts and then I tried adding a new element - a paragraph - to the /src/app/app.component.html template:

This text gets displayed

The CLI informed me that everything is fine and the browser refreshed automatically, and then I saw the default "app works!" heading and my new paragraph with text inside.

But then, I decided to change the title variable in app.component.ts file, so my new class declaration looked like this:

    export class AppComponent {
        title = 'New App Title!';
    }

The CLI again told me that everything is fine, but no changes were seen in the browser. I refreshed the page manually, but no changes were present - the heading still said "app works!".

So I tried adding a new variable to the file:

   otherText = "some other text";

Then added another paragraph to my template:

New text: {{otherText}}

The paragraph got shown on the webpage, but the {{otherText}} variable contents were missing. The page looked like this:

app works!

this text gets displayed

New text:

Does anyone know what might be the problem here? What can I do to make the variables work? I don't have this kind of problem when I work with the standard quickstart package, only with the CLI.

I'm on a Windows 10 machine, I tried updating Node.js and NPM but that didn't help.

@edit: The variables actually get updated, but I have to start the server with ng serve, and I have to kill it and re-start it every time I make a change to a variable to see the changes.


问:
I cant load admob rewaeded videos in my android app
I am using this code but it always write
W/Ads: Failed to load ad: 3
in the logcat..

```<code>RewardedVideoAd m2Ad = MobileAds.getRewardedVideoAdInstance(this);
    AdRequest adRequest = new AdRequest.Builder().build();
    m2Ad.loadAd("ca-app-pub-#########", adRequest);
    if (m2Ad.isLoaded()) {
        m2Ad.show();
    }
</code>```

答:
If you are running app in debug mode then you should use these Ad Unit ID according to Google Mobile Ads SDK Team

For Reward Videos, the following are our test Ad Unit ID

```<code>iOS - ca-app-pub-3940256099942544/1712485313
Android - ca-app-pub-3940256099942544/5224354917
</code>```

Note that Reward Video Ad Unit IDs are platform specific.

Body:
I am using this code but it always write
W/Ads: Failed to load ad: 3
in the logcat..

RewardedVideoAd m2Ad = MobileAds.getRewardedVideoAdInstance(this);
    AdRequest adRequest = new AdRequest.Builder().build();
    m2Ad.loadAd("ca-app-pub-#########", adRequest);
    if (m2Ad.isLoaded()) {
        m2Ad.show();
    }

Body:
If you are running app in debug mode then you should use these Ad Unit ID according to Google Mobile Ads SDK Team

For Reward Videos, the following are our test Ad Unit ID

iOS - ca-app-pub-3940256099942544/1712485313
Android - ca-app-pub-3940256099942544/5224354917

Note that Reward Video Ad Unit IDs are platform specific.


问:
Adding CheckBox to DefaultTableModel
I have a DefaultTableModel which is populated with an Object[][] array.

Now I want to add a column with checkBoxes and perform operations accordingly.

When I add the checkbox into the Object[][] array and view it, I get text displayed

'javax.swing.JCheckBox[,0,0,0x0....', how do I get it to show a checkbox and add actions to it?

答: JTable have default checkbox renderer/editor for boolean values. Just make your TableModel#getColumnClass return Boolean.class for given column.

Title: Adding CheckBox to DefaultTableModel