问:
How to properly access javascript object properties via this in the following example?
I want to create the following JavaScript object:

```<code>function Thumbnail(thumbnailUrl) {
    this.thumbnailUrl = thumbnailUrl;
    this.width = 200;
    this.height = 150;
    this.element = init(this.width, this.height, this.thumbnailUrl);
    this.element.addEventListener("mouseover",this.onmouseover);

    function init(width, height, thumbnailUrl) {
        var thumbViewHTML  = "<div class='container shadow' style='width:"+width+"px; height:"+height+"px; background: green;'>";
        thumbViewHTML += "<div class='container' style='width:100%; height:80%; background: yellow'>";
        thumbViewHTML += "<img class='centered' src='"+thumbnailUrl+"'  style = 'max-width: 100%; max-height: 100%;'/>";
        thumbViewHTML += "</div>";
        thumbViewHTML += "<div class='container' style='width: 100%; height:20%; background: black'>";
        thumbViewHTML += "<div class='textStyle centeredVertically' style='margin-left:5px; color: white'>Landscape</div>";
        thumbViewHTML += "</div>";
        thumbViewHTML += "</div>";

        return DOMElementFromHtml(thumbViewHTML);
    }

    return this;
}

Thumbnail.prototype.onmouseover = function() {
    console.log(this.width); //undefined with this pointing to this.element property on the Thumbnail object
}

function DOMElementFromHtml(htmlString) {
    var tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlString;
    return tempDiv.firstChild;
}
</code>```

When I access this.width on the onmouseover handler I get undefined because this points to the this.element member of the Thumbnail object. Is there any way to get this inside that method to point to the Thumbnail instance instead of the this.element instance.

I assume I could implement onmouseover in the local scope of the Thumbnail constructor and that might work but what if I want onmouseover to be a public method that can be modified externally?

答:
Bind the function to this like so:

```<code>this.element.addEventListener("mouseover",this.onmouseover.bind(this));
</code>```

Although you had this.onmouseover, as you don't call it right there, but (need to) pass a function reference, the actual call (when the event triggers) is not made with the this. prefix, and so it will be called without a specific context. Depending on whether you are in non-strict or strict mode, this will then refer to the global object or be undefined.

This behaviour you can override with bind, which creates a new function, but which will be ensured to have as context the argument you pass to it.

You can read more about the subject at "How does the this keyword work?"

Body:
I want to create the following JavaScript object:

function Thumbnail(thumbnailUrl) {
    this.thumbnailUrl = thumbnailUrl;
    this.width = 200;
    this.height = 150;
    this.element = init(this.width, this.height, this.thumbnailUrl);
    this.element.addEventListener("mouseover",this.onmouseover);

    function init(width, height, thumbnailUrl) {
        var thumbViewHTML  = "
";
        thumbViewHTML += "
";
        thumbViewHTML += "";
        thumbViewHTML += "
";
        thumbViewHTML += "
";
        thumbViewHTML += "
Landscape
";
        thumbViewHTML += "
";
        thumbViewHTML += "
";

        return DOMElementFromHtml(thumbViewHTML);
    }

    return this;
}

Thumbnail.prototype.onmouseover = function() {
    console.log(this.width); //undefined with this pointing to this.element property on the Thumbnail object
}

function DOMElementFromHtml(htmlString) {
    var tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlString;
    return tempDiv.firstChild;
}

When I access this.width on the onmouseover handler I get undefined because this points to the this.element member of the Thumbnail object. Is there any way to get this inside that method to point to the Thumbnail instance instead of the this.element instance.

I assume I could implement onmouseover in the local scope of the Thumbnail constructor and that might work but what if I want onmouseover to be a public method that can be modified externally?

Body:
Bind the function to this like so:

this.element.addEventListener("mouseover",this.onmouseover.bind(this));

Although you had this.onmouseover, as you don't call it right there, but (need to) pass a function reference, the actual call (when the event triggers) is not made with the this. prefix, and so it will be called without a specific context. Depending on whether you are in non-strict or strict mode, this will then refer to the global object or be undefined.

This behaviour you can override with bind, which creates a new function, but which will be ensured to have as context the argument you pass to it.

You can read more about the subject at "How does the this keyword work?"


来源: stackexchange

问:
MSDN Licensing?
Simple question, but one I can't find an answer to on the MSDN subscriber site: As an MSDN Professional Subscriber, can I install the same copy of Windows 2008 in multiple VMs at the same time?

The MSDN keys state that they can be used for "multiple activations", but they don't state whether these are sequential or concurrent. I seem to recall that Windows 2008 Enterprise has its own "you can run multiple instances in VMs" terms. Did I remember that right, and does that apply to MSDN subscriptions?

答: If i recall correctly, you can run 10 activations of each one concurrently in a test environment and not a production environment.</p>

OwnerDisplayName: Roger Lipscombe

ContentLicense: CC BY-SA 2.5

Title: MSDN Licensing?

LastEditorDisplayName: moocha

OwnerDisplayName: Tom Anderson


问:
How can I use the values Selected in a While Exists statement inside the While loop?
I'm new-ish to SQL and am trying to figure out how to use the values from the Select statement in a While Exists conditional loop.  The purpose is to combine multiple occurences of an attribute for a Document into a single field, and later pivot and join those results to the Document record.

For example, three tables exist like so:

ATTRIBUTES TABLE

ID, ATTRIBUTE_NAME

---------------------------

1, Created

2, Embedded_Image

...

ATTRIBUTE_VALUES TABLE

ATTRIBUTE_ID, VALUE, DOC_ID

-------------------------------------------

1, 2010/11/01, 1

2, 'Home.png', 1

2, 'Castle.png', 1

2, 'Apartment.jpg', 1

1, 2008/06/23, 2

2, 'Ski Jump.jpg', 2

2, 'Snowboarding.png', 2

...

DOCUMENTS TABLE

ID, TEXT

---------------------------

1, 'Homes of the ...'

2, 'Winter sports ...'

...

So a final Pivot and Join of the tables would look like so:

DOC_ID, TEXT, Created, Embedded_Image

----------------------------------------------------------------------------------------

1, 'Homes of the ...', 2010/11/01, 'Home.png,Castle.png,Apartment.jpg'

2, 'Winter sports ...', 2008/06/23, 'Ski Jump.jpg, Snowboarding.png'

The SQL While Exists condition I've tried to write looks like so:
    ```<code>
    DECLARE @LOOP_DOC_ID UNIQUEIDENTIFIER
    DECLARE @LOOP_ATTRIBUTE_NAME NVARCHAR(MAX)<br>
    WHILE EXISTS(
      SELECT [dbo].[ATTRIBUTE_VALUES].[DOC_ID], [dbo].[ATTRIBUTES].[ATTRIBUTE_NAME]
      FROM ([dbo].[ATTRIBUTE_VALUES] INNER JOIN [dbo].[ATTRIBUTES]
      ON [dbo].[ATTRIBUTE_VALUES].[ATTRIBUTE_ID] = [dbo].[ATTRIBUTES].[ID])
    )
    BEGIN
      SET @LOOP_DOC_ID = DOC_ID
      SET @LOOP_ATTRIBUTE_NAME = ATTRIBUTE_NAME<br>
      SELECT STUFF(
        (
          SELECT DISTINCT ',' + RTRIM(LTRIM([dbo].[ATTRIBUTE_VALUES].[VALUE]))
          FROM
            (
              [dbo].[ATTRIBUTE_VALUES] INNER JOIN [dbo].[ATTRIBUTES]
              ON [dbo].[ATTRIBUTE_VALUES].[ATTRIBUTE_ID] = [dbo].[ATTRIBUTES].[ID]
            )
          WHERE [dbo].[ATTRIBUTE_VALUES].[DOC_ID] = @LOOP_DOC_ID
                AND [dbo].[ATTRIBUTES].[ATTRIBUTE_NAME] = @LOOP_ATTRIBUTE_NAME
          ORDER BY ',' + RTRIM(LTRIM([dbo].[ATTRIBUTE_VALUES].[VALUE]))
          FOR XML PATH('')
        ), 1, 2, ''
      ) AS VALUE, @LOOP_DOC_ID AS DOC_ID, @LOOP_ATTRIBUTE_NAME AS ATTRIBUTE_NAME
    END
    </code>```
SQL Server doesn't like the lines where I'm trying to SET the variables to the values from the Select statement in the While Exists condition.

How can I use the [dbo].[ATTRIBUTE_VALUES].[DOC_ID], [dbo].[ATTRIBUTES].[ATTRIBUTE_NAME] values Selected in the While Exists conditional statement between the BEGIN and END statements?

Preferrably I would like to do away with the @LOOP_DOC_ID and @LOOP_ATTRIBUTE_NAME variables and deal directly with the values.

I've looked through forums that have talked about using Cursors to solve similar problems, but each one of them seem to recommend only using Cursors as a last resort due to their lack of speed.  I've also seen some people use stored procedures, but I can't use those, since my boss has ruled those as off-limits.  Am I in need of a Cursor, or is there a better way to do this?

答:
Have a look at something like this (Full Example)

```<code>DECLARE @ATTRIBUTES TABLE(
        ID INT,
        ATTRIBUTE_NAME VARCHAR(100)
)

INSERT INTO @ATTRIBUTES SELECT 1, 'Created'
INSERT INTO @ATTRIBUTES SELECT 2, 'Embedded_Image'

DECLARE @ATTRIBUTE_VALUES TABLE(
        ATTRIBUTE_ID INT,
        VALUE VARCHAR(100),
        DOC_ID INT
)
INSERT INTO @ATTRIBUTE_VALUES SELECT 1, '2010/11/01', 1
INSERT INTO @ATTRIBUTE_VALUES SELECT 2, 'Home.png', 1
INSERT INTO @ATTRIBUTE_VALUES SELECT 2, 'Castle.png', 1
INSERT INTO @ATTRIBUTE_VALUES SELECT 2, 'Apartment.jpg', 1
INSERT INTO @ATTRIBUTE_VALUES SELECT 1, '2008/06/23', 2
INSERT INTO @ATTRIBUTE_VALUES SELECT 2, 'Ski Jump.jpg', 2
INSERT INTO @ATTRIBUTE_VALUES SELECT 2, 'Snowboarding.png', 2

DECLARE @DOCUMENTS TABLE(
    ID INT,
    [TEXT] VARCHAR(100)
)

INSERT INTO @DOCUMENTS SELECT 1, 'Homes of the ...'
INSERT INTO @DOCUMENTS SELECT 2, 'Winter sports ...'

;WITH Vals AS (
        SELECT  d.ID DOC_ID,
                d.[TEXT] [TEXT],
                a.ATTRIBUTE_NAME,
                av.VALUE
        FROM    @DOCUMENTS d INNER JOIN
                @ATTRIBUTE_VALUES av ON d.ID = av.DOC_ID INNER JOIN
                @ATTRIBUTES a   ON  av.ATTRIBUTE_ID = a.ID
)
SELECT  *
FROM    (
            SELECT  DOC_ID,
                    [TEXT],
                    ATTRIBUTE_NAME,
                    stuff(
                            (
                                select  ',' + t.VALUE
                                from    Vals t
                                where   t.DOC_ID = v.DOC_ID
                                AND     t.ATTRIBUTE_NAME = v.ATTRIBUTE_NAME
                                order by t.VALUE
                                for xml path('')
                            ),1,1,'') Concats
            FROM    Vals v
            GROUP BY    DOC_ID,
                        [TEXT],
                        ATTRIBUTE_NAME
        ) s
PIVOT   ( MAX(ConCats) FOR ATTRIBUTE_NAME IN ([Created],[Embedded_Image])) pvt
</code>```

Output

```<code>DOC_ID  TEXT    Created Embedded_Image
1   Homes of the ...    2010/11/01  Apartment.jpg,Castle.png,Home.png
2   Winter sports ...   2008/06/23  Ski Jump.jpg,Snowboarding.png
</code>```

Body:
I'm new-ish to SQL and am trying to figure out how to use the values from the Select statement in a While Exists conditional loop.  The purpose is to combine multiple occurences of an attribute for a Document into a single field, and later pivot and join those results to the Document record.

For example, three tables exist like so:

ATTRIBUTES TABLE

ID, ATTRIBUTE_NAME

---------------------------

1, Created

2, Embedded_Image

...

ATTRIBUTE_VALUES TABLE

ATTRIBUTE_ID, VALUE, DOC_ID

-------------------------------------------

1, 2010/11/01, 1

2, 'Home.png', 1

2, 'Castle.png', 1

2, 'Apartment.jpg', 1

1, 2008/06/23, 2

2, 'Ski Jump.jpg', 2

2, 'Snowboarding.png', 2

...

DOCUMENTS TABLE

ID, TEXT

---------------------------

1, 'Homes of the ...'

2, 'Winter sports ...'

...

So a final Pivot and Join of the tables would look like so:

DOC_ID, TEXT, Created, Embedded_Image

----------------------------------------------------------------------------------------

1, 'Homes of the ...', 2010/11/01, 'Home.png,Castle.png,Apartment.jpg'

2, 'Winter sports ...', 2008/06/23, 'Ski Jump.jpg, Snowboarding.png'

The SQL While Exists condition I've tried to write looks like so:

    DECLARE @LOOP_DOC_ID UNIQUEIDENTIFIER
    DECLARE @LOOP_ATTRIBUTE_NAME NVARCHAR(MAX)

    WHILE EXISTS(
      SELECT [dbo].[ATTRIBUTE_VALUES].[DOC_ID], [dbo].[ATTRIBUTES].[ATTRIBUTE_NAME]
      FROM ([dbo].[ATTRIBUTE_VALUES] INNER JOIN [dbo].[ATTRIBUTES]
      ON [dbo].[ATTRIBUTE_VALUES].[ATTRIBUTE_ID] = [dbo].[ATTRIBUTES].[ID])
    )
    BEGIN
      SET @LOOP_DOC_ID = DOC_ID
      SET @LOOP_ATTRIBUTE_NAME = ATTRIBUTE_NAME

      SELECT STUFF(
        (
          SELECT DISTINCT ',' + RTRIM(LTRIM([dbo].[ATTRIBUTE_VALUES].[VALUE]))
          FROM
            (
              [dbo].[ATTRIBUTE_VALUES] INNER JOIN [dbo].[ATTRIBUTES]
              ON [dbo].[ATTRIBUTE_VALUES].[ATTRIBUTE_ID] = [dbo].[ATTRIBUTES].[ID]
            )
          WHERE [dbo].[ATTRIBUTE_VALUES].[DOC_ID] = @LOOP_DOC_ID
                AND [dbo].[ATTRIBUTES].[ATTRIBUTE_NAME] = @LOOP_ATTRIBUTE_NAME
          ORDER BY ',' + RTRIM(LTRIM([dbo].[ATTRIBUTE_VALUES].[VALUE]))
          FOR XML PATH('')
        ), 1, 2, ''
      ) AS VALUE, @LOOP_DOC_ID AS DOC_ID, @LOOP_ATTRIBUTE_NAME AS ATTRIBUTE_NAME
    END

SQL Server doesn't like the lines where I'm trying to SET the variables to the values from the Select statement in the While Exists condition.

How can I use the [dbo].[ATTRIBUTE_VALUES].[DOC_ID], [dbo].[ATTRIBUTES].[ATTRIBUTE_NAME] values Selected in the While Exists conditional statement between the BEGIN and END statements?

Preferrably I would like to do away with the @LOOP_DOC_ID and @LOOP_ATTRIBUTE_NAME variables and deal directly with the values.

I've looked through forums that have talked about using Cursors to solve similar problems, but each one of them seem to recommend only using Cursors as a last resort due to their lack of speed.  I've also seen some people use stored procedures, but I can't use those, since my boss has ruled those as off-limits.  Am I in need of a Cursor, or is there a better way to do this?

Body:
Have a look at something like this (Full Example)

DECLARE @ATTRIBUTES TABLE(
        ID INT,
        ATTRIBUTE_NAME VARCHAR(100)
)

INSERT INTO @ATTRIBUTES SELECT 1, 'Created'
INSERT INTO @ATTRIBUTES SELECT 2, 'Embedded_Image'

DECLARE @ATTRIBUTE_VALUES TABLE(
        ATTRIBUTE_ID INT,
        VALUE VARCHAR(100),
        DOC_ID INT
)
INSERT INTO @ATTRIBUTE_VALUES SELECT 1, '2010/11/01', 1
INSERT INTO @ATTRIBUTE_VALUES SELECT 2, 'Home.png', 1
INSERT INTO @ATTRIBUTE_VALUES SELECT 2, 'Castle.png', 1
INSERT INTO @ATTRIBUTE_VALUES SELECT 2, 'Apartment.jpg', 1
INSERT INTO @ATTRIBUTE_VALUES SELECT 1, '2008/06/23', 2
INSERT INTO @ATTRIBUTE_VALUES SELECT 2, 'Ski Jump.jpg', 2
INSERT INTO @ATTRIBUTE_VALUES SELECT 2, 'Snowboarding.png', 2

DECLARE @DOCUMENTS TABLE(
    ID INT,
    [TEXT] VARCHAR(100)
)

INSERT INTO @DOCUMENTS SELECT 1, 'Homes of the ...'
INSERT INTO @DOCUMENTS SELECT 2, 'Winter sports ...'

;WITH Vals AS (
        SELECT  d.ID DOC_ID,
                d.[TEXT] [TEXT],
                a.ATTRIBUTE_NAME,
                av.VALUE
        FROM    @DOCUMENTS d INNER JOIN
                @ATTRIBUTE_VALUES av ON d.ID = av.DOC_ID INNER JOIN
                @ATTRIBUTES a   ON  av.ATTRIBUTE_ID = a.ID
)
SELECT  *
FROM    (
            SELECT  DOC_ID,
                    [TEXT],
                    ATTRIBUTE_NAME,
                    stuff(
                            (
                                select  ',' + t.VALUE
                                from    Vals t
                                where   t.DOC_ID = v.DOC_ID
                                AND     t.ATTRIBUTE_NAME = v.ATTRIBUTE_NAME
                                order by t.VALUE
                                for xml path('')
                            ),1,1,'') Concats
            FROM    Vals v
            GROUP BY    DOC_ID,
                        [TEXT],
                        ATTRIBUTE_NAME
        ) s
PIVOT   ( MAX(ConCats) FOR ATTRIBUTE_NAME IN ([Created],[Embedded_Image])) pvt

Output

DOC_ID  TEXT    Created Embedded_Image
1   Homes of the ...    2010/11/01  Apartment.jpg,Castle.png,Home.png
2   Winter sports ...   2008/06/23  Ski Jump.jpg,Snowboarding.png


问:
Microsoft debug symbol don't work
I try to analyze some memory dump. But I stack on debug symbols of some Microsoft dll (sechost.dll).
What I do:

1) !sym noisy

2) .symfix

3) .sympath

My .sympath is:

```<code>Symbol search path is: srv*
Expanded Symbol search path is: cache*;SRV*http://msdl.microsoft.com/download/symbols
</code>```

4) analyze -v
After it I saw symbols loading.
But for some symbols I have

```<code>......
SYMSRV:  The operation timed out
SYMSRV:  http://msdl.microsoft.com/download/symbols/sechost.pdb/C4FD72A96E384F62A5F796624D37EAB42/sechost.pdb not found
SYMSRV:  C:\ProgramData\dbg\sym\sechost.pdb\C4FD72A96E384F62A5F796624D37EAB42\sechost.pdb not found
DBGHELP: sechost.pdb - file not found
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for sechost.dll -
DBGHELP: sechost - export symbols
......
</code>```

When actual analyze start I saw:

```<code>.....
IMAGE_NAME:  sechost.dll
BUCKET_ID:  WRONG_SYMBOLS
FAILURE_BUCKET_ID:  WRONG_SYMBOLS_80000003_sechost.dll!SubscribeServiceChangeNotifications
.....
</code>```

I understand that I don't have PDB for this DLL. I try load it with .reload /f sechost.dll. But analyze got stuck on same place.
How to deal with this?
Maybe there is possibility to increase connection timeout or other way to get what I need?

答:
Symbols was temporary unavailable on the server after cumulative update Win10 1607.
Microsoft already solved the issue.
Better solution in such kind of situations - report the issue to the maintainer.</p>

ContentLicense: CC BY-SA 3.0

Title: Microsoft debug symbol don't work

Body:
I try to analyze some memory dump. But I stack on debug symbols of some Microsoft dll (sechost.dll).
What I do:

1) !sym noisy

2) .symfix

3) .sympath

My .sympath is:

Symbol search path is: srv*
Expanded Symbol search path is: cache*;SRV*http://msdl.microsoft.com/download/symbols

4) analyze -v
After it I saw symbols loading.
But for some symbols I have

......
SYMSRV:  The operation timed out
SYMSRV:  http://msdl.microsoft.com/download/symbols/sechost.pdb/C4FD72A96E384F62A5F796624D37EAB42/sechost.pdb not found
SYMSRV:  C:\ProgramData\dbg\sym\sechost.pdb\C4FD72A96E384F62A5F796624D37EAB42\sechost.pdb not found
DBGHELP: sechost.pdb - file not found
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for sechost.dll -
DBGHELP: sechost - export symbols
......

When actual analyze start I saw:

.....
IMAGE_NAME:  sechost.dll
BUCKET_ID:  WRONG_SYMBOLS
FAILURE_BUCKET_ID:  WRONG_SYMBOLS_80000003_sechost.dll!SubscribeServiceChangeNotifications
.....

I understand that I don't have PDB for this DLL. I try load it with .reload /f sechost.dll. But analyze got stuck on same place.
How to deal with this?
Maybe there is possibility to increase connection timeout or other way to get what I need?


问:
JAVA Console error
If i run this code below in Netbeans

```<code>import java.io.Console;
public class Introduction {
    public static void main(String[] args) {
        Console console= System.console();// creates a java Object which has method that allows us to write
        console.printf("Hallo parvel");
    }
}
</code>```

It gives me the error:

```<code>Exception in thread "main" java.lang.NullPointerException
    at Introduction.main(Introduction.java:10)
/home/parvel/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds).
</code>```

please help

答:
java.io.Console object is null because there is no console attached to it.

Try to run from command line or attached console to it.

Find more details about it here: https://netbeans.org/bugzilla/show_bug.cgi?id=111337

Title: JAVA Console error

Body:
If i run this code below in Netbeans

import java.io.Console;
public class Introduction {
    public static void main(String[] args) {
        Console console= System.console();// creates a java Object which has method that allows us to write
        console.printf("Hallo parvel");
    }
}

It gives me the error:

Exception in thread "main" java.lang.NullPointerException
    at Introduction.main(Introduction.java:10)
/home/parvel/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds).

please help


问:
How to play an audio file sample
Okay I'm trying to do something similar to iTunes not sure if it's still the same. It's when you click a song and it gives a sample of the audio file. This is my code looks.

The music file is like 2-3min long. I got the start time to start at 42sec seconds. However, the song finishes to the end. I'm trying to make the audio file a sample of 30sec. So it should start at 42sec and end at 1min and 12sec.

Would appreciate any help thanks.

答:
Every time your audio sample starts playing, you can create a Timer object which will make your player stop in a given amount of time.

```<code>var audioPlayer = AVAudioPlayer()
var timer: Timer?

func prepareMusic() {
    ....

    // Your code to start playing sample

    audioPlayer.currentTime = 42
    audioPlayer.play()

    // Here we are stopping previous timer if there was any, and creating new one for 30 seconds. It will make player stop.

    timer?.invalidate()
    timer = Timer(fire: Date.init(timeIntervalSinceNow: 30), interval: 0, repeats: false) { (timer) in
        if self.audioPlayer.isPlaying {
            self.audioPlayer.stop()
        }
    }

    RunLoop.main.add(timer!, forMode: .defaultRunLoopMode)
}

func musicButton(sender: UIButton) {
    ....

    // If sample is stopped by user — stop timer as well

    if audioPlayer.isPlaying {
        audioPlayer.stop()
        timer?.invalidate()
    }
}
</code>```

There is one more edge case I can think of — if you hide/close view controller, you might also want to stop that timer.

```<code>override func viewWillDisappear(_ animated: Bool) {
    timer?.invalidate()
}
</code>```

Title: How to play an audio file sample

Body:
Every time your audio sample starts playing, you can create a Timer object which will make your player stop in a given amount of time.

var audioPlayer = AVAudioPlayer()
var timer: Timer?

func prepareMusic() {
    ....

    // Your code to start playing sample

    audioPlayer.currentTime = 42
    audioPlayer.play()

    // Here we are stopping previous timer if there was any, and creating new one for 30 seconds. It will make player stop.

    timer?.invalidate()
    timer = Timer(fire: Date.init(timeIntervalSinceNow: 30), interval: 0, repeats: false) { (timer) in
        if self.audioPlayer.isPlaying {
            self.audioPlayer.stop()
        }
    }

    RunLoop.main.add(timer!, forMode: .defaultRunLoopMode)
}

func musicButton(sender: UIButton) {
    ....

    // If sample is stopped by user — stop timer as well

    if audioPlayer.isPlaying {
        audioPlayer.stop()
        timer?.invalidate()
    }
}

There is one more edge case I can think of — if you hide/close view controller, you might also want to stop that timer.

override func viewWillDisappear(_ animated: Bool) {
    timer?.invalidate()
}


问:
Angular JS - How to apply / bind ng-model late (lazy)
I have a simple scenario in a large piece of code:

Angular APP & Controller (all working well)

one ng-model element is dynamically created later (or lets say it comes from an ajax call). How to bind this into that controller?

For example:

```<code>var dtApp = angular.module('App1', []);
dtApp.controller('Cont1', function($scope)
{
  .
  .
  .
  .
  $scope.xyz='1';
}
.
.
.
//element created dynamically on click:
<input type="text" ng-model="xyz" />
.
</code>```

This is just an example, but it will solve the actual and larger problem if I know the solution.

Thanks a lot.

答:
if you want to manually add DOM element to DOM tree of the controller after it finishes binding & compiling phase, you will need to compile and bind the scope of the controller to the new DOM element yourself using $compile service : https://docs.angularjs.org/api/ng/service/$compile

```<code>var dtApp = angular.module('App1', []);
dtApp.controller('Cont1', function($scope, $compile)
{
   var parent_element_to_append = angular.element(YOUR_SELECTOR);
   var element = $compile("<input type="text" ng-model="xyz" />")($scope);
   parent_element_to_append.append(element);
}
</code>```

Body:
I have a simple scenario in a large piece of code:

Angular APP & Controller (all working well)

one ng-model element is dynamically created later (or lets say it comes from an ajax call). How to bind this into that controller?

For example:

var dtApp = angular.module('App1', []);
dtApp.controller('Cont1', function($scope)
{
  .
  .
  .
  .
  $scope.xyz='1';
}
.
.
.
//element created dynamically on click:
<input type="text" ng-model="xyz" />
.

This is just an example, but it will solve the actual and larger problem if I know the solution.

Thanks a lot.

Body:
if you want to manually add DOM element to DOM tree of the controller after it finishes binding & compiling phase, you will need to compile and bind the scope of the controller to the new DOM element yourself using $compile service : https://docs.angularjs.org/api/ng/service/$compile

var dtApp = angular.module('App1', []);
dtApp.controller('Cont1', function($scope, $compile)
{
   var parent_element_to_append = angular.element(YOUR_SELECTOR);
   var element = $compile("<input type="text" ng-model="xyz" />")($scope);
   parent_element_to_append.append(element);
}


问:
In C++ trying to write a newline after each operator overload cascade
this is a bit of a hard nut to crack. I'm writing a logging function that is trying to have a similar look to the std::cout

So basically the goal is to have the following code do as commented

```<code>   log << "text"; // This would output "text\n";
   log << "some " << "text"; //This would output "some text\n"
   log << "some number "<< 5; //This would output "some number 5\n"
</code>```

I've tried using variadic templates, but didn't get far.
Here's the most successful attempt so far:

```<code>#include <iostream>

// stream_newliner works by just taking the address of an ostream you
// give it, and forwarding all writes (via operator<<) to that ostream.
// Then, when it finally destructs, it writes the newline.
template <typename CharT, typename Traits>
class stream_newliner
{
public:
// The constructor just takes the address of the stream you give it.
explicit stream_newliner(std::basic_ostream<CharT, Traits>& s) :
    p_s_{&s}
{}

// Boilerplate move construction. Nothing special here.
stream_newliner(stream_newliner&& s) : p_s_{nullptr}
{
    *this = std::move(s);
}

// On destruction, write the newline. (Note we check the pointer for
// null for technical reasons.)
~stream_newliner()
{
    if (p_s_)
    {
        // If you have std::unhandled_exceptions(), you can check to
        // see if a new exception is in flight, and only do the
        // newline if there's not.

        // Note that I'm writing an X and not a newline so you can
        // see it easier.
        (*p_s_) << 'X';
    }
}

// This is where the magic happens. Any time you do "x << y" where
// x is this type, it just passes it on to the underlying stream.
// When you do "x << y1 << y2", it all works magically because it
// translates to "operator<<(operator<<(x, y1), y2)"... and this
// function just passes each call to the underlying stream.
template <typename T>
auto operator<<(T&& t) -> stream_newliner<CharT, Traits>&
{
    (*p_s_) << std::forward<T>(t);
    return *this;
}

// Boilerplate move assignment. Nothing special here.
auto operator=(stream_newliner&& s) -> stream_newliner&
{
    std::swap(p_s_, s.p_s_);
    return *this;
}

// Technically don't need these, but it doesn't hurt to be explicit.
stream_newliner(stream_newliner const&) = delete;
auto operator=(stream_newliner const&) = delete;

   private:
// You could use a reference to the stream rather than a pointer,
// but references are harder to work with as class members.
std::basic_ostream<CharT, Traits>* p_s_ = nullptr;
   };

   // Helper function to make it easier to create.
   template <typename CharT, typename Traits>
   auto line(std::basic_ostream<CharT, Traits>& s)
   {
return stream_newliner<CharT, Traits>{s};
   }

   auto main() -> int
   {
line(std::cout) << "foo";
std::cout << '\n';

line(std::cout) << 1 << ' ' << 2 << ' ' << 3;
std::cout << '\n';
   }
</code>```

答:
Someone posted this, and it sorta does the job.</p>

```<code>#include <iostream>
using namespace std;

struct Liner {
    bool Owned = true;
    Liner() = default;
    Liner(Liner &&O) { O.Owned = false; }
    ~Liner() { if (Owned) std::cout << '\n'; }
};

template <typename T>
const Liner &operator<<(const Liner &L, T &&E) {
    std::cout << std::forward<T>(E);
    return L;
}

struct SubLiner {
    operator Liner() const { return {}; }
};

const static SubLiner line;

int main() {
    line << "hello " << "world!";
    line << 1 << 2;
    line << 3;
    return 0;
}
</code>```

Body:
this is a bit of a hard nut to crack. I'm writing a logging function that is trying to have a similar look to the std::cout

So basically the goal is to have the following code do as commented

   log << "text"; // This would output "text\n";
   log << "some " << "text"; //This would output "some text\n"
   log << "some number "<< 5; //This would output "some number 5\n"

I've tried using variadic templates, but didn't get far.
Here's the most successful attempt so far:

#include <iostream>

// stream_newliner works by just taking the address of an ostream you
// give it, and forwarding all writes (via operator<<) to that ostream.
// Then, when it finally destructs, it writes the newline.
template <typename CharT, typename Traits>
class stream_newliner
{
public:
// The constructor just takes the address of the stream you give it.
explicit stream_newliner(std::basic_ostream<CharT, Traits>& s) :
    p_s_{&s}
{}

// Boilerplate move construction. Nothing special here.
stream_newliner(stream_newliner&& s) : p_s_{nullptr}
{
    *this = std::move(s);
}

// On destruction, write the newline. (Note we check the pointer for
// null for technical reasons.)
~stream_newliner()
{
    if (p_s_)
    {
        // If you have std::unhandled_exceptions(), you can check to
        // see if a new exception is in flight, and only do the
        // newline if there's not.

        // Note that I'm writing an X and not a newline so you can
        // see it easier.
        (*p_s_) << 'X';
    }
}

// This is where the magic happens. Any time you do "x << y" where
// x is this type, it just passes it on to the underlying stream.
// When you do "x << y1 << y2", it all works magically because it
// translates to "operator<<(operator<<(x, y1), y2)"... and this
// function just passes each call to the underlying stream.
template <typename T>
auto operator<<(T&& t) -> stream_newliner<CharT, Traits>&
{
    (*p_s_) << std::forward<T>(t);
    return *this;
}

// Boilerplate move assignment. Nothing special here.
auto operator=(stream_newliner&& s) -> stream_newliner&
{
    std::swap(p_s_, s.p_s_);
    return *this;
}

// Technically don't need these, but it doesn't hurt to be explicit.
stream_newliner(stream_newliner const&) = delete;
auto operator=(stream_newliner const&) = delete;

   private:
// You could use a reference to the stream rather than a pointer,
// but references are harder to work with as class members.
std::basic_ostream<CharT, Traits>* p_s_ = nullptr;
   };

   // Helper function to make it easier to create.
   template <typename CharT, typename Traits>
   auto line(std::basic_ostream<CharT, Traits>& s)
   {
return stream_newliner<CharT, Traits>{s};
   }

   auto main() -> int
   {
line(std::cout) << "foo";
std::cout << '\n';

line(std::cout) << 1 << ' ' << 2 << ' ' << 3;
std::cout << '\n';
   }

Body:
Someone posted this, and it sorta does the job.

#include <iostream>
using namespace std;

struct Liner {
    bool Owned = true;
    Liner() = default;
    Liner(Liner &&O) { O.Owned = false; }
    ~Liner() { if (Owned) std::cout << '\n'; }
};

template <typename T>
const Liner &operator<<(const Liner &L, T &&E) {
    std::cout << std::forward<T>(E);
    return L;
}

struct SubLiner {
    operator Liner() const { return {}; }
};

const static SubLiner line;

int main() {
    line << "hello " << "world!";
    line << 1 << 2;
    line << 3;
    return 0;
}


问:
Redirecting AWK output as input to GDB
I am doing a

```<code>ps | grep process_name | awk '{if ($2 == "process_name")  {print $1} }'
</code>```

which displays the process_id for the process name

After that I do a gdb -p process_id. I want to combine these two statements into a single statement. Any suggestions ?

```<code>ps | grep process_name | awk '{if ($2 == "process_name")  {print $1} }'
</code>```

Output : process_id

```<code>gdb -p process_id
</code>```

答:
No need for grep or awk or any other external commands. This is what pgrep is made for:

```<code>PID=$(pgrep process_name) && gdb -p $PID
</code>```

Title: Redirecting AWK output as input to GDB

Body:
I am doing a

ps | grep process_name | awk '{if ($2 == "process_name")  {print $1} }'

which displays the process_id for the process name

After that I do a gdb -p process_id. I want to combine these two statements into a single statement. Any suggestions ?

ps | grep process_name | awk '{if ($2 == "process_name")  {print $1} }'

Output : process_id

gdb -p process_id

Body:
No need for grep or awk or any other external commands. This is what pgrep is made for:

PID=$(pgrep process_name) && gdb -p $PID


问:
hdf to ndarray in numpy - fast way
I am looking for a fast way to set my collection of hdf files into a numpy array where each row is a flattened version of an image. What I exactly mean:

My hdf files store, beside other informations, images per frames. Each file holds 51 frames with 512x424 images. Now I have 300+ hdf files and I want the image pixels to be stored as one single vector per frame, where all frames of all images are stored in one numpy ndarray. The following picture should help to understand:

What I got so far is a very slow method, and I actually have no idea how i can make it faster. The problem is that my final array is called too often, as far as I think. Since I observe that the first files are loaded into the array very fast but speed decreases fast. (observed by printing the number of the current hdf file)

My current code:

```<code>os.chdir(os.getcwd()+"\\datasets")

# predefine first row to use vstack later
numpy_data = np.ndarray((1,217088))

# search for all .hdf files
for idx, file in enumerate(glob.glob("*.hdf5")):
  f = h5py.File(file, 'r')
  # load all img data to imgs (=ndarray, but not flattened)
  imgs = f['img']['data'][:]

  # iterate over all frames (50)
  for frame in range(0, imgs.shape[0]):
    print("processing {}/{} (file/frame)".format(idx+1,frame+1))
    data = np.array(imgs[frame].flatten())
    numpy_data = np.vstack((numpy_data, data))

    # delete first row after another is one is stored
    if idx == 0 and frame == 0:
        numpy_data = np.delete(numpy_data, 0,0)

f.close()
</code>```

For further information, I need this for learning a decision tree. Since my hdf file is bigger than my RAM, I think converting into a numpy array save memory and is therefore better suited.

Thanks for every input.

答:
Do you really wan't to load all Images into the RAM and not use a single HDF5-File instead? Accessing a HDF5-File can be quite fast if you don't make any mistakes (unnessesary fancy indexing, improper chunk-chache-size).
If you wan't the numpy-way this would be a possibility:

```<code>os.chdir(os.getcwd()+"\\datasets")
img_per_file=51

# get all HDF5-Files
files=[]
for idx, file in enumerate(glob.glob("*.hdf5")):
    files.append(file)

# allocate memory for your final Array (change the datatype if your images have some other type)
numpy_data=np.empty((len(files)*img_per_file,217088),dtype=np.uint8)

# Now read all the data
ii=0
for i in range(0,len(files)):
    f = h5py.File(files[0], 'r')
    imgs = f['img']['data'][:]
    f.close()
    numpy_data[ii:ii+img_per_file,:]=imgs.reshape((img_per_file,217088))
    ii=ii+img_per_file
</code>```

Writing your data to a single HDF5-File would be quite similar:

```<code>f_out=h5py.File(File_Name_HDF5_out,'w')
# create the dataset (change the datatype if your images have some other type)
dset_out = f_out.create_dataset(Dataset_Name_out, ((len(files)*img_per_file,217088), chunks=(1,217088),dtype='uint8')

# Now read all the data
ii=0
for i in range(0,len(files)):
    f = h5py.File(files[0], 'r')
    imgs = f['img']['data'][:]
    f.close()
    dset_out[ii:ii+img_per_file,:]=imgs.reshape((img_per_file,217088))
    ii=ii+img_per_file

f_out.close()
</code>```

If you only wan't to access whole images afterwards the chunk-size should be okay. If not you have to change that to your needs.

What you should do when accessing a HDF5-File:

Use a chunk-size, which fits your needs.

Set a proper chunk-chache-size. This can be done with the h5py low level api or h5py_cache. https://pypi.python.org/pypi/h5py-cache/1.0

Avoid any type of fancy indexing. If your Dataset has n dimensions access it in a way that the returned Array has also n dimensions.

```<code># Chunk size is [50,50] and we iterate over the first dimension
numpyArray=h5_dset[i,:] #slow
numpyArray=np.squeeze(h5_dset[i:i+1,:]) #does the same but is much faster
</code>```

EDIT
This shows how to read your data to a memmaped numpy array. I think your method expects data of format np.float32.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html#numpy.memmap

```<code> numpy_data = np.memmap('Your_Data.npy', dtype='np.float32', mode='w+', shape=((len(files)*img_per_file,217088)))
</code>```

Everything else could be kept the same. If it works I would also recommend to use a SSD instead of a hardisk.

Title: hdf to ndarray in numpy - fast way

Body:
I am looking for a fast way to set my collection of hdf files into a numpy array where each row is a flattened version of an image. What I exactly mean:

My hdf files store, beside other informations, images per frames. Each file holds 51 frames with 512x424 images. Now I have 300+ hdf files and I want the image pixels to be stored as one single vector per frame, where all frames of all images are stored in one numpy ndarray. The following picture should help to understand:

What I got so far is a very slow method, and I actually have no idea how i can make it faster. The problem is that my final array is called too often, as far as I think. Since I observe that the first files are loaded into the array very fast but speed decreases fast. (observed by printing the number of the current hdf file)

My current code:

os.chdir(os.getcwd()+"\\datasets")

# predefine first row to use vstack later
numpy_data = np.ndarray((1,217088))

# search for all .hdf files
for idx, file in enumerate(glob.glob("*.hdf5")):
  f = h5py.File(file, 'r')
  # load all img data to imgs (=ndarray, but not flattened)
  imgs = f['img']['data'][:]

  # iterate over all frames (50)
  for frame in range(0, imgs.shape[0]):
    print("processing {}/{} (file/frame)".format(idx+1,frame+1))
    data = np.array(imgs[frame].flatten())
    numpy_data = np.vstack((numpy_data, data))

    # delete first row after another is one is stored
    if idx == 0 and frame == 0:
        numpy_data = np.delete(numpy_data, 0,0)

f.close()

For further information, I need this for learning a decision tree. Since my hdf file is bigger than my RAM, I think converting into a numpy array save memory and is therefore better suited.

Thanks for every input.

Body:
Do you really wan't to load all Images into the RAM and not use a single HDF5-File instead? Accessing a HDF5-File can be quite fast if you don't make any mistakes (unnessesary fancy indexing, improper chunk-chache-size).
If you wan't the numpy-way this would be a possibility:

os.chdir(os.getcwd()+"\\datasets")
img_per_file=51

# get all HDF5-Files
files=[]
for idx, file in enumerate(glob.glob("*.hdf5")):
    files.append(file)

# allocate memory for your final Array (change the datatype if your images have some other type)
numpy_data=np.empty((len(files)*img_per_file,217088),dtype=np.uint8)

# Now read all the data
ii=0
for i in range(0,len(files)):
    f = h5py.File(files[0], 'r')
    imgs = f['img']['data'][:]
    f.close()
    numpy_data[ii:ii+img_per_file,:]=imgs.reshape((img_per_file,217088))
    ii=ii+img_per_file

Writing your data to a single HDF5-File would be quite similar:

f_out=h5py.File(File_Name_HDF5_out,'w')
# create the dataset (change the datatype if your images have some other type)
dset_out = f_out.create_dataset(Dataset_Name_out, ((len(files)*img_per_file,217088), chunks=(1,217088),dtype='uint8')

# Now read all the data
ii=0
for i in range(0,len(files)):
    f = h5py.File(files[0], 'r')
    imgs = f['img']['data'][:]
    f.close()
    dset_out[ii:ii+img_per_file,:]=imgs.reshape((img_per_file,217088))
    ii=ii+img_per_file

f_out.close()

If you only wan't to access whole images afterwards the chunk-size should be okay. If not you have to change that to your needs.

What you should do when accessing a HDF5-File:

Use a chunk-size, which fits your needs.

Set a proper chunk-chache-size. This can be done with the h5py low level api or h5py_cache. https://pypi.python.org/pypi/h5py-cache/1.0

Avoid any type of fancy indexing. If your Dataset has n dimensions access it in a way that the returned Array has also n dimensions.

# Chunk size is [50,50] and we iterate over the first dimension
numpyArray=h5_dset[i,:] #slow
numpyArray=np.squeeze(h5_dset[i:i+1,:]) #does the same but is much faster

EDIT
This shows how to read your data to a memmaped numpy array. I think your method expects data of format np.float32.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html#numpy.memmap

 numpy_data = np.memmap('Your_Data.npy', dtype='np.float32', mode='w+', shape=((len(files)*img_per_file,217088)))

Everything else could be kept the same. If it works I would also recommend to use a SSD instead of a hardisk.


问:
richfaces contextmenu onclick not working
I have the following:

```<code><h:panelGroup id="picture">
<h:graphicImage id="pic" library="image" name="image.png" />
<rich:contextMenu event="onclick" attachTo="pic">
   <rich:menuItem value="Zoom In" id="zin">Zoom In</rich:menuItem>
</rich:contextMenu>
</h:panelGroup>
</code>```

Originally the event was oncontextmenu, and that works fine. But when I change it to onclick, it still responds to right click instead of left.

I already tried doing showEvent="onclick" to no avail:

```<code><h:panelGroup id="picture">
<h:graphicImage id="pic" library="image" name="image.png" />
<rich:contextMenu showEvent="onclick" event="onclick" attachTo="pic">
   <rich:menuItem value="Zoom In" id="zin">Zoom In</rich:menuItem>
</rich:contextMenu>
</h:panelGroup>
</code>```

I am not sure which Richfaces version I'm running. But it does work with right click, not with left click as I need.

Thank you in advance.

答: I changed the value of showEvent from "onclick" to "click" and it worked. </p>

Body:
I have the following:

<h:panelGroup id="picture">
<h:graphicImage id="pic" library="image" name="image.png" />
<rich:contextMenu event="onclick" attachTo="pic">
   <rich:menuItem value="Zoom In" id="zin">Zoom In</rich:menuItem>
</rich:contextMenu>
</h:panelGroup>

Originally the event was oncontextmenu, and that works fine. But when I change it to onclick, it still responds to right click instead of left.

I already tried doing showEvent="onclick" to no avail:

<h:panelGroup id="picture">
<h:graphicImage id="pic" library="image" name="image.png" />
<rich:contextMenu showEvent="onclick" event="onclick" attachTo="pic">
   <rich:menuItem value="Zoom In" id="zin">Zoom In</rich:menuItem>
</rich:contextMenu>
</h:panelGroup>

I am not sure which Richfaces version I'm running. But it does work with right click, not with left click as I need.

Thank you in advance.


问:
Not returning Set-Cookie parameter when using HttpWebResponse
The following code:

```<code>string url = "https://accounts.spotify.com/en/login";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.CookieContainer = new CookieContainer();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    string source = sr.ReadToEnd();
    MessageBox.Show(source);
    MessageBox.Show(resp.Cookies.Count.ToString());

    foreach (Cookie cookie in resp.Cookies)
    {
        MessageBox.Show(cookie.Name, cookie.Value);
    }
}
</code>```

Is meant to make a Message Box for each cookie with the name and value.

But it doesn't! not a single value gets returned.

Instead it does the following:

Shows the Source, the amount of Cookies (Shows 0) and then nothing else just a brief 1-2 seconds before the form loads.

It should respond with csrf_token=<...>

As you can see, even in the Fiddler response you can see the cookies.

答:
I am not sure why resp.Cookies no having any cookies in it. But if you observe resp.Headers has one value Set-Cookie. You can use that to retrieve cookies coming in the response.

Use following line of code to get the cookie header.

```<code>var cookieHeader = resp.Headers["Set-Cookie"];
</code>```

This will give you value like

```<code>csrf_token={sometokenvalue};Version=1;Domain=accounts.spotify.com;Path=/;Secure
</code>```

Body:
The following code:

string url = "https://accounts.spotify.com/en/login";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.CookieContainer = new CookieContainer();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    string source = sr.ReadToEnd();
    MessageBox.Show(source);
    MessageBox.Show(resp.Cookies.Count.ToString());

    foreach (Cookie cookie in resp.Cookies)
    {
        MessageBox.Show(cookie.Name, cookie.Value);
    }
}

Is meant to make a Message Box for each cookie with the name and value.

But it doesn't! not a single value gets returned.

Instead it does the following:

Shows the Source, the amount of Cookies (Shows 0) and then nothing else just a brief 1-2 seconds before the form loads.

It should respond with csrf_token=<...>

As you can see, even in the Fiddler response you can see the cookies.

Body:
I am not sure why resp.Cookies no having any cookies in it. But if you observe resp.Headers has one value Set-Cookie. You can use that to retrieve cookies coming in the response.

Use following line of code to get the cookie header.

var cookieHeader = resp.Headers["Set-Cookie"];

This will give you value like

csrf_token={sometokenvalue};Version=1;Domain=accounts.spotify.com;Path=/;Secure


问:
Concatenation in between records in Access Query
I have a table in Access that lists property IDs and the years each were certified:

```<code>B_ID    CertYear
a   2016
b   2016
c   2015
a   2015
a   2014
</code>```

I want to create a query/table that will count the number of years each building has been certified and also list each year in separate columns to look like this:

```<code>B_ID    Count_CertYear  Detail_CertYear
a   3   2016|2015|2014
b   1   2016
c   1   2015
</code>```

In the query design I was able to calculate the first two columns but am unable to figure out how to do the third. Here is how I currently have the table laid out.

```<code>Field:  B_ID    B_ID
Table:  MyTable MyTable
Total:  Count   Count
Sort:
Show:
Criteria:
Or:
</code>```

答:
Access does come with a set of domain aggregation functions, Count(), Sum(), Avg(), First(), Last(), Min(), Max(), StDev(), StDevP(), Var(), and VarP(), however, there is no native domain concatenation function.

My preference would be to handle this in SQL server and return the results via stored procedure, but if you're limited to Access, then using Patrick Matthews' domain concatenation function here is your best bet.

From the documentation of DConcat():

```<code>SELECT DConcat("Account","Sample") AS Accounts
FROM Sample
GROUP BY DConcat("Account","Sample");

Returns:
Accounts
-----------------------------------------------------------------------------
Acct1, Acct10, Acct2, Acct3, Acct4, Acct5, Acct6, Acct7, Acct8, Acct9
</code>```

For the specific example in your question:

```<code>SELECT B_ID
     , COUNT(Cert_Year)
     , DConcat("CertYear","MyTable", "B_ID='" & [B_ID] & "'") AS Detail_CertYear
FROM MyTable
GROUP BY B_ID
</code>```

Should return these values:

```<code>B_ID Count_CertYear Detail_CertYear
------------------------------
a    3              2016,2015,2014
b    1              2016
c    1              2015
</code>```

Body:
I have a table in Access that lists property IDs and the years each were certified:

B_ID    CertYear
a   2016
b   2016
c   2015
a   2015
a   2014

I want to create a query/table that will count the number of years each building has been certified and also list each year in separate columns to look like this:

B_ID    Count_CertYear  Detail_CertYear
a   3   2016|2015|2014
b   1   2016
c   1   2015

In the query design I was able to calculate the first two columns but am unable to figure out how to do the third. Here is how I currently have the table laid out.

Field:  B_ID    B_ID
Table:  MyTable MyTable
Total:  Count   Count
Sort:
Show:
Criteria:
Or:

Body:
Access does come with a set of domain aggregation functions, Count(), Sum(), Avg(), First(), Last(), Min(), Max(), StDev(), StDevP(), Var(), and VarP(), however, there is no native domain concatenation function.

My preference would be to handle this in SQL server and return the results via stored procedure, but if you're limited to Access, then using Patrick Matthews' domain concatenation function here is your best bet.

From the documentation of DConcat():

SELECT DConcat("Account","Sample") AS Accounts
FROM Sample
GROUP BY DConcat("Account","Sample");

Returns:
Accounts
-----------------------------------------------------------------------------
Acct1, Acct10, Acct2, Acct3, Acct4, Acct5, Acct6, Acct7, Acct8, Acct9

For the specific example in your question:

SELECT B_ID
     , COUNT(Cert_Year)
     , DConcat("CertYear","MyTable", "B_ID='" & [B_ID] & "'") AS Detail_CertYear
FROM MyTable
GROUP BY B_ID

Should return these values:

B_ID Count_CertYear Detail_CertYear
------------------------------
a    3              2016,2015,2014
b    1              2016
c    1              2015


问:
How to get the subdomain value from a url?
how can I get the subdomain value in rails, is there a built-in way to do this?

e.g.

```<code>test123.example.com
</code>```

I want the test123 part of the url.

答:
Rails 3.0 has this capability built-in, you can access the subdomain from request.subdomain.

You can also route based on the subdomain:

```<code>class SupportSubdomain
  def self.matches?(request)
    request.subdomain == "support"
  end
end

Basecamp::Application.routes do
  constraints(SupportSubdomain) do
    match "/foo/bar", :to => "foo#bar"
  end
end
</code>```

If you're using 2.3, you'll need to use a plugin such as subdomain-fu.

Body:
how can I get the subdomain value in rails, is there a built-in way to do this?

e.g.

test123.example.com

I want the test123 part of the url.

Body:
Rails 3.0 has this capability built-in, you can access the subdomain from request.subdomain.

You can also route based on the subdomain:

class SupportSubdomain
  def self.matches?(request)
    request.subdomain == "support"
  end
end

Basecamp::Application.routes do
  constraints(SupportSubdomain) do
    match "/foo/bar", :to => "foo#bar"
  end
end

If you're using 2.3, you'll need to use a plugin such as subdomain-fu.


问:
How can I see whether the Scan Credit Card feature is working in safari in iOS Simulator
I am trying to change a form that includes credit card input details so that when viewed on iOS it will give the user the option of scanning their credit card details (see below):

However, the solution I think should work (see here) isn't showing the scan card option when I open the page in safari on XCode iOS Simulator so I want to know:

Should I expect the Simulator to work exactly like an actual device (I know some camera based things do not work)?

If so, what steps I need to take in order to get it working?

If not possible, what alternative routes might there be to testing whether the scan card feature is working for my form.

答:
The Simulator does not currently provide a virtual camera. </p>

<p>If this is something you'd like to see, please file a bug report at https://bugreport.apple.com and request camera support be added to the Simulator. </p>

Body:
The Simulator does not currently provide a virtual camera.

If this is something you'd like to see, please file a bug report at https://bugreport.apple.com and request camera support be added to the Simulator.


问:
Google Chrome V 57.0 unable to input text when used with Robot Framework & throws error
I am using Robot Framework for test automation.
Recently I upgraded my Chrome browser to the latest version, V 57.0
Since then, I am unable to execute my test scripts on Chrome.
The webpage opens up and navigates until Login page, the cursor focus is set on Username field and then it just keeps on trying for few seconds until i receive an error saying:

```<code> [ WARN ] Keyword 'Capture Page Screenshot' could not be run on
   failure: WebDriverException: Message: unknown error: cannot get
   automation extension from unknown error: page could not be found:
   chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
   (Session info: chrome=57.0.2987.133)   (Driver info:
   chromedriver=2.24.417431
   (9aea000394714d2fbb20850021f6204f2256b9cf),platform=Windows NT
   10.0.10586 x86_64)
</code>```

I have no extensions installed in the browser.

Also followed up a similar post here
It just mentions about removing your extensions, which I already did.

Thanks

答:
EDIT: Always make certain you are using current and compatible versions of Chromedriver.  I always suspect this when the problems show up at the element level.  The driver has to be updated a lot as the browser evolves.  In your case, you've indicated a current Chromedriver is a solution.  Note that this solution generalizes to all browsers.

If the problem were more related to window sizing/resizing, it might be due to the fact that selenium is trying to use an extension to perform a windowing function.  Issues with running headless...  This assumes you are running headless.

Solution is likely to rework the test for headless runs, or run else try a real browser.

Body:
I am using Robot Framework for test automation.
Recently I upgraded my Chrome browser to the latest version, V 57.0
Since then, I am unable to execute my test scripts on Chrome.
The webpage opens up and navigates until Login page, the cursor focus is set on Username field and then it just keeps on trying for few seconds until i receive an error saying:

 [ WARN ] Keyword 'Capture Page Screenshot' could not be run on
   failure: WebDriverException: Message: unknown error: cannot get
   automation extension from unknown error: page could not be found:
   chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
   (Session info: chrome=57.0.2987.133)   (Driver info:
   chromedriver=2.24.417431
   (9aea000394714d2fbb20850021f6204f2256b9cf),platform=Windows NT
   10.0.10586 x86_64)

I have no extensions installed in the browser.

Also followed up a similar post here
It just mentions about removing your extensions, which I already did.

Thanks


问:
Error handling on GoTo Bookmark if bookmark doesn't exist
I'm working on a macro to copy and paste bookmarked tables from one word document to another. It works fine as long as the value I put in the input box matches an existing bookmark, but if I mistype the value, it simply pulls in the top table from my source document. I understand why it does that (because it selects table 1 if it doesn't find a bookmark), but I can't figure out how to fix it. I tried putting in error handling, but since it doesn't trigger an error, what I added doesn't work. Can someone show me how to edit the code below to fix this issue? Also, is there a way to use relative pathways for the source document and target document? They will always be in the same folder, but each different user will have a copy of them in their own folder, and I don't want to rewrite the macro every time. Any other improvements or edits would be appreciated, such as how to not use the selection event so much here. Or how to not reopen the documents if they are already open. The command button (and code) is in the Target document (Product.docm)</p>

```<code>Private Sub CommandButton2_Click()

' Copy table from source document and add to table in target document

  Dim oTarDoc As Document, oSourceDoc As Document
  Dim oTable As Table
  Dim oNewRow As Row

    Set oSourceDoc = Documents.Open("H:\Test Documents\Tables.docx")
    Set oTarDoc = Documents.Open("H:\Test Documents\Product.docm")

    Application.ScreenUpdating = False

    oTarDoc.Activate
    Set oTable = oTarDoc.Tables(2)
    Set oNewRow = oTable.Rows(oTable.Rows.Count - 3)

    oSourceDoc.Activate
    Selection.GoTo What:=wdGoToBookmark, Name:="A" & InputBox("119f, 979, 981a...", "Enter Number and Letter as Shown")
    With oSourceDoc.Bookmarks
        .DefaultSorting = wdSortByName
        .ShowHidden = False
    End With
    Selection.Tables(1).Select
    Selection.Copy

    oTarDoc.Activate
    oNewRow.Select
    Selection.Paste
       Application.ScreenUpdating = True    End Sub
</code>```

答:
You could do something like this:

```<code>Dim bm As Word.Bookmark
Dim bm_name As String
.
.
bm_name = "A" & InputBox("119f, 979, 981a...", "Enter Number and Letter as Shown")
' TODO: if user hits Cancel, bm_name = "", need to trap with If bm_name=""
On Error Resume Next
Set bm = oSourceDoc.Bookmarks(bm_name)
If Err.Number = 0 Then
    bm.Select
    Selection.Tables(1).Select
    Selection.Copy
    ' Paste-to-target code goes here

Else
    Err.Clear
    MsgBox "Didn't find " bm_name, vbOKOnly, "Not found"
End If
</code>```

Hope that helps

Body:
I'm working on a macro to copy and paste bookmarked tables from one word document to another. It works fine as long as the value I put in the input box matches an existing bookmark, but if I mistype the value, it simply pulls in the top table from my source document. I understand why it does that (because it selects table 1 if it doesn't find a bookmark), but I can't figure out how to fix it. I tried putting in error handling, but since it doesn't trigger an error, what I added doesn't work. Can someone show me how to edit the code below to fix this issue? Also, is there a way to use relative pathways for the source document and target document? They will always be in the same folder, but each different user will have a copy of them in their own folder, and I don't want to rewrite the macro every time. Any other improvements or edits would be appreciated, such as how to not use the selection event so much here. Or how to not reopen the documents if they are already open. The command button (and code) is in the Target document (Product.docm)

Private Sub CommandButton2_Click()

' Copy table from source document and add to table in target document

  Dim oTarDoc As Document, oSourceDoc As Document
  Dim oTable As Table
  Dim oNewRow As Row

    Set oSourceDoc = Documents.Open("H:\Test Documents\Tables.docx")
    Set oTarDoc = Documents.Open("H:\Test Documents\Product.docm")

    Application.ScreenUpdating = False

    oTarDoc.Activate
    Set oTable = oTarDoc.Tables(2)
    Set oNewRow = oTable.Rows(oTable.Rows.Count - 3)

    oSourceDoc.Activate
    Selection.GoTo What:=wdGoToBookmark, Name:="A" & InputBox("119f, 979, 981a...", "Enter Number and Letter as Shown")
    With oSourceDoc.Bookmarks
        .DefaultSorting = wdSortByName
        .ShowHidden = False
    End With
    Selection.Tables(1).Select
    Selection.Copy

    oTarDoc.Activate
    oNewRow.Select
    Selection.Paste
       Application.ScreenUpdating = True    End Sub

Body:
You could do something like this:

Dim bm As Word.Bookmark
Dim bm_name As String
.
.
bm_name = "A" & InputBox("119f, 979, 981a...", "Enter Number and Letter as Shown")
' TODO: if user hits Cancel, bm_name = "", need to trap with If bm_name=""
On Error Resume Next
Set bm = oSourceDoc.Bookmarks(bm_name)
If Err.Number = 0 Then
    bm.Select
    Selection.Tables(1).Select
    Selection.Copy
    ' Paste-to-target code goes here

Else
    Err.Clear
    MsgBox "Didn't find " bm_name, vbOKOnly, "Not found"
End If

Hope that helps


问:
Session Window preventing GroupByKey from working
I have an incoming stream of events, each of which already has an associated sessionId from another process.

All I wish to do is combine these events into a single session object using a custom CombineFn.

During development, I'm using a bounded dataset that reads from a file and the following code seems to work:

```<code>input.apply(ParDo.named("ParseEvent").of(new ParseEventFn()))
    .setCoder(KvCoder.of(StringUtf8Coder.of(), AvroCoder.of(Event.class)))
    .apply(GroupByKey.<String, Event>create())
    .apply(Combine.groupedValues(new SessionAccumulator()))
</code>```

The above code (with input/output handling) will output a series of sessions with multiple events in each.

```<code>{sessionId: 1, events: [event1,event2,event3]}
{sessionId: 2, events: [event4,event5]}
</code>```

But in order for this to work on an unbounded dataset, I need to apply a Windowing function, which in this case is a SessionWindow.

```<code>input.apply(ParDo.named("ParseEvent").of(new ParseEventFn()))
    .setCoder(KvCoder.of(StringUtf8Coder.of(), AvroCoder.of(Event.class)))
    .apply(Window.<KV<String, Event>>into(Sessions.withGapDuration(Duration.standardMinutes(30))))
    .apply(GroupByKey.<String, Event>create())
    .apply(Combine.groupedValues(new SessionAccumulator()))
</code>```

In that case the only new code is the Windowing function, and rather than rolling up the events, I get each event in it's own session, like this:

```<code>{sessionId: 1, events: [event1]}
{sessionId: 1, events: [event2]}
{sessionId: 1, events: [event3]}
{sessionId: 2, events: [event4]}
{sessionId: 2, events: [event5]}
</code>```

Any idea why this is happening?

EDIT: I should add, the ParseEventFn is applying a timestamp to the PCollection using context.outputWithTimestamp(), and that timestamp seems to be correct.

答:
Digging into it further, in my case the issue was that my core assumption that the timestamps were correct, was wrong.

The timestamps I was applying before the windowing were wrong.

The Windowing was doing exactly what it should, but I had set my timestamps too far apart and it was creating separate sessions for each event.

Oops

Body:
I have an incoming stream of events, each of which already has an associated sessionId from another process.

All I wish to do is combine these events into a single session object using a custom CombineFn.

During development, I'm using a bounded dataset that reads from a file and the following code seems to work:

input.apply(ParDo.named("ParseEvent").of(new ParseEventFn()))
    .setCoder(KvCoder.of(StringUtf8Coder.of(), AvroCoder.of(Event.class)))
    .apply(GroupByKey.<String, Event>create())
    .apply(Combine.groupedValues(new SessionAccumulator()))

The above code (with input/output handling) will output a series of sessions with multiple events in each.

{sessionId: 1, events: [event1,event2,event3]}
{sessionId: 2, events: [event4,event5]}

But in order for this to work on an unbounded dataset, I need to apply a Windowing function, which in this case is a SessionWindow.

input.apply(ParDo.named("ParseEvent").of(new ParseEventFn()))
    .setCoder(KvCoder.of(StringUtf8Coder.of(), AvroCoder.of(Event.class)))
    .apply(Window.<KV<String, Event>>into(Sessions.withGapDuration(Duration.standardMinutes(30))))
    .apply(GroupByKey.<String, Event>create())
    .apply(Combine.groupedValues(new SessionAccumulator()))

In that case the only new code is the Windowing function, and rather than rolling up the events, I get each event in it's own session, like this:

{sessionId: 1, events: [event1]}
{sessionId: 1, events: [event2]}
{sessionId: 1, events: [event3]}
{sessionId: 2, events: [event4]}
{sessionId: 2, events: [event5]}

Any idea why this is happening?

EDIT: I should add, the ParseEventFn is applying a timestamp to the PCollection using context.outputWithTimestamp(), and that timestamp seems to be correct.


问:
quick loading of a drools knowledge base
I'm trying to use Drools as the rule engine for a grammar relations to semantics mapping framework. The rule base is in excess of 5000 rules even now and will get extended. In using Drools currently the reading of the drl file containing the rules and creating the knowledge base takes a lot of time each time the program is run. Is there a way create the knowledge base once and save it in some persistent format that can be quickly loaded with the option to regenerate the knowledge base only when a change is made? </p>

答:
Yes, drools can serialise a knowledgebase out to external storage and then load this serialised knowledgebase back in again.

So, you need a cycle that loads from drl, compiles, serialises out.  Then a second cycle that uses the serialised version.

I've used this with some success, reducing a 1 minute 30 loading time down to about 15-20 seconds.   Also, it reduces your heap/perm gen requirements as well.

Check the API for the exact methods.


问:
UE4 - Removing Text When Exiting TriggerBox
Having some trouble getting text to disappear when I exit the trigger box from reading the note. I can easily display the text I want but I am unsure how I can make it disappear when I leave the triggerbox. Blueprint included, any help is appreciated.

答:
Connect GetPlayerController to Create Widget?

Also store the created widget as a variable. It's likely that the widget reference is being lost once the E input event is finished, so the RemoveFromParent node doesn't know what to remove.

For widgets that you're going to use all the time, pre-create them and store them as variables. Much easier to maintain in the long run.


问:
Google places - GMSAutocompleteViewController didAutocompleteWith full text
This is the delegate function in my viewController :

```<code>func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
        print("Place name: \(place.name)")
        print("Place address: \(place.formattedAddress)")

        dismiss(animated: true, completion: nil)
    }
</code>```

I searched for "Grav Skole" and selected the first option here :

Following are the logs :

Place name: Grav skole

  Place address: "Hosleveien 24, 1358 Jar,
  Norway"

On Android, the result is displayed as "Grav skole, Hosleveien, Jar, Norway", which is the desired text and does not match with the iOS.

What am I missing ?

答:
It sounds like you want to access the text of the predictions as they are displayed in the list by GMSAutocompleteViewController. You can do this by implementing the viewController:didSelectPrediction method of GMSAutocompleteViewControllerDelegate, which will be called when an item is selected.

```<code>func viewController(_ viewController: GMSAutocompleteViewController,
didSelectPrediction prediction: GMSAutocompletePrediction) -> Bool {
    print("Primary: \(prediction.attributedPrimaryText)")
    print("Secondary: \(prediction.attributedSecondaryText)")
    return false;
}
</code>```

Body:
This is the delegate function in my viewController :

func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
        print("Place name: \(place.name)")
        print("Place address: \(place.formattedAddress)")

        dismiss(animated: true, completion: nil)
    }

I searched for "Grav Skole" and selected the first option here :

Following are the logs :

Place name: Grav skole

  Place address: "Hosleveien 24, 1358 Jar,
  Norway"

On Android, the result is displayed as "Grav skole, Hosleveien, Jar, Norway", which is the desired text and does not match with the iOS.

What am I missing ?

Body:
It sounds like you want to access the text of the predictions as they are displayed in the list by GMSAutocompleteViewController. You can do this by implementing the viewController:didSelectPrediction method of GMSAutocompleteViewControllerDelegate, which will be called when an item is selected.

func viewController(_ viewController: GMSAutocompleteViewController,
didSelectPrediction prediction: GMSAutocompletePrediction) -> Bool {
    print("Primary: \(prediction.attributedPrimaryText)")
    print("Secondary: \(prediction.attributedSecondaryText)")
    return false;
}


问:
Kafka console producer does not fail if broker address is incorrect
I run the following command (where <incorrect port> is a number):

```<code>bin/kafka-console-producer.sh --broker-list localhost:<incorrect port> --topic some-topic
</code>```

And the process doesnt fail, it continues as if nothing is wrong

Is there a way upon startup of kafka-console-producer.sh  to check the destination broker port has a broker listening to that port upon startup?

I'm using kafka 0.10.2.0 on osx 10.12.3

答: That's by design... The producer just assumes, that the broker will get available at the specified port eventually. However, the producer should time out at some point (IIRC the default is 5 minutes). You can reduce the timeout config to get the error earlier via request.timeout.ms or metadata.fetch.timeout.ms.

Body:
I run the following command (where <incorrect port> is a number):

bin/kafka-console-producer.sh --broker-list localhost:<incorrect port> --topic some-topic

And the process doesnt fail, it continues as if nothing is wrong

Is there a way upon startup of kafka-console-producer.sh  to check the destination broker port has a broker listening to that port upon startup?

I'm using kafka 0.10.2.0 on osx 10.12.3


答: Why don't you just play with element visibility instead of generating it ng-show/ng-hide/ng-if. If the request is outside the controller's visibility you can trigger an event and listen to it and then make the element visible. This way the you will have the element from the beginning it just won't be visible but ng-model will bind your property. This won't work only if you don't know what element will be generated (if there are a lot of possibilities), but if there are a small number you can add all of them and only make the one you want visible.

Title: Angular JS - How to apply / bind ng-model late (lazy)

Body:
I have a simple scenario in a large piece of code:

Angular APP & Controller (all working well)

one ng-model element is dynamically created later (or lets say it comes from an ajax call). How to bind this into that controller?

For example:

var dtApp = angular.module('App1', []);
dtApp.controller('Cont1', function($scope)
{
  .
  .
  .
  .
  $scope.xyz='1';
}
.
.
.
//element created dynamically on click:
<input type="text" ng-model="xyz" />
.

This is just an example, but it will solve the actual and larger problem if I know the solution.

Thanks a lot.


问:
How to array of int transform into 2d array of binary value of every array number?
Hi i'm trying to find binary value of every element of array and to set it in 2d array.
Here is my code:

```<code>#include <iostream>

void tobin(int a,int b[]);

int main()
{
    int i,j;
    int b[8];//bin array
    int d[3][8]; //2d array
    int c[3] = {6,15,24}; //int array

    //My code for transformation from array to 2d array
    for(i=0;i<3;i++)
        {
            tobin(c[i],b);
            for(j=0;j<8;j++)
            {
                d[i][j]=b[j];

            }
        }

    //Printing of 2d array
    for(i=0;i<8;i++)
        {
            for(j=0;j<8;j++)
                std::cout<<d[i][j];
            std::cout<<std::endl;
        }
}

//Function for convert int to bin
void tobin(int a,int b[])
{
    int i;
    for(i=0;i<8;i++)
    {
        b[i]=a%2;
        a/=2;
    }
}
</code>```

And here my output:

```<code>01100000
11110000
00011000
00-16437331793270200193648149632765
014196397000-640061051-1985511146
419616001936481488327650000
16416403251985832910-46743922719940467470000
004196848019364814963276510
</code>```

First 3 lines is what i was looking for, but i don't know what is the rest.
Can someone help me to fix this. And to give me explanation why is this happening or link to explanation.

答: Your last for-loop (the one that prints) should only have i<3 as its condition.  Right now i is allowed to go to 7, but then d[i][j] is out of bounds and prints garbage.

Body:
Hi i'm trying to find binary value of every element of array and to set it in 2d array.
Here is my code:

#include <iostream>

void tobin(int a,int b[]);

int main()
{
    int i,j;
    int b[8];//bin array
    int d[3][8]; //2d array
    int c[3] = {6,15,24}; //int array

    //My code for transformation from array to 2d array
    for(i=0;i<3;i++)
        {
            tobin(c[i],b);
            for(j=0;j<8;j++)
            {
                d[i][j]=b[j];

            }
        }

    //Printing of 2d array
    for(i=0;i<8;i++)
        {
            for(j=0;j<8;j++)
                std::cout<<d[i][j];
            std::cout<<std::endl;
        }
}

//Function for convert int to bin
void tobin(int a,int b[])
{
    int i;
    for(i=0;i<8;i++)
    {
        b[i]=a%2;
        a/=2;
    }
}

And here my output:

01100000
11110000
00011000
00-16437331793270200193648149632765
014196397000-640061051-1985511146
419616001936481488327650000
16416403251985832910-46743922719940467470000
004196848019364814963276510

First 3 lines is what i was looking for, but i don't know what is the rest.
Can someone help me to fix this. And to give me explanation why is this happening or link to explanation.


问:
JAVA Console error
If i run this code below in Netbeans

```<code>import java.io.Console;
public class Introduction {
    public static void main(String[] args) {
        Console console= System.console();// creates a java Object which has method that allows us to write
        console.printf("Hallo parvel");
    }
}
</code>```

It gives me the error:

```<code>Exception in thread "main" java.lang.NullPointerException
    at Introduction.main(Introduction.java:10)
/home/parvel/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds).
</code>```

please help

答:
You need to run this from a terminal using java -jar myjar.jar

In order to have this print to console using System.console();

You will need to export this as a runnable jar

then you can run java -jar myjar.jar and it will output Hallo parvel

Title: JAVA Console error

Body:
If i run this code below in Netbeans

import java.io.Console;
public class Introduction {
    public static void main(String[] args) {
        Console console= System.console();// creates a java Object which has method that allows us to write
        console.printf("Hallo parvel");
    }
}

It gives me the error:

Exception in thread "main" java.lang.NullPointerException
    at Introduction.main(Introduction.java:10)
/home/parvel/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds).

please help


问:
copy paste excel vba
I have those sheets.
The second sheet is how I would it to be.
I am now trying for hours how I would do this.
Please can anyone help me on the right track.

I am copying from sheet 7(pic1) to sheet 9(pic2).
The lastrow to look for should be range F.

But I always end up like in pic3.

答:
this is the code i have for so far</p>

```<code>Sub Test1()
Dim lrow As Long
Dim scr1 As Range 'source range
Dim scr2 As Range
Dim drng As Range 'destination range
Dim drng2 As Range
Application.ScreenUpdating = False

Sheet7.Activate
Set drng = Sheet9.Range("A3")
Set drng2 = Sheet9.Range("D3")

Set scr1 = Sheet7.Range("RecipeHeader")
scr1.Select
Selection.Copy
Sheet9.Activate
drng.End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Sheet7.Activate
Set scr2 = Sheet7.Range("FoodCost_full")
scr2.Select
Selection.Copy
Sheet9.Activate
drng2.End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Sheet7.Range("ClearHeader").ClearContents
Sheet7.Range("Clearfood").ClearContents

Application.CutCopyMode = False
Application.ScreenUpdating = False

'lrow = Range("F" & Rows.Count).End(xlUp).Select

End Sub
</code>```

Title: copy paste excel vba

Body:
this is the code i have for so far

Sub Test1()
Dim lrow As Long
Dim scr1 As Range 'source range
Dim scr2 As Range
Dim drng As Range 'destination range
Dim drng2 As Range
Application.ScreenUpdating = False

Sheet7.Activate
Set drng = Sheet9.Range("A3")
Set drng2 = Sheet9.Range("D3")

Set scr1 = Sheet7.Range("RecipeHeader")
scr1.Select
Selection.Copy
Sheet9.Activate
drng.End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Sheet7.Activate
Set scr2 = Sheet7.Range("FoodCost_full")
scr2.Select
Selection.Copy
Sheet9.Activate
drng2.End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Sheet7.Range("ClearHeader").ClearContents
Sheet7.Range("Clearfood").ClearContents

Application.CutCopyMode = False
Application.ScreenUpdating = False

'lrow = Range("F" & Rows.Count).End(xlUp).Select

End Sub


问:
Trouble with creating one-time calendar event from Google Sheets row
I'm having some trouble with my Google Apps Script code trying to have it take the information on one row of my sheet and create a single, Calendar event, with beginning and ending times.

```<code>    //push new events to calendar
function pushToCalendar() {

  //spreadsheet variables
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var range = sheet.getRange(2,1,lastRow,16);
  var values = range.getValues();

  var numValues = 0;
  for (var i = 0; i < values.length; i++) {
    //check to see if Age, Competition, Start Date, Start Time and End Date & Time are filled out
    if ((values[i][0].length == '<>') && (values[i][1].length == '<>') && (values[i][4].length == '<>') && (values[i][5].length == '<>') && (values[i][6].length == '<>') && (values[i][7].length == '<>')) {

      //check if it's been entered before
      if ((values[i][8] == '')||(values[i][8] == null)) {

        //create event https://developers.google.com/apps-script/class_calendarapp#createEvent
        var newEventTitle = 'Game: ' + values[i][0] + ' - ' + values[i][1];
        var startDay = Utilities.formatDate(new Date(values[i][3]), 'America/Chicago', 'MMMM dd, yyyy');
        var startTime = Utilities.formatDate(new Date(values[i][4]), 'America/Chicago', 'HH:mm');
        var start = startDay + ' ' + startTime;
        var endDay = Utilities.formatDate(new Date(values[i][5]), 'America/Chicago', 'MMMM dd, yyyy');
        var endTime = Utilities.formatDate(new Date(values[i][6]), 'America/Chicago', 'HH:mm');
        var end = endDay+ ' ' + endTime;
        var newEvent = CalendarApp.getDefaultCalendar().createEvent(newEventTitle, new Date(start), new Date(end), {location: values[i][12]});
        //get ID
        var newEventId = newEvent.getId();

        //mark as entered, enter ID
        sheet.getRange(i+2,8).setValue(newEventId);

      } //could edit here with an else statement
    }
    numValues++;
  }
}
</code>```

I have pertinent information (used in the event title) in the first three columns, and Start Date in column 4, Start Time in column 5, End Date in column 6, and End Time in column 7. The other columns contain information that I'll add to the description of the event.

The problem I'm mostly running into is filtering the data set into events that have not been pushed to the Calendar yet, as well as the script accurately recording once it does push an event over, such that it will be able to filter it on the next cycle of the script.

答:
I modified the code a little but not much. Here it is. I was able to get all six events on the calendar with very few changes.

```<code>function pushToCalendar() {

  //spreadsheet variables
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var range = sheet.getRange(2,1,lastRow,16);
  var values = range.getValues();
  var numValues = 0;
  for (var i = 0; i < values.length; i++) {
    //check to see if Age, Competition, Start Date, Start Time and End Date & Time are filled out
    if ((values[i][0]) && (values[i][1]) && (values[i][4]) && (values[i][5]) && (values[i][6]) && (values[i][7]))
    {
      //check if it's been entered before
      if (!values[i][8])
      {
        //create event https://developers.google.com/apps-script/class_calendarapp#createEvent
        var newEventTitle = 'Game: ' + values[i][0] + ' - ' + values[i][1];
        var startDay = Utilities.formatDate(new Date(values[i][4]), 'GMT-5', 'MMMM dd, yyyy');
        var startTime = Utilities.formatDate(new Date(values[i][5]), 'GMT-5', 'HH:mm');
        var start = startDay + ' ' + startTime;
        var endDay = Utilities.formatDate(new Date(values[i][6]), 'GMT-5', 'MMMM dd, yyyy');
        var endTime = Utilities.formatDate(new Date(values[i][7]), 'GMT-5', 'HH:mm');
        var end = endDay+ ' ' + endTime;
        var newEvent = CalendarApp.getDefaultCalendar().createEvent(newEventTitle, new Date(start), new Date(end), {location: values[i][12]});
        //get ID
        var newEventId = newEvent.getId();
        //mark as entered, enter ID
        sheet.getRange(i+2,9).setValue(newEventId);//Why i+2
      } //could edit here with an else statement
    }
    numValues++;
  }
}
</code>```

and here's my test data.

```<code>Title1  Title2          startDay    startTime   endDay  endTime completed               Location
Event1  Day1            4/1/2017    10:00 AM    4/1/2017    2:00 PM sbcfnqdevvc16vs4q237k6udnk@google.com               Denver
Event1  Day2            4/2/2017    10:00 AM    4/2/2017    2:00 PM oj8ui4m5h3jcpqmj7ev10ih91k@google.com               Honolulu
Event1  Day3            4/3/2017    10:00 AM    4/3/2017    12:00 PM    n6fro1u4rcgieu6720ujudents@google.com               San Francisco
Event2  Day1            4/4/2017    10:00 AM    4/4/2017    2:00 PM kq3m6cel3jg5j6kiljtlvhgppg@google.com               Denver
Event2  Day2            4/5/2017    10:00 AM    4/5/2017    2:00 PM nbmfsb9bar5ucsvgaddqsbvss8@google.com               Honolulu
Event2  Day3            4/6/2017    10:00 AM    4/6/2017    12:00 PM    p7kc6p82gbvf94terd6cl1aiuo@google.com               San Francisco
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having some trouble with my Google Apps Script code trying to have it take the information on one row of my sheet and create a single, Calendar event, with beginning and ending times.

    //push new events to calendar
function pushToCalendar() {

  //spreadsheet variables
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var range = sheet.getRange(2,1,lastRow,16);
  var values = range.getValues();

  var numValues = 0;
  for (var i = 0; i < values.length; i++) {
    //check to see if Age, Competition, Start Date, Start Time and End Date & Time are filled out
    if ((values[i][0].length == '<>') && (values[i][1].length == '<>') && (values[i][4].length == '<>') && (values[i][5].length == '<>') && (values[i][6].length == '<>') && (values[i][7].length == '<>')) {

      //check if it's been entered before
      if ((values[i][8] == '')||(values[i][8] == null)) {

        //create event https://developers.google.com/apps-script/class_calendarapp#createEvent
        var newEventTitle = 'Game: ' + values[i][0] + ' - ' + values[i][1];
        var startDay = Utilities.formatDate(new Date(values[i][3]), 'America/Chicago', 'MMMM dd, yyyy');
        var startTime = Utilities.formatDate(new Date(values[i][4]), 'America/Chicago', 'HH:mm');
        var start = startDay + ' ' + startTime;
        var endDay = Utilities.formatDate(new Date(values[i][5]), 'America/Chicago', 'MMMM dd, yyyy');
        var endTime = Utilities.formatDate(new Date(values[i][6]), 'America/Chicago', 'HH:mm');
        var end = endDay+ ' ' + endTime;
        var newEvent = CalendarApp.getDefaultCalendar().createEvent(newEventTitle, new Date(start), new Date(end), {location: values[i][12]});
        //get ID
        var newEventId = newEvent.getId();

        //mark as entered, enter ID
        sheet.getRange(i+2,8).setValue(newEventId);

      } //could edit here with an else statement
    }
    numValues++;
  }
}

I have pertinent information (used in the event title) in the first three columns, and Start Date in column 4, Start Time in column 5, End Date in column 6, and End Time in column 7. The other columns contain information that I'll add to the description of the event.

The problem I'm mostly running into is filtering the data set into events that have not been pushed to the Calendar yet, as well as the script accurately recording once it does push an event over, such that it will be able to filter it on the next cycle of the script.

Body:
I modified the code a little but not much. Here it is. I was able to get all six events on the calendar with very few changes.

function pushToCalendar() {

  //spreadsheet variables
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var range = sheet.getRange(2,1,lastRow,16);
  var values = range.getValues();
  var numValues = 0;
  for (var i = 0; i < values.length; i++) {
    //check to see if Age, Competition, Start Date, Start Time and End Date & Time are filled out
    if ((values[i][0]) && (values[i][1]) && (values[i][4]) && (values[i][5]) && (values[i][6]) && (values[i][7]))
    {
      //check if it's been entered before
      if (!values[i][8])
      {
        //create event https://developers.google.com/apps-script/class_calendarapp#createEvent
        var newEventTitle = 'Game: ' + values[i][0] + ' - ' + values[i][1];
        var startDay = Utilities.formatDate(new Date(values[i][4]), 'GMT-5', 'MMMM dd, yyyy');
        var startTime = Utilities.formatDate(new Date(values[i][5]), 'GMT-5', 'HH:mm');
        var start = startDay + ' ' + startTime;
        var endDay = Utilities.formatDate(new Date(values[i][6]), 'GMT-5', 'MMMM dd, yyyy');
        var endTime = Utilities.formatDate(new Date(values[i][7]), 'GMT-5', 'HH:mm');
        var end = endDay+ ' ' + endTime;
        var newEvent = CalendarApp.getDefaultCalendar().createEvent(newEventTitle, new Date(start), new Date(end), {location: values[i][12]});
        //get ID
        var newEventId = newEvent.getId();
        //mark as entered, enter ID
        sheet.getRange(i+2,9).setValue(newEventId);//Why i+2
      } //could edit here with an else statement
    }
    numValues++;
  }
}

and here's my test data.

Title1  Title2          startDay    startTime   endDay  endTime completed               Location
Event1  Day1            4/1/2017    10:00 AM    4/1/2017    2:00 PM sbcfnqdevvc16vs4q237k6udnk@google.com               Denver
Event1  Day2            4/2/2017    10:00 AM    4/2/2017    2:00 PM oj8ui4m5h3jcpqmj7ev10ih91k@google.com               Honolulu
Event1  Day3            4/3/2017    10:00 AM    4/3/2017    12:00 PM    n6fro1u4rcgieu6720ujudents@google.com               San Francisco
Event2  Day1            4/4/2017    10:00 AM    4/4/2017    2:00 PM kq3m6cel3jg5j6kiljtlvhgppg@google.com               Denver
Event2  Day2            4/5/2017    10:00 AM    4/5/2017    2:00 PM nbmfsb9bar5ucsvgaddqsbvss8@google.com               Honolulu
Event2  Day3            4/6/2017    10:00 AM    4/6/2017    12:00 PM    p7kc6p82gbvf94terd6cl1aiuo@google.com               San Francisco