问:
How to count checked checkbox with Javascript?
I would like to count the checkboxes that are checked and display the count in the Div.

Here is my HTML :

```<code><form name="liste_figurine" method="post">

<input type="checkbox" id="radio-1" class="z" name="chck1[]" onclick="updateCount()" />
<input type="checkbox" id="radio-2" class="z" name="chck2[]" onclick="updateCount()" />

</form>

<div id="y"></div>
</code>```

Here is my JS :

```<code>function updateCount {
    var x = $(".z:checked").length;
    document.getElementById("y").innerHTML = x;
};
</code>```

Here is an exemple : https://jsfiddle.net/r3todbs6/3/

Sorry, I'm not really used to JS... What is wrong with my code ?

Finally, it's working but I have one last issue : the onclick must contain 2 functions and I don't manage to make them working together.

Now this function works, alone : onclick="updateCount()"

This other function works also, alone : onclick="document.getElementById(\'radio-'.$ligne['id'].'-2\').checked = false"

But these two functions doesn't work, together :
onclick="updateCount(); fx2(document.getElementById(\'radio-'.$ligne['id'].'-1\').checked = false);"

What is wrong with the third proposition ? Is it a syntax error ?

答:
The answer provided by kangsu is the best answer but here is how I did it.

var form = document.getElementById('form');
var checkBoxes = $(form).children('.checkbox');
var count = 0;

var divBoxesChecked = document.getElementById('boxesChecked');
divBoxesChecked.innerHTML = 0;

$(checkBoxes).on('click', function() {
  $.each(checkBoxes, function(i) {
    if (checkBoxes[i].checked) {
      count++;
    }
  });
  console.log(count);
  divBoxesChecked.innerHTML = count;
  count = 0;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<form id="form" method="post">

  <input type="checkbox" id="box_01" class="checkbox" name="box_01" />
  <label>Box 1</label>

  <input type="checkbox" id="box_02" class="checkbox" name="box_02" />
  <label>Box 2</label>

  <input type="checkbox" id="box_03" class="checkbox" name="box_03" />
  <label>Box 3</label>

</form>

<div id="boxesChecked"></div></code>```

Basically, every time one of the boxes is clicked it counts how many boxes are checked in total and prints that out to the div and the console, then it resets the counter to zero since it re-counts all of the checked boxes every time you click on one.

Body:
I would like to count the checkboxes that are checked and display the count in the Div.

Here is my HTML :

<form name="liste_figurine" method="post">

<input type="checkbox" id="radio-1" class="z" name="chck1[]" onclick="updateCount()" />
<input type="checkbox" id="radio-2" class="z" name="chck2[]" onclick="updateCount()" />

</form>

Here is my JS :

function updateCount {
    var x = $(".z:checked").length;
    document.getElementById("y").innerHTML = x;
};

Here is an exemple : https://jsfiddle.net/r3todbs6/3/

Sorry, I'm not really used to JS... What is wrong with my code ?

Finally, it's working but I have one last issue : the onclick must contain 2 functions and I don't manage to make them working together.

Now this function works, alone : onclick="updateCount()"

This other function works also, alone : onclick="document.getElementById(\'radio-'.$ligne['id'].'-2\').checked = false"

But these two functions doesn't work, together :
onclick="updateCount(); fx2(document.getElementById(\'radio-'.$ligne['id'].'-1\').checked = false);"

What is wrong with the third proposition ? Is it a syntax error ?

Body:
The answer provided by kangsu is the best answer but here is how I did it.

var form = document.getElementById('form');
var checkBoxes = $(form).children('.checkbox');
var count = 0;

var divBoxesChecked = document.getElementById('boxesChecked');
divBoxesChecked.innerHTML = 0;

$(checkBoxes).on('click', function() {
  $.each(checkBoxes, function(i) {
    if (checkBoxes[i].checked) {
      count++;
    }
  });
  console.log(count);
  divBoxesChecked.innerHTML = count;
  count = 0;
});

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<form id="form" method="post">

  <input type="checkbox" id="box_01" class="checkbox" name="box_01" />
  <label>Box 1</label>

  <input type="checkbox" id="box_02" class="checkbox" name="box_02" />
  <label>Box 2</label>

  <input type="checkbox" id="box_03" class="checkbox" name="box_03" />
  <label>Box 3</label>

</form>

<div id="boxesChecked"></div>

Basically, every time one of the boxes is clicked it counts how many boxes are checked in total and prints that out to the div and the console, then it resets the counter to zero since it re-counts all of the checked boxes every time you click on one.


来源: stackexchange

问:
Do not discard keys with null values when converting to JSON in PySpark DataFrame
I am creating a column in a DataFrame from several other columns that I want to store as a JSON serialized string. When the serialization to JSON occurs, keys with null values are dropped. Is there a way to keep keys even if the value is null?

Sample program illustrating the issue:

```<code>from pyspark.sql import functions as F

df = sc.parallelize([
    (1, 10),
    (2, 20),
    (3, None),
    (4, 40),
]).toDF(['id', 'data'])
df.collect()
#[Row(id=1, data=10),
# Row(id=2, data=20),
# Row(id=3, data=None),
# Row(id=4, data=40)]

df_s = df.select(F.struct('data').alias('struct'))
df_s.collect()
#[Row(struct=Row(data=10)),
# Row(struct=Row(data=20)),
# Row(struct=Row(data=None)),
# Row(struct=Row(data=40))]

df_j = df.select(F.to_json(F.struct('data')).alias('json'))
df_j.collect()
#[Row(json=u'{"data":10}'),
# Row(json=u'{"data":20}'),
# Row(json=u'{}'), <= would like this to be u'{"data":null}'
# Row(json=u'{"data":40}')]
</code>```

Running Spark 2.1.0

答:
Could not find a Spark specific solution so just wrote a udf and used the python json package:</p>

```<code>import json
from pyspark.sql import types as T

def to_json(data):
    return json.dumps({'data': data})

to_json_udf = F.udf(to_json, T.StringType())

df.select(to_json_udf('data').alias('json')).collect()
# [Row(json=u'{"data": 10}'),
#  Row(json=u'{"data": 20}'),
#  Row(json=u'{"data": null}'),
#  Row(json=u'{"data": 40}')]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am creating a column in a DataFrame from several other columns that I want to store as a JSON serialized string. When the serialization to JSON occurs, keys with null values are dropped. Is there a way to keep keys even if the value is null?

Sample program illustrating the issue:

from pyspark.sql import functions as F

df = sc.parallelize([
    (1, 10),
    (2, 20),
    (3, None),
    (4, 40),
]).toDF(['id', 'data'])
df.collect()
#[Row(id=1, data=10),
# Row(id=2, data=20),
# Row(id=3, data=None),
# Row(id=4, data=40)]

df_s = df.select(F.struct('data').alias('struct'))
df_s.collect()
#[Row(struct=Row(data=10)),
# Row(struct=Row(data=20)),
# Row(struct=Row(data=None)),
# Row(struct=Row(data=40))]

df_j = df.select(F.to_json(F.struct('data')).alias('json'))
df_j.collect()
#[Row(json=u'{"data":10}'),
# Row(json=u'{"data":20}'),
# Row(json=u'{}'), <= would like this to be u'{"data":null}'
# Row(json=u'{"data":40}')]

Running Spark 2.1.0

Body:
Could not find a Spark specific solution so just wrote a udf and used the python json package:

import json
from pyspark.sql import types as T

def to_json(data):
    return json.dumps({'data': data})

to_json_udf = F.udf(to_json, T.StringType())

df.select(to_json_udf('data').alias('json')).collect()
# [Row(json=u'{"data": 10}'),
#  Row(json=u'{"data": 20}'),
#  Row(json=u'{"data": null}'),
#  Row(json=u'{"data": 40}')]


问:
Fastest possible MYSQL SELECT query with JOINS (join itself)
i am having some trouble with indices and the performance of my query.
I am currently doing as following:

```<code>SELECT
    images.imageId,
    path,
    fileName,
    alt,
    description,
    width,
    height
FROM
    images
LEFT JOIN imagesEn ON images.imageId=imagesEn.imageId

WHERE

images.adId = ?

AND images.imageStatus = 1
AND images.isPreview = 1
AND (images.isBanner = 0 OR images.isBanner IS NULL)

ORDER BY RAND() LIMIT 1;';
</code>```

This gives me the image i want. But i am using responsive picture elements, there are smaller versions of the image.
My limited sql-knowledge forced me to use another query then like so:

```<code>SELECT
    images.imageId,
    relativePathToImageFromImgFolder,
    fileName,
    altAttribute,
    description,
    width,
    height
FROM
    images
LEFT JOIN imagesEn ON images.imageId=imagesEn.imageId

WHERE

images.adId = ?

AND images.imageStatus = 1
AND images.isPreview = 0
AND images.isSmallerVersionOf = ?

ORDER by width DESC
</code>```

Then i am ending up with two queries and two arrays which gives me the main image plus all the smaller versions of the image to create my picture element.
The join is needed because i have several languages (imagesEn, imagesDe, imagesFr, etc.) which joins the filename, attributes in the given language.
I have just set single-column indices, multi-column indices are new to me i have heard from the the first time today :D.
I am showing something like producte on a product page and my page-generation time is about 0.3 seconds (uncashed). All my other pages have 0.0x second which is my goal for that page, too.
Plus i am doing this query inside a loop

```<code>$query = 'SELECT name, id, url, whatever from products where productColor = "blue";';
foreach($arr as $r)
{
    $str .= '<div>';
            $str .= $r['name'] . ' ' . $r['whatever'];
            $str .= self::createPictureElementFromId($r['id']);  //this calls the above queries to create the picture element with its main image and the child images (smaller versions for smaller screens)
    $str .= '</div>';
}

return $str;
</code>```

Hope the description is precise enough ;).
Thanks in advance

答:
i.isBanner = 0 OR i.isBanner IS NULL -- pick one.  This will let you get rid of OR, which is a performance killer.

Then have INDEX(adId, imageStatus, isPreview, isBanner) (in any order).  This should allow the filtering to run faster.

Please provide SHOW CREATE TABLE, since I am having to guess at some of your datatypes, etc.

To do the ORDER BY RAND() LIMIT 1, it is inefficient to haul around all the columns, only to pick one of them.  So, instead do this:

```<code>SELECT i.imageId, i.path, ...
    FROM ( SELECT imageId FROM images WHERE ...
               ORDER BY RAND() LIMIT 1 ) AS x
    JOIN images i  USING(imageId)
</code>```

But then you need INDEX(adId, imageStatus, isPreview, isBanner, imageId) so that the inner query can run entirely in the index.

"Smaller version" -- Have the flag say "this is a small image" and include it in the WHERE and the INDEX.

Language URL -- Add another JOIN to the above to get the language-specific URL, which should be in another table.  That table should have PRIMARY KEY(imageId, lang).

Body:
i am having some trouble with indices and the performance of my query.
I am currently doing as following:

SELECT
    images.imageId,
    path,
    fileName,
    alt,
    description,
    width,
    height
FROM
    images
LEFT JOIN imagesEn ON images.imageId=imagesEn.imageId

WHERE

images.adId = ?

AND images.imageStatus = 1
AND images.isPreview = 1
AND (images.isBanner = 0 OR images.isBanner IS NULL)

ORDER BY RAND() LIMIT 1;';

This gives me the image i want. But i am using responsive picture elements, there are smaller versions of the image.
My limited sql-knowledge forced me to use another query then like so:

SELECT
    images.imageId,
    relativePathToImageFromImgFolder,
    fileName,
    altAttribute,
    description,
    width,
    height
FROM
    images
LEFT JOIN imagesEn ON images.imageId=imagesEn.imageId

WHERE

images.adId = ?

AND images.imageStatus = 1
AND images.isPreview = 0
AND images.isSmallerVersionOf = ?

ORDER by width DESC

Then i am ending up with two queries and two arrays which gives me the main image plus all the smaller versions of the image to create my picture element.
The join is needed because i have several languages (imagesEn, imagesDe, imagesFr, etc.) which joins the filename, attributes in the given language.
I have just set single-column indices, multi-column indices are new to me i have heard from the the first time today :D.
I am showing something like producte on a product page and my page-generation time is about 0.3 seconds (uncashed). All my other pages have 0.0x second which is my goal for that page, too.
Plus i am doing this query inside a loop

$query = 'SELECT name, id, url, whatever from products where productColor = "blue";';
foreach($arr as $r)
{
    $str .= '
';
            $str .= $r['name'] . ' ' . $r['whatever'];
            $str .= self::createPictureElementFromId($r['id']);  //this calls the above queries to create the picture element with its main image and the child images (smaller versions for smaller screens)
    $str .= '
';
}

return $str;

Hope the description is precise enough ;).
Thanks in advance

Body:
i.isBanner = 0 OR i.isBanner IS NULL -- pick one.  This will let you get rid of OR, which is a performance killer.

Then have INDEX(adId, imageStatus, isPreview, isBanner) (in any order).  This should allow the filtering to run faster.

Please provide SHOW CREATE TABLE, since I am having to guess at some of your datatypes, etc.

To do the ORDER BY RAND() LIMIT 1, it is inefficient to haul around all the columns, only to pick one of them.  So, instead do this:

SELECT i.imageId, i.path, ...
    FROM ( SELECT imageId FROM images WHERE ...
               ORDER BY RAND() LIMIT 1 ) AS x
    JOIN images i  USING(imageId)

But then you need INDEX(adId, imageStatus, isPreview, isBanner, imageId) so that the inner query can run entirely in the index.

"Smaller version" -- Have the flag say "this is a small image" and include it in the WHERE and the INDEX.

Language URL -- Add another JOIN to the above to get the language-specific URL, which should be in another table.  That table should have PRIMARY KEY(imageId, lang).


问:
How do I run that database backup and restore scripts from my winform application?
I am developing a small business application which uses Sqlserver 2005 database.

Platform: .Net framework 3.5;
Application type: windows application;
Language: C#

Question:

I need to take and restore the backup from my application. I have the required script generated from SSME.

How do I run that particular script (or scripts) from my winform application?

答: Just use your connection to the database (ADO I presume?) and send your plain TSQL instructions to the server through this connection. </p>

OwnerDisplayName: Asad Malik

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Philippe Grondier


问:
Geolocation provider for Firefox that allows manual input
Are there any easy ways to override the default behaviors of the geolocation api and just hard code your current location?

I think this would be useful for testing and for privacy reasons (providing fake location data)

I thought there was an add on for this but I can't seem to find one.  Only option right now seems to be changing the about:config geo.wifi.url to some alternative webservice, which I consider overly complicated.

Any ideas?

Thanks

Ideal Scenario

Somebody implements an add-on where a google map appears and I can pick a new default location.

答:
I have wired up Google Latitude to Firefox geolocation. This lets you manually update your location in Google Latitude with a single mouse click, instead of looking up your latitude and longitude yourself and typing it into a local file. My article on the subject is Make Firefox Take Geolocation From Google Latitude.

The solution required a small amount of server-side coding (I provide source code in the article), but I am for the time being running this code as a free live service that you can use.

Cheers, MetaEd


问:
Delphi Thread and TCriticalSection
I encounter some strange behaviors with threads so I guess there is something I'm doing wrong or something I don't understand.

My application (Delphi Berlin) has two processes : a service and a console app. They communitcate via socket (Indy).

Each process has a thread dedicated to communication.

I use TCriticalSection when I need to read/write variables used by main thread and by communication Thread.

I also make intensive usage of log. The log can be written (one log file by process) by main thread and by communication thread.

So what I'm doing when I want to write a trace in log file is to use a variable TCriticalSection to prevent main thread and commmunication thread to write to the log file at the same time:

```<code>Procedure TApp.trace(logLevel : byte; procName , pi_str: string);
var F: textfile;
    LogFileName: String;
    vl_log : Boolean;
    vc_LogHeader : String;
    th, thcurrent : TTh;
begin
    if GetLog() then begin // False if log is deactivated
        for th := Low(TTh) to High(TTh) do begin
            if TThread.CurrentThread.ClassName = ThreadsLog.Name[th] then begin
                thcurrent := th;
                break;
            end;
        end;
        if ThreadsLog.LogLevel[thcurrent] < logLevel then exit;

        LogFileName := gc_tmp + WinProc.Name[WHO_AM_I] + '.log';
        vc_LogHeader := '[' + GetLogTime + ' ' + ThreadsLog.Name[thcurrent] + ' ' + procName + ' ' + IntToStr(logLevel) + ']';
        if Length(vc_LogHeader) < 60 then vc_LogHeader := vc_LogHeader + StringOfChar (' ', 60 - Length(vc_LogHeader) );

        LockTrace.Acquire;
        try
            try
                {$IFDEF MACOS}
                    AssignFile(F, LogFileName, CP_UTF8);
                {$ELSE}
                    AssignFile(F, LogFileName);
                {$ENDIF}
                if FileExists(LogFileName) then Append(F) else Rewrite(F);
                {$IFDEF MACOS}
                    Writeln(F, UTF8String(vc_LogHeader + AnsiString(pi_str)));
                {$ELSE}
                    Writeln(F, vc_LogHeader + pi_str);
                {$ENDIF}
                CloseFile(F);
            except
                on e : exception do begin
                    dbg(LogFileName + ' ' + e.Message);
                end;
            end;
        finally
            lockTrace.Release;
        end;
    end;
end;

function TApp.GetLog() : boolean;
begin
    gl_logLock.Acquire;
    try
        result := gl_log;
    finally
        gl_logLock.Release;
    end;
end;
</code>```

However sometimes, some lines are not written to the file.
But dbg(LogFileName + ' ' + e.Message) does not execute cause it is supposed to write in another log file and this file stays empty. So no exception seems to be fired.

Is it possible to use TCriticalSection this way ?
What I understand about TCriticalSection, is that it puts a lock so others threads trying to put their own lock have to wait until it is released. Is that right ?

I guess I can use one variable or several variables TCriticalSection. If I use only one variable, there will be more cases where a lock exists so more time to wait. If I use one TCriticalSection per shared variable, there will be less locks so better performances. Is it right ?

Thanks for any correction or clarification.

答:
There are many problems with your code, not all thread / critical section related.

```<code>function TApp.GetLog() : boolean;
begin
    gl_logLock.Acquire;
    try
        result := gl_log;
    finally
        gl_logLock.Release;
    end;
end;
</code>```

The above lock code is useless it doesn't provide any protection whatsoever. Reading a boolean variable is already atomic. It's also symptomatic of a common misunderstanding of how to make code thread-safe.

Locks are intended to protect access to data.

The above pattern is often incorrectly used to protect access to an object.

But once the calling code is able to start using the object, you're already outside the lock.

I.e the underlying data of the object is no longer protected from concurrent thread access.

```<code>for th := Low(TTh) to High(TTh) do begin
    if TThread.CurrentThread.ClassName = ThreadsLog.Name[th] then begin
        thcurrent := th;
        break;
    end;
end;
if ThreadsLog.LogLevel[thcurrent] < logLevel then exit;
</code>```

In the above, if the loop ever ends without the if condition evaluating to True, thcurrent will be uninitialised leading to undefined behaviour. Anything from AV exceptions to things just not behaving as you'd expect.

Quite possibly ThreadsLog.LogLevel[thcurrent] < logLevel could evaluate to True (and Exit) without triggering an AV for some undefined values of thcurrent.

Also note that looping through your threads and doing string comparisons is a pretty inefficient way to check your current thread. It's not clear what you're trying to achieve, but you should be able to figure certain things out simply from the current thread id.

You say dbg(LogFileName + ' ' + e.Message); is not called. Well there are many reasons it might not be called. You'll have to figure out which (1 or multiple) apply.

You could Exit early.

GetLog() might return False.

Any exception before the try..except block won't get there.

If you've disabled IO errors, an exception won't be raised by old-style file operations. You would have to manually check them using IOResult.

And of course dbg might be called, but could itself also fail in some way.

Title: Delphi Thread and TCriticalSection

Body:
I encounter some strange behaviors with threads so I guess there is something I'm doing wrong or something I don't understand.

My application (Delphi Berlin) has two processes : a service and a console app. They communitcate via socket (Indy).

Each process has a thread dedicated to communication.

I use TCriticalSection when I need to read/write variables used by main thread and by communication Thread.

I also make intensive usage of log. The log can be written (one log file by process) by main thread and by communication thread.

So what I'm doing when I want to write a trace in log file is to use a variable TCriticalSection to prevent main thread and commmunication thread to write to the log file at the same time:

Procedure TApp.trace(logLevel : byte; procName , pi_str: string);
var F: textfile;
    LogFileName: String;
    vl_log : Boolean;
    vc_LogHeader : String;
    th, thcurrent : TTh;
begin
    if GetLog() then begin // False if log is deactivated
        for th := Low(TTh) to High(TTh) do begin
            if TThread.CurrentThread.ClassName = ThreadsLog.Name[th] then begin
                thcurrent := th;
                break;
            end;
        end;
        if ThreadsLog.LogLevel[thcurrent] < logLevel then exit;

        LogFileName := gc_tmp + WinProc.Name[WHO_AM_I] + '.log';
        vc_LogHeader := '[' + GetLogTime + ' ' + ThreadsLog.Name[thcurrent] + ' ' + procName + ' ' + IntToStr(logLevel) + ']';
        if Length(vc_LogHeader) < 60 then vc_LogHeader := vc_LogHeader + StringOfChar (' ', 60 - Length(vc_LogHeader) );

        LockTrace.Acquire;
        try
            try
                {$IFDEF MACOS}
                    AssignFile(F, LogFileName, CP_UTF8);
                {$ELSE}
                    AssignFile(F, LogFileName);
                {$ENDIF}
                if FileExists(LogFileName) then Append(F) else Rewrite(F);
                {$IFDEF MACOS}
                    Writeln(F, UTF8String(vc_LogHeader + AnsiString(pi_str)));
                {$ELSE}
                    Writeln(F, vc_LogHeader + pi_str);
                {$ENDIF}
                CloseFile(F);
            except
                on e : exception do begin
                    dbg(LogFileName + ' ' + e.Message);
                end;
            end;
        finally
            lockTrace.Release;
        end;
    end;
end;

function TApp.GetLog() : boolean;
begin
    gl_logLock.Acquire;
    try
        result := gl_log;
    finally
        gl_logLock.Release;
    end;
end;

However sometimes, some lines are not written to the file.
But dbg(LogFileName + ' ' + e.Message) does not execute cause it is supposed to write in another log file and this file stays empty. So no exception seems to be fired.

Is it possible to use TCriticalSection this way ?
What I understand about TCriticalSection, is that it puts a lock so others threads trying to put their own lock have to wait until it is released. Is that right ?

I guess I can use one variable or several variables TCriticalSection. If I use only one variable, there will be more cases where a lock exists so more time to wait. If I use one TCriticalSection per shared variable, there will be less locks so better performances. Is it right ?

Thanks for any correction or clarification.

Body:
There are many problems with your code, not all thread / critical section related.

function TApp.GetLog() : boolean;
begin
    gl_logLock.Acquire;
    try
        result := gl_log;
    finally
        gl_logLock.Release;
    end;
end;

The above lock code is useless it doesn't provide any protection whatsoever. Reading a boolean variable is already atomic. It's also symptomatic of a common misunderstanding of how to make code thread-safe.

Locks are intended to protect access to data.

The above pattern is often incorrectly used to protect access to an object.

But once the calling code is able to start using the object, you're already outside the lock.

I.e the underlying data of the object is no longer protected from concurrent thread access.

for th := Low(TTh) to High(TTh) do begin
    if TThread.CurrentThread.ClassName = ThreadsLog.Name[th] then begin
        thcurrent := th;
        break;
    end;
end;
if ThreadsLog.LogLevel[thcurrent] < logLevel then exit;

In the above, if the loop ever ends without the if condition evaluating to True, thcurrent will be uninitialised leading to undefined behaviour. Anything from AV exceptions to things just not behaving as you'd expect.

Quite possibly ThreadsLog.LogLevel[thcurrent] < logLevel could evaluate to True (and Exit) without triggering an AV for some undefined values of thcurrent.

Also note that looping through your threads and doing string comparisons is a pretty inefficient way to check your current thread. It's not clear what you're trying to achieve, but you should be able to figure certain things out simply from the current thread id.

You say dbg(LogFileName + ' ' + e.Message); is not called. Well there are many reasons it might not be called. You'll have to figure out which (1 or multiple) apply.

You could Exit early.

GetLog() might return False.

Any exception before the try..except block won't get there.

If you've disabled IO errors, an exception won't be raised by old-style file operations. You would have to manually check them using IOResult.

And of course dbg might be called, but could itself also fail in some way.


问:
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.

答:
In your case, you could possibly write your own WindowFn. If you set the keys to be the session IDs then a large gap duration also works, but it doesn't reflect the nature of your data and computation quite as well.

The ingredients to your WindowFn would be:

your own subclass of BoundedWindow, in this case you would make a window type that contained the session ID in a field

assignWindows, where you would assign each element to a window identified by the session ID. The length of the window still matters, as it controls when the window expires and is garbage collected.

mergeWindows, where you would merge all windows that have the same session ID. They wouldn't have to fall within any particular gap duration.

Another thing you'll need to be careful of is that the watermark that governs the garbage collection of these windows is determined by the source of your unbounded stream of events. So setting the timestamps in your ParDo.of(new ParseEventFn()) will be too late to influence the watermark. You may have data dropped that you'd like to keep.

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.


问:
Automatically pausing html5 video as the 'next' button is pressed (javascript/ jquery)
I have designed an i-phone-like screen on a web browser where I am testing this application I am in the process of building. None of the videos have auto-play; the user can play the video by clicking on the video area.The user can navigate to the next video by clicking on the top right button.

THE PROBLEM:  The problem is if I pressed on a video and it is playing,if I press the 'next' button, if I have not clicked back on, the video continues to play as the new one advances, and I can hear the sound of it playing in the background.

I HAVE TRIED TO MUTE THE VIDEOS BUT IT DID NOT WORK I have tried muting the video if the user clicks on the 'next' button, and it works to mute it, BUT, the problem is that if I press the return button, the video is completely muted and unless I refresh the page, the sound will not play again at all*.

This is the jquery code I used to try and mute the video if the 'next' button is pressed:

```<code>$("#nextButtonTop, #prevButtonTop ").click( function (){
if( $("#topVid video:visible").prop('muted') ) {
        $("#topVid video:visible").prop('muted', true);

  } else {
    $("#topVid video:visible").prop('muted', true);

  }
});
</code>```

The basic html code for this section:

```<code><div class="topVid channel1960s">
  <div class="testMarqueeLeft"><div>CHANNEL 1960s: Jackie Kennedy at JFK's service</div></div>
      <video loop onclick="this.paused? this.play() : this.pause()" >
      <source src="videos/1960s_Jackie_mourning_VERT.mp4" type="video/mp4">
      Your browser does not support the video tag.
      </video> </div>
</code>```

IDEAL SOLUTION: PAUSING AS SOON AS THE 'NEXT' BUTTON IS PRESSED ultimately, I realized that muting is not the ideal solution because of performance issues (the hidden video will keep playing even without the sound). What is the best way to pause (instead of muting) the video as soon with this 'next' button pressed? There is already inline javascript code on the html that will play and pause if the user clicks on it but I am not sure how add this other part, where it pauses if the next button is pressed and it can be played once it is visible.

I tried this to make the video pause but it did not work

```<code>$("#nextButtonTop, #prevButtonTop ").click( function (){
  if ($('.topVid.video').is(":hidden")) {
      $('.topVid.video').pause();
  }
});
</code>```

I tried this as well and nothing

```<code>$('video').each(function(){
    if ($(this).is(":in-viewport")) {
        $(this)[0].play();
    } else {
        $(this)[0].pause();
    }
})
</code>```

the use of

```<code> "this.paused ? this.play() : this.pause();"
</code>```

was suggested on another answer but I am not sure how this could work given that the pausing would be triggered by clicking on another element (the 'next' button, not the video itself.

答:
Unless your jQuery is at the end of the document, remember to wrap it in jQuery(function($) {...}).

Attach all event handlers in javaScript, not HTML. This is not essential, but allows you to see all your interactive code in a single glance.

Stay aware that .play() and .pause() are <video> element methods, not jQuery methods.

Try this :

HTML

```<code><div class="topVid channel1960s">
    <div class="testMarqueeLeft">
        <div>CHANNEL 1960s: Jackie Kennedy at JFK's service</div>
    </div>
    <video loop> <!-- remove onclick="..." -->
        <source src="videos/1960s_Jackie_mourning_VERT.mp4" type="video/mp4" />
        Your browser does not support the video tag.
    </video>
</div>
</code>```

JavaScript

```<code>jQuery(function($) {
    // Attach click handler to both <video> elements
    $('video').on('click', function() {
        this.paused? this.play() : this.pause();
    });

    // Attach click handler to top video's prev/next buttons
    $("#nextButtonTop, #prevButtonTop").on('click', function(e) {
        e.preventDefault(); // maybe not required but does no harm.
        var $video = $('.topVid video');
        if ($video.is(':hidden')) {
            $video.get(0).pause(); // .pause() is a method of the <video> element, not a jQuery method.
        }
    });
});
</code>```

Body:
I have designed an i-phone-like screen on a web browser where I am testing this application I am in the process of building. None of the videos have auto-play; the user can play the video by clicking on the video area.The user can navigate to the next video by clicking on the top right button.

THE PROBLEM:  The problem is if I pressed on a video and it is playing,if I press the 'next' button, if I have not clicked back on, the video continues to play as the new one advances, and I can hear the sound of it playing in the background.

I HAVE TRIED TO MUTE THE VIDEOS BUT IT DID NOT WORK I have tried muting the video if the user clicks on the 'next' button, and it works to mute it, BUT, the problem is that if I press the return button, the video is completely muted and unless I refresh the page, the sound will not play again at all*.

This is the jquery code I used to try and mute the video if the 'next' button is pressed:

$("#nextButtonTop, #prevButtonTop ").click( function (){
if( $("#topVid video:visible").prop('muted') ) {
        $("#topVid video:visible").prop('muted', true);

  } else {
    $("#topVid video:visible").prop('muted', true);

  }
});

The basic html code for this section:

CHANNEL 1960s: Jackie Kennedy at JFK's service

      <video loop onclick="this.paused? this.play() : this.pause()" >
      <source src="videos/1960s_Jackie_mourning_VERT.mp4" type="video/mp4">
      Your browser does not support the video tag.
      </video>

IDEAL SOLUTION: PAUSING AS SOON AS THE 'NEXT' BUTTON IS PRESSED ultimately, I realized that muting is not the ideal solution because of performance issues (the hidden video will keep playing even without the sound). What is the best way to pause (instead of muting) the video as soon with this 'next' button pressed? There is already inline javascript code on the html that will play and pause if the user clicks on it but I am not sure how add this other part, where it pauses if the next button is pressed and it can be played once it is visible.

I tried this to make the video pause but it did not work

$("#nextButtonTop, #prevButtonTop ").click( function (){
  if ($('.topVid.video').is(":hidden")) {
      $('.topVid.video').pause();
  }
});

I tried this as well and nothing

$('video').each(function(){
    if ($(this).is(":in-viewport")) {
        $(this)[0].play();
    } else {
        $(this)[0].pause();
    }
})

the use of

 "this.paused ? this.play() : this.pause();"

was suggested on another answer but I am not sure how this could work given that the pausing would be triggered by clicking on another element (the 'next' button, not the video itself.

Body:
Unless your jQuery is at the end of the document, remember to wrap it in jQuery(function($) {...}).

Attach all event handlers in javaScript, not HTML. This is not essential, but allows you to see all your interactive code in a single glance.

Stay aware that .play() and .pause() are <video> element methods, not jQuery methods.

Try this :

HTML

<div class="topVid channel1960s">
    <div class="testMarqueeLeft">
        <div>CHANNEL 1960s: Jackie Kennedy at JFK's service</div>
    </div>
    <video loop> <!-- remove onclick="..." -->
        <source src="videos/1960s_Jackie_mourning_VERT.mp4" type="video/mp4" />
        Your browser does not support the video tag.
    </video>
</div>

JavaScript

jQuery(function($) {
    // Attach click handler to both <video> elements
    $('video').on('click', function() {
        this.paused? this.play() : this.pause();
    });

    // Attach click handler to top video's prev/next buttons
    $("#nextButtonTop, #prevButtonTop").on('click', function(e) {
        e.preventDefault(); // maybe not required but does no harm.
        var $video = $('.topVid video');
        if ($video.is(':hidden')) {
            $video.get(0).pause(); // .pause() is a method of the <video> element, not a jQuery method.
        }
    });
});


问:
How can i print all possible order of an array with n integers using recursion?
For example, if I have an array a=  {1, 2, 6, 10}, it should print all combinations of these 4 numbers, there should be 4! total combinations. An array of 5 integers will have a total of 5! combinations. (Different from previous versions because my number of parameters have to stay same. I am not allowed to put more than 3 paramrters in.

array a=  {1, 2, 6, 10}

{1, 2, 10, 6}

{1, 6, 2, 10}

{1, 6, 10, 2}

.

.

.

{10, 6, 2, 1}

I am trying to solve this process using Recursion, any idea how? this is the code i have for now. Can anyone who has any idea whats going on please help me?

```<code>static void permutations (int a[], int n, int p){
    if (p==n-1)
        return ;
    for (int i=p; i<n; i++){
        int b[]=new int [n];
        b[p]=a[i];
        for (int j=0; j<i; j++)
            b[j]=a[j];
            for (int k =i+1; k<n; k++)
                b[k]=a[k];
        System.out.println(Arrays.toString(b));
        return permutations(b, n, p+1);
    }
}
</code>```

答:
best way to solve your problem to use Permutations concept in Algebra it's very useful way to get all possible combinations of a set.

you should also have knowledge in possibilities to solve this problem:

in this set {1, 2, 6, 10} element 1 has a k-Permutations which is 3

and this Permutations is : {2, 1, 6, 10},{6, 2, 1, 10},{10, 2, 6, 1}.

also element 2 has k-Permutations which is 2

2 Permutations is : {1, 6, 2, 10},{1, 10, 6, 2}.

element 6 has a k-Permutations which is 1

6 Permutations is : {1, 2, 10, 6}.

finally the total possible Permutations for all elements in set : 3 * 2 * 1 = 6.

simple algorithm to print all possible Permutations:

```<code>   int[] num = {1,2,6,10};
   int[] a = num.clone();
   ArrayList<String> combs = new ArrayList<String>();
   int temp;
    for(int i=0; i < num.length-1; i++){
        for(int j=i+1; j < num.length; j++){
             temp = a[i];
             a[i] = a[j];
             a[j] = temp;
            String obj = Arrays.toString(a);
            if(!combs.contains(obj)){
               combs.add(obj);
            }
             a = num.clone();
        }
    }
    System.out.println("All possible order Combinations:");
    for(String obj : combs){
        System.out.println(obj);
    }
</code>```

output:

```<code>All possible order Combinations:
[2, 1, 6, 10]
[6, 2, 1, 10]
[10, 2, 6, 1]
[1, 6, 2, 10]
[1, 10, 6, 2]
[1, 2, 10, 6]
</code>```

hope this would help.

Body:
For example, if I have an array a=  {1, 2, 6, 10}, it should print all combinations of these 4 numbers, there should be 4! total combinations. An array of 5 integers will have a total of 5! combinations. (Different from previous versions because my number of parameters have to stay same. I am not allowed to put more than 3 paramrters in.

array a=  {1, 2, 6, 10}

{1, 2, 10, 6}

{1, 6, 2, 10}

{1, 6, 10, 2}

.

.

.

{10, 6, 2, 1}

I am trying to solve this process using Recursion, any idea how? this is the code i have for now. Can anyone who has any idea whats going on please help me?

static void permutations (int a[], int n, int p){
    if (p==n-1)
        return ;
    for (int i=p; i<n; i++){
        int b[]=new int [n];
        b[p]=a[i];
        for (int j=0; j<i; j++)
            b[j]=a[j];
            for (int k =i+1; k<n; k++)
                b[k]=a[k];
        System.out.println(Arrays.toString(b));
        return permutations(b, n, p+1);
    }
}

Body:
best way to solve your problem to use Permutations concept in Algebra it's very useful way to get all possible combinations of a set.

you should also have knowledge in possibilities to solve this problem:

in this set {1, 2, 6, 10} element 1 has a k-Permutations which is 3

and this Permutations is : {2, 1, 6, 10},{6, 2, 1, 10},{10, 2, 6, 1}.

also element 2 has k-Permutations which is 2

2 Permutations is : {1, 6, 2, 10},{1, 10, 6, 2}.

element 6 has a k-Permutations which is 1

6 Permutations is : {1, 2, 10, 6}.

finally the total possible Permutations for all elements in set : 3 * 2 * 1 = 6.

simple algorithm to print all possible Permutations:

   int[] num = {1,2,6,10};
   int[] a = num.clone();
   ArrayList<String> combs = new ArrayList<String>();
   int temp;
    for(int i=0; i < num.length-1; i++){
        for(int j=i+1; j < num.length; j++){
             temp = a[i];
             a[i] = a[j];
             a[j] = temp;
            String obj = Arrays.toString(a);
            if(!combs.contains(obj)){
               combs.add(obj);
            }
             a = num.clone();
        }
    }
    System.out.println("All possible order Combinations:");
    for(String obj : combs){
        System.out.println(obj);
    }

output:

All possible order Combinations:
[2, 1, 6, 10]
[6, 2, 1, 10]
[10, 2, 6, 1]
[1, 6, 2, 10]
[1, 10, 6, 2]
[1, 2, 10, 6]

hope this would help.


问:
I need to write an automation script in Postman to validate that GET would bring only "account" that has code1 & code2 in one record
I am new to Postman and I am trying to write automated validation for GET </p>

<p>I have multiple records saved in DB and I need to write an automation script in  Postman to validate that GET would bring  only "account" that has code1 & code2  in one record like in an example  below </p>

```<code>"account": [
             {    {
                    "system":" 'system1",
                     "code": "code1"
                  },
                  {
                    "system": "sytem1",
                    "code": "code2"
                  }]

Tried  var obj = responseData.entry[i];
       tests["Specialty"]= obj.account[0].code ===  "code1"&"code2";
        and it is not working
</code>```

答:
You can try this:

```<code>var obj = responseData.entry[i];
var account;
if (obj.account[0].code ===  "code1" && obj.account[1].code = "code2"){
    account = obj.account;
}
tests["Specialty", account] = true;
</code>```

Hope this helps

Body:
I am new to Postman and I am trying to write automated validation for GET

I have multiple records saved in DB and I need to write an automation script in  Postman to validate that GET would bring  only "account" that has code1 & code2  in one record like in an example  below

"account": [
             {    {
                    "system":" 'system1",
                     "code": "code1"
                  },
                  {
                    "system": "sytem1",
                    "code": "code2"
                  }]

Tried  var obj = responseData.entry[i];
       tests["Specialty"]= obj.account[0].code ===  "code1"&"code2";
        and it is not working

Body:
You can try this:

var obj = responseData.entry[i];
var account;
if (obj.account[0].code ===  "code1" && obj.account[1].code = "code2"){
    account = obj.account;
}
tests["Specialty", account] = true;

Hope this helps


问:
MS Access Error '2110' Can't move the focus to the control
I'm a beginner using MS Access 2016.
I have a save button on a form that does some last minute input validation that is meant to be very direct and helpful to the end-user. I'm using a series of textboxes to step through the validation when they click the save button, this way they can complete then entire form and if there is an error it takes them directly to that field with the error.

My code appears to work,
it detects an error,
sets the focus to the text179,
sees there is an error in the JobNo field,
gives a message saying "Please enter a 5 digit job number"and
sets the focus to JobNo.
Then and only then, do I get a second prompt saying there is an error.
But why is it saying it can't set the focus to text179 when it clearly already has done so and should no longer be trying at that point?

Here is my code:
Private Sub SaveRecord_GotFocus()
    If Me.JobNo & "" Like "#####" And Me.ItemNo & "" <> "" Then
        Exit Sub
        Else
        Me.Text179.SetFocus
    End If
End Sub
Private Sub Text179_GotFocus()
    If Me.JobNo & "" Like "#####" Then
        Me.Text181.SetFocus
        Exit Sub
        Else
        MsgBox "Please enter a 5 digit Job Number", vbOKOnly
        Cancel = True
        Me.JobNo.SetFocus
        Exit Sub
    End If
End Sub

Error:
Run-time error '2110':
Microsoft Access can't move the focus to the control Text179.

Let me know if any additional information is needed.

答:
I was able to solve this with a much cleaner method, using just VB code without trying to use setfocus. It just took me a while to figure out how to nest my if statements correctly since I'm new with Access/VB. I'll post the code below.

Private Sub SaveRecord_GotFocus()
    If Me.JobNo & "" Like "#####" Then
    GoTo Eval_ItemNo
        Else
    MsgBox "Please enter a 5 digit Job Number", vbOKOnly
    Me.JobNo.SetFocus
    Exit Sub
    End If
Eval_ItemNo:
    If Me.ItemNo & "" <> "" Then
    GoTo Eval_QtyFinished
    Else
    MsgBox "Please enter an Item Number", vbOKOnly
        Me.ItemNo.SetFocus
    Exit Sub
    End If
Eval_QtyFinished:
    If Me.QtyFinished & "" <> "" Then
    GoTo Eval_WorkCenter
    Else
    MsgBox "Please enter a Qty Finished", vbOKOnly
        Me.QtyFinished.SetFocus
    Exit Sub
    End If
Eval_WorkCenter:
    If Me.WorkCenter & "" <> "" Then
    Exit Sub
    Else
    MsgBox "Please enter a WorkCenter", vbOKOnly
        Me.WorkCenter.SetFocus
    End If
End Sub

OwnerDisplayName: NateV


问:
How to generate unique request id for each log4j request
I am printing log of request and response by using log4j. I want to assign a unique ID to each request and same ID to its response, there are multiple requests so it will be easier for me to identify each request and response.

This is what i was using, but its not working. Its updating the UDID on response as well.

```<code>    public void logRequestObject(HttpServletRequest httprequest){
    uniqueID= UUID.randomUUID().toString();
    logger.info("Log4J - "+ "Request: requestId= "+ uniqueID+  ",Headers= "+ map);
}

    public void logResponseObject(HttpServletResponse httpResponse){
      logger.info("Log4J - "+ "Response: ,requestId= " + uniqueID + " ,responseTime= " + " totalTime= "+ totalTime);
}
</code>```

Then i came to know that log4j provides a way to record unique ID to each request.

I have read many posts on stackoverflow, but still unable to understand it.

This is my properties files.

```<code># Root logger option
log4j.rootLogger=INFO, stdout, file, CATALINA

# Catalina

    log4j.appender.CATALINA=org.apache.log4j.RollingFileAppender
    log4j.appender.CATALINA.File=${catalina.home}/logs/catalina.out
    log4j.appender.CATALINA.MaxFileSize=10MB
    log4j.appender.CATALINA.MaxBackupIndex=5
    log4j.appender.CATALINA.layout=org.apache.log4j.PatternLayout
    log4j.appender.CATALINA.layout.ConversionPattern=%d{dd.MM.yyyy HH:mm:ss}  %X{RequestId} %p-%c{1}: [%m]%n
    log4j.appender.CATALINA.Append=true
    log4j.appender.CATALINA.Encoding=UTF-8
</code>```

答:
You can consider using Context Map Lookup, here's a brief example:

Java code sinppet:

```<code>public static void main(String[] args) {
  String uuid = "1";
  logRequestObject("http request", uuid);
  logResponseObject("http response");

  uuid = "2";
  logRequestObject("http request", uuid);
  logResponseObject("http response");
}

static void logRequestObject(Object httpRequest, String uniqueID) {
  ThreadContext.put("uniqueID", uniqueID); // Update uniqueID before logging request and response
  logger.info("This is {}", httpRequest);
}

static void logResponseObject(Object httpResponse) {
  logger.info("This is {}", httpResponse);
}
</code>```

log4j.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern='%level -> %msg %X{uniqueID}%n'/> <!-- Get uniqueID from ThreadContext -->
        </Console>
    </Appenders>

    <Loggers>
        <Root level="DEBUG">
            <AppenderRef ref="STDOUT"/>
        </Root>
    </Loggers>
</Configuration>
</code>```

Output

```<code>INFO -> This is http request 1
INFO -> This is http response 1
INFO -> This is http request 2
INFO -> This is http response 2
</code>```

I hope it helps :)

Body:
I am printing log of request and response by using log4j. I want to assign a unique ID to each request and same ID to its response, there are multiple requests so it will be easier for me to identify each request and response.

This is what i was using, but its not working. Its updating the UDID on response as well.

    public void logRequestObject(HttpServletRequest httprequest){
    uniqueID= UUID.randomUUID().toString();
    logger.info("Log4J - "+ "Request: requestId= "+ uniqueID+  ",Headers= "+ map);
}

    public void logResponseObject(HttpServletResponse httpResponse){
      logger.info("Log4J - "+ "Response: ,requestId= " + uniqueID + " ,responseTime= " + " totalTime= "+ totalTime);
}

Then i came to know that log4j provides a way to record unique ID to each request.

I have read many posts on stackoverflow, but still unable to understand it.

This is my properties files.

# Root logger option
log4j.rootLogger=INFO, stdout, file, CATALINA

# Catalina

    log4j.appender.CATALINA=org.apache.log4j.RollingFileAppender
    log4j.appender.CATALINA.File=${catalina.home}/logs/catalina.out
    log4j.appender.CATALINA.MaxFileSize=10MB
    log4j.appender.CATALINA.MaxBackupIndex=5
    log4j.appender.CATALINA.layout=org.apache.log4j.PatternLayout
    log4j.appender.CATALINA.layout.ConversionPattern=%d{dd.MM.yyyy HH:mm:ss}  %X{RequestId} %p-%c{1}: [%m]%n
    log4j.appender.CATALINA.Append=true
    log4j.appender.CATALINA.Encoding=UTF-8

Body:
You can consider using Context Map Lookup, here's a brief example:

Java code sinppet:

public static void main(String[] args) {
  String uuid = "1";
  logRequestObject("http request", uuid);
  logResponseObject("http response");

  uuid = "2";
  logRequestObject("http request", uuid);
  logResponseObject("http response");
}

static void logRequestObject(Object httpRequest, String uniqueID) {
  ThreadContext.put("uniqueID", uniqueID); // Update uniqueID before logging request and response
  logger.info("This is {}", httpRequest);
}

static void logResponseObject(Object httpResponse) {
  logger.info("This is {}", httpResponse);
}

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern='%level -> %msg %X{uniqueID}%n'/> <!-- Get uniqueID from ThreadContext -->
        </Console>
    </Appenders>

    <Loggers>
        <Root level="DEBUG">
            <AppenderRef ref="STDOUT"/>
        </Root>
    </Loggers>
</Configuration>

Output

INFO -> This is http request 1
INFO -> This is http response 1
INFO -> This is http request 2
INFO -> This is http response 2

I hope it helps :)


问:
Override non-dynamic class delaration
With new Xcode 8.3, I get the error:

Cannot override a non-dynamic class declaration from an extension

from the line of code:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
</code>```

How I can avoid this warning?

答:
which means, you can't not override like super class delegate method in extension.
the way you can do is mv extension override method to subclass declare.</p>
```<code>final class DEMO, UITableViewDataSource, UITableViewDelegate {

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
         return sectionHeader
    }

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
         return 40
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Override non-dynamic class delaration

Body:
With new Xcode 8.3, I get the error:

Cannot override a non-dynamic class declaration from an extension

from the line of code:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

How I can avoid this warning?

Body:
which means, you can't not override like super class delegate method in extension.
the way you can do is mv extension override method to subclass declare.

final class DEMO, UITableViewDataSource, UITableViewDelegate {

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
         return sectionHeader
    }

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
         return 40
    }

}


问:
Click on a href in VBA
I want to click on the following link

I have the class name and the line code I was trying ot use is the following:

```<code>objIE.document.getElementByClassName("msDataText searchLink").Click
</code>```

This may well be a very basic question.. any guidance

Thanks a lot

答:
Not sure if it is a duplicate question.
A good function GetHTTPResult is already available from the link. You need to just pass the url for the GET request to fetch the data. For POST request (this function will not work), you need to make a POST request with postdata.

Also there is a sample for XMLHttpRequest at link

```<code>Function GetHTTPResult(sURL As String) As String
    Dim XMLHTTP As Variant, sResult As String

    Set XMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    XMLHTTP.Open "GET", sURL, False
    XMLHTTP.Send
    Debug.Print "Status: " & XMLHTTP.Status & " - " & XMLHTTP.StatusText
    sResult = XMLHTTP.ResponseText
    Debug.Print "Length of response: " & Len(sResult)
    Set XMLHTTP = Nothing
    GetHTTPResult = sResult
End Function
</code>```

Title: Click on a href in VBA

Body:
I want to click on the following link

I have the class name and the line code I was trying ot use is the following:

objIE.document.getElementByClassName("msDataText searchLink").Click

This may well be a very basic question.. any guidance

Thanks a lot

Body:
Not sure if it is a duplicate question.
A good function GetHTTPResult is already available from the link. You need to just pass the url for the GET request to fetch the data. For POST request (this function will not work), you need to make a POST request with postdata.

Also there is a sample for XMLHttpRequest at link

Function GetHTTPResult(sURL As String) As String
    Dim XMLHTTP As Variant, sResult As String

    Set XMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    XMLHTTP.Open "GET", sURL, False
    XMLHTTP.Send
    Debug.Print "Status: " & XMLHTTP.Status & " - " & XMLHTTP.StatusText
    sResult = XMLHTTP.ResponseText
    Debug.Print "Length of response: " & Len(sResult)
    Set XMLHTTP = Nothing
    GetHTTPResult = sResult
End Function


问:
Laravel: WhereNull, OrWhere, is ignoring WhereRaw
In my controller I am using Laravels WhereNull, OrWhere and WhereRaw in DB Query.  It is pulling in all the results but the problem is it looks like it is pulling in everything and ignoring the last Where clause.  I have used this in a different method on other controllers and it works fine.  Is there a specific order or something I am missing?

Doesn't Work (Ignores WhereRaw and shows all results)

```<code>$lists = DB::table('statuses')
                    ->whereNull('company_id')
                    ->orWhere('company_id', '=', Auth::user()->company_id)
                    ->whereRaw("FIND_IN_SET('Task',assigned_to)")
                    ->get();
</code>```

This works in other controllers used as a different method without the whereRaw:

```<code>return Status::whereNull('company_id')->orWhere('company_id', '=', Auth::user()->company_id)
                    ->orderBy('created_at', 'asc')
                    ->get();
</code>```

Sample DB

Source link: https://laravel.com/docs/5.3/queries#where-clauses

答:
Use DB::raw instead of whereRaw

```<code>->where(DB::raw("FIND_IN_SET('Task',assigned_to)"))
</code>```

Body:
In my controller I am using Laravels WhereNull, OrWhere and WhereRaw in DB Query.  It is pulling in all the results but the problem is it looks like it is pulling in everything and ignoring the last Where clause.  I have used this in a different method on other controllers and it works fine.  Is there a specific order or something I am missing?

Doesn't Work (Ignores WhereRaw and shows all results)

$lists = DB::table('statuses')
                    ->whereNull('company_id')
                    ->orWhere('company_id', '=', Auth::user()->company_id)
                    ->whereRaw("FIND_IN_SET('Task',assigned_to)")
                    ->get();

This works in other controllers used as a different method without the whereRaw:

return Status::whereNull('company_id')->orWhere('company_id', '=', Auth::user()->company_id)
                    ->orderBy('created_at', 'asc')
                    ->get();

Sample DB

Source link: https://laravel.com/docs/5.3/queries#where-clauses

Body:
Use DB::raw instead of whereRaw

->where(DB::raw("FIND_IN_SET('Task',assigned_to)"))


问:
How do I reload UITableView data when the app comes to foreground? (Xcode 8.3 / Swift 3)
I have the following methods in my "ViewController" class to populate custom cells in a UITableView from a GET API call. This works fine when app first loads.

```<code>//ViewController
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    loadDataInUITableViewCell()
}

func loadDataInUITableViewCell() {
        apiCentral.sharedInstance.fetchData() {
        result in
        guard result.error == nil else {
            self.handleError(result.error!)
            return
        }
        if let fetchedData = result.value {
            self.data = fetchedData
        }
        self.messagesTableView.reloadData()
    }
}
</code>```

How do I refresh the data when the app comes to the foreground? Well, I added the following to AppDelegate to run the "loadDataInUITableViewCell" method so that the data reloads.

```<code>//AppDelegate
let mainViewController = ViewController()

func applicationWillEnterForeground(_ application: UIApplication) {
    mainViewController.loadDataInUITableViewCell()
}
</code>```

ISSUE: The above mechanism works fine however, I get the following error when the app comes to the foreground.

"fatal error: unexpectedly found nil while unwrapping an Optional value"

The issue seems to be happening at "self.messagesTableView.reloadData()" line of code. I'm using Xcode 8.3 and coding in Swift 3. Any guidance would be appreciated. Thank you.

答:
Solutions 1. In appdelegate:

```<code>   //AppDelegate
    let mainViewController : ViewController?

    func applicationWillEnterForeground(_ application: UIApplication) {
        mainViewController.loadDataInUITableViewCell()
    }
</code>```

And in Your viewcontroller:

```<code>//ViewController
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    (UIApplication.sharedApplication().delegate as! AppDelegate).mainViewController  = self
    loadDataInUITableViewCell()
}
</code>```

Solutions  2.

listen in viewcontroller:

```<code>    //ViewController
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(ViewController.loadDataInUITableViewCell(), name: UIApplicationWillEnterForegroundNotification, object: nil)
    loadDataInUITableViewCell()
}
</code>```

Body:
I have the following methods in my "ViewController" class to populate custom cells in a UITableView from a GET API call. This works fine when app first loads.

//ViewController
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    loadDataInUITableViewCell()
}

func loadDataInUITableViewCell() {
        apiCentral.sharedInstance.fetchData() {
        result in
        guard result.error == nil else {
            self.handleError(result.error!)
            return
        }
        if let fetchedData = result.value {
            self.data = fetchedData
        }
        self.messagesTableView.reloadData()
    }
}

How do I refresh the data when the app comes to the foreground? Well, I added the following to AppDelegate to run the "loadDataInUITableViewCell" method so that the data reloads.

//AppDelegate
let mainViewController = ViewController()

func applicationWillEnterForeground(_ application: UIApplication) {
    mainViewController.loadDataInUITableViewCell()
}

ISSUE: The above mechanism works fine however, I get the following error when the app comes to the foreground.

"fatal error: unexpectedly found nil while unwrapping an Optional value"

The issue seems to be happening at "self.messagesTableView.reloadData()" line of code. I'm using Xcode 8.3 and coding in Swift 3. Any guidance would be appreciated. Thank you.

Body:
Solutions 1. In appdelegate:

   //AppDelegate
    let mainViewController : ViewController?

    func applicationWillEnterForeground(_ application: UIApplication) {
        mainViewController.loadDataInUITableViewCell()
    }

And in Your viewcontroller:

//ViewController
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    (UIApplication.sharedApplication().delegate as! AppDelegate).mainViewController  = self
    loadDataInUITableViewCell()
}

Solutions  2.

listen in viewcontroller:

    //ViewController
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(ViewController.loadDataInUITableViewCell(), name: UIApplicationWillEnterForegroundNotification, object: nil)
    loadDataInUITableViewCell()
}


问:
If is not working in javascript-meteor
I have a piece of code on click event for set a session variable. The console log in working in event click, but it doesn't go inside if condition:</p>

```<code>      'click .family': function(event) {
        event.preventDefault();
        console.log('in change'); // result in change
        $("#btnFamily").html(event.target.text);

        var role = event.target.text;
        console.log('role',role); //result role  Fils

         if(role == "Fils"){
             console.log('here in son'); //never comes here
             Session.set('family', "Son");  //never comes here
         }

    },
</code>```

答:
if you are using Javascript then use role.trim()=='Fils' and if using jQuery then use $.trim(role)=='Fils'

you can use triple equal(===) operator for strict validation

i think this will be helpful..

Title: If is not working in javascript-meteor

Body:
I have a piece of code on click event for set a session variable. The console log in working in event click, but it doesn't go inside if condition:

      'click .family': function(event) {
        event.preventDefault();
        console.log('in change'); // result in change
        $("#btnFamily").html(event.target.text);

        var role = event.target.text;
        console.log('role',role); //result role  Fils

         if(role == "Fils"){
             console.log('here in son'); //never comes here
             Session.set('family', "Son");  //never comes here
         }

    },


问:
Can I embed a twitter feed in my email?
I'm about to send out an email campaign to my clients. The email will be sent in HTML format, and I wanted to embed a twitter feed in my email, similar to the twitter widgets you see embedded in blogs and websites everywhere. When I copy and paste the code generated through the twitter website, my email doesn't render anything :(

Any ideas if this is possible? Thanks! Here's the code twitter generated:

答: There is no standard for HTML email, and most email clients sensibly reject JavaScript.  I recommend you link to a page on your web site.</p>

Title: Can I embed a twitter feed in my email?


问:
Possible to outsource computations to AWS and utilize results locally?
I'm working on a robot that uses a CNN that needs much more memory than my embedded computer (Jetson TX1) can handle. I was wondering if it would be possible (with an extremely low latency connection) to outsource the heavy computations to EC2 and send the results back to the be used in a Python script. If this is possible, how would I go about it and what would the latency look like (not computations, just sending to and from). </p>

答:
Possible: of course it is.

You can use any kind of RPC to implement this. HTTPS requests, xml-rpc, raw UDP packets, and many more. If you're more interested in latency and small amounts of data, then something UDP based could be better than TCP, but you'd need to build extra logic for ordering the messages and retrying the lost ones. Alternatively something like Zeromq could help.

As for the latency: only you can answer that, because it depends on where you're connecting from. Start up an instance in the region closest to you and run ping, or mtr against it to find out what's the roundtrip time. That's the absolute minimum you can achieve. Your processing time goes on top of that.


问:
Should i be using the uvm_component/object_utils macros
I see a lot of articles which talk about whether you should be using field macros.

General guideline is:

```<code>`uvm_do... macro:
</code>```

Can be used, but try to avoid if you are lazy.

```<code>`uvm_field... macro:
</code>```

Avoid like the plague.

Sure, people also tell not to use

```<code>`uvm_component_param_utils...
`uvm_object_param_utils...
</code>```

But i cannot seem to find what anyone thinks about the

```<code>`uvm_component_utils...
`uvm_object_utils...
</code>```

Should they be avoided? Or they can be used without much issues?

Thanks :)

答: The *_utils macros do not introduce any performance penalties. They do save some typing and may reduce typographical errors, but I wish people would learn the code behind the macros before using them. See http://go.mentor.com/mcem</p>

Body:
I see a lot of articles which talk about whether you should be using field macros.

General guideline is:

`uvm_do... macro:

Can be used, but try to avoid if you are lazy.

`uvm_field... macro:

Avoid like the plague.

Sure, people also tell not to use

`uvm_component_param_utils...
`uvm_object_param_utils...

But i cannot seem to find what anyone thinks about the

`uvm_component_utils...
`uvm_object_utils...

Should they be avoided? Or they can be used without much issues?

Thanks :)


问:
Katana or Microsoft.Owin.HttpListener for Servicing both http and https in a single service
I'm having trouble in understanding the way to implement both https and http in a single service.

I have a OWIN hosted Web API. Currently it serves http only. I like to implement ssl for it. Creating two http server instances does the job but this StackOverflow question says that Katana or Microsoft.Owin.HttpListener can be used to accomplish this purpose.

How is that possible using Microsoft.Owin.HttpListener?

答:
Start by getting https set up: https://github.com/aspnet/AspNetKatana/wiki/Selfhosting

Then you just need to add both the http and the https url when you start the service:
https://github.com/aspnet/AspNetKatana/blob/f3a8d848b7548e62d52737efa0a4fc9cf6c6cedf/src/Microsoft.Owin.Hosting/StartOptions.cs#L39
https://github.com/aspnet/AspNetKatana/blob/f3a8d848b7548e62d52737efa0a4fc9cf6c6cedf/src/Microsoft.Owin.Hosting/WebApp.cs#L34

What do you call today to set the url?


问:
Pythonic way to check if: all elements evaluate to False -OR- all elements evaluate to True
I want the results of the function to be:

All values evaluate to False (None, 0, empty string) -> True

All values evaluate to True -> True

Every other case -> False

This is my try at it:

```<code>>>> def consistent(x):
...  x_filtered = filter(None, x)
...  return len(x_filtered) in (0, len(x))
...
>>> consistent((0,1))
False
>>> consistent((1,1))
True
>>> consistent((0,0))
True
</code>```

[Bonus]

What should this function be named?

答:
```<code>def AllTheSame(iterable):
    return any(iterable) is all(iterable)
</code>```

Body:
I want the results of the function to be:

All values evaluate to False (None, 0, empty string) -> True

All values evaluate to True -> True

Every other case -> False

This is my try at it:

>>> def consistent(x):
...  x_filtered = filter(None, x)
...  return len(x_filtered) in (0, len(x))
...
>>> consistent((0,1))
False
>>> consistent((1,1))
True
>>> consistent((0,0))
True

[Bonus]

What should this function be named?


答:
I think it's certainly possible. You would need some scripts or a web server to transfer data to and from. Here is how I think you might achieve it:

Send all your training data to an EC2 instance

Train your CNN

Save the weights and/or any other generated parameters you may need

Construct the CNN on your embedded system and input the weights
from the EC2 instance. Since you won't be needing to do any training
here and won't need to load in the training set, the memory usage
will be minimal.

Use your embedded device to predict whatever you may need

It's hard to give you an exact answer on latency because you haven't given enough information. The exact latency is highly dependent on your hardware, internet connection, amount of data you'd be transferring, software, etc. If you're only training once on an initial training set, you only need to transfer your weights once and thus latency will be negligible. If you're constantly sending data and training, or doing predictions on the remote server, latency will be higher.

Title: Possible to outsource computations to AWS and utilize results locally?

Body: I'm working on a robot that uses a CNN that needs much more memory than my embedded computer (Jetson TX1) can handle. I was wondering if it would be possible (with an extremely low latency connection) to outsource the heavy computations to EC2 and send the results back to the be used in a Python script. If this is possible, how would I go about it and what would the latency look like (not computations, just sending to and from).


问:
How to calculate number of swaps in permutations?
I have this code below, I would like to know how to calculate the number of swaps. I used a count variable to figure it out, but I was getting different number than the computer. I figure the number of swaps would be 2 * (n - 1)(n - 2)...(n - n + 1). For n == 4, the computer got 128, and I got 48. What am I doing wrong?</p>

```<code>public void permute(int n) {
        if (n == 1) {
            printOutPut();
        }
        for (int i = 1; i <= n; i++){
          swap(i, n);
          permute1(n-1);
          swap(i, n);
        }
    }
</code>```

答:
The code  defines a recursion:

```<code>num_swaps(0) = 0
num_swaps(i) = i * (num_swaps(i - 1) + 2)
</code>```

or with more math-like symbols:

```<code>s_{n+1} = (n + 1) (s_n + 2)
s_0 = 0
s_1 = 2
s_2 = 8
s_3 = 30
s_4 = 128
</code>```

You can probably solve that recursion for a general n using techniques from maths, but this verifies that the computer is right

Edit: I was trying to find a solution for general n, ended up on wolfram alpha and the solution presented had incomplete gamma functions and stuff. So, don't expect the calculation to be easy!

Body:
I have this code below, I would like to know how to calculate the number of swaps. I used a count variable to figure it out, but I was getting different number than the computer. I figure the number of swaps would be 2 * (n - 1)(n - 2)...(n - n + 1). For n == 4, the computer got 128, and I got 48. What am I doing wrong?

public void permute(int n) {
        if (n == 1) {
            printOutPut();
        }
        for (int i = 1; i <= n; i++){
          swap(i, n);
          permute1(n-1);
          swap(i, n);
        }
    }

Body:
The code  defines a recursion:

num_swaps(0) = 0
num_swaps(i) = i * (num_swaps(i - 1) + 2)

or with more math-like symbols:

s_{n+1} = (n + 1) (s_n + 2)
s_0 = 0
s_1 = 2
s_2 = 8
s_3 = 30
s_4 = 128

You can probably solve that recursion for a general n using techniques from maths, but this verifies that the computer is right

Edit: I was trying to find a solution for general n, ended up on wolfram alpha and the solution presented had incomplete gamma functions and stuff. So, don't expect the calculation to be easy!


问:
Ajax query for JSON data not returning data
I'm trying to use World Bank's API to obtain some data. This is how to query their database. Basically to query a country's information, I would need to go to this url:

```<code>http://api.worldbank.org/countries/"alpha2Code of the country"
</code>```

In my code here (Link to CodePen code.) I use use the alpha2Code from a previous query to add to the World Bank query's URL. Here's the method:

```<code>getDetails(alpha2Code) {
  this.load('http://api.worldbank.org/countries/'+alpha2Code)
    .then((countryDetails) => {
      this.generateOverlay(countryDetails);
    });
},
</code>```

the load() method is defined here:

```<code>load(url, type = 'json') {
  return $.ajax({
    dataType: type,
    url: url,
  });
},
</code>```

According to World Bank's basic calling format, I would need to add

```<code>format=json
</code>```

in order to receive response in JSON. Somehow I don't think it's actually obtaining anything from WorldBank.

The query to World Bank is suppose to give me details to put into the overlay that covers the country flags after a click.

Thank you in advance for the help!

答:
You need to pass the desired result format in the query. For example, to query INDIA, you would need to change the url to :

```<code>http://api.worldbank.org/countries/IN?format=json
</code>```

The resulting data received is like:

```<code>[{"page":1,"pages":1,"per_page":"50","total":1},[{"id":"IND","iso2Code":"IN","name":"India","region":{"id":"SAS","value":"South Asia"},"adminregion":{"id":"SAS","value":"South Asia"},"incomeLevel":{"id":"LMC","value":"Lower middle income"},"lendingType":{"id":"IBD","value":"IBRD"},"capitalCity":"New Delhi","longitude":"77.225","latitude":"28.6353"}]]
</code>```

The default output is in XML format. Hence your code may not be working.

Body:
I'm trying to use World Bank's API to obtain some data. This is how to query their database. Basically to query a country's information, I would need to go to this url:

http://api.worldbank.org/countries/"alpha2Code of the country"

In my code here (Link to CodePen code.) I use use the alpha2Code from a previous query to add to the World Bank query's URL. Here's the method:

getDetails(alpha2Code) {
  this.load('http://api.worldbank.org/countries/'+alpha2Code)
    .then((countryDetails) => {
      this.generateOverlay(countryDetails);
    });
},

the load() method is defined here:

load(url, type = 'json') {
  return $.ajax({
    dataType: type,
    url: url,
  });
},

According to World Bank's basic calling format, I would need to add

format=json

in order to receive response in JSON. Somehow I don't think it's actually obtaining anything from WorldBank.

The query to World Bank is suppose to give me details to put into the overlay that covers the country flags after a click.

Thank you in advance for the help!

Body:
You need to pass the desired result format in the query. For example, to query INDIA, you would need to change the url to :

http://api.worldbank.org/countries/IN?format=json

The resulting data received is like:

[{"page":1,"pages":1,"per_page":"50","total":1},[{"id":"IND","iso2Code":"IN","name":"India","region":{"id":"SAS","value":"South Asia"},"adminregion":{"id":"SAS","value":"South Asia"},"incomeLevel":{"id":"LMC","value":"Lower middle income"},"lendingType":{"id":"IBD","value":"IBRD"},"capitalCity":"New Delhi","longitude":"77.225","latitude":"28.6353"}]]

The default output is in XML format. Hence your code may not be working.


问:
is replaceWith() duplicated with replaceAll()
I am learning jQuery,
get to know that some functions have liken function.
for example.
replaceWith() Vs. replaceAll().

according to their grammar defintion, just rotate the order of content and selected element.

similarily, append(), appendTo(), prepend(), prependTo(), after(), insertAfter(), before(), insertBefore().

I am newer in programming, can't really understand why there are many 'same' functions which have been put here for taking 'same' effect.

Then, why don't create just one or two (anyway, less, not many look like same) comprehensive and decent function.

答:
Actually, I think you're misleading with the documentation of JQuery.

Certains functions have the same effect, but can be called differently.

Let's take replaceWith() and replaceAll() for examples

The only difference is that you can put the replacement wether in the selector or the function's parameter.

JQuery is meant to be a toolbox that serves the most, and the most means that every programmers have different way to behave and they could appreciate more using a function that you find useless.
Furthermore, if those functions exists in two types, it's that it's a commonly wanted behavior of them for purposal of readability and/or usability within certains architectures.


问:
Spring Cloud Stream Dispatcher has no subscribers

Spring Cloud Stream Dispatcher has no subscribers Error.

After a successful spring boot container start up we need to put few notification messages on a Kafka topic and several of our microservices does same function and for this reason we wrote a common jar that contains out put channel definitions and dispatch utils. And the functionality works as expected as long as we invoke the util right after the SpringApplication.run call.

Following is one of our microservices Application class sample.

```<code>@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context =SpringApplication.run(Application.class, args);
        context.getBean(SchedulerConsumerUtils.class).registerOrRestartConsumerJobs();
    }
}
</code>```

The above set up works as expected, however this puts unnecessary burden the developer to write the boiler template code on every microservice. So to avoid this, we wrote an Aspect implementation to do the same function, however with our aspect approach we are running into the following error.

org.springframework.context.ApplicationContextException: Failed to start bean 'outputBindingLifecycle'; nested exception is org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'schedulertestsvcs:dev:1180.scheduledJobExecutionResponseOutput'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers

We tried several approaches like Spring SmartLifeCycle to get a handle on all Kafka Output/Input channel startup completion but all of them are running into the same error.

Following is our Aspect implementation on org.springframework.boot.SpringApplication.run(..)

```<code>@Aspect
@Component
public class SchedulerConsumerAspect {

    @Autowired
    protected ApplicationContext applicationContext;
    @AfterReturning(value = "execution(* org.springframework.boot.SpringApplication.run(..))",returning = "result")
    public void afterConsumerApplicationStartup(JoinPoint pjp, Object result) throws Throwable {
        if(result!=null){
            ConfigurableApplicationContext context=(ConfigurableApplicationContext) result;
            if(context.containsBean("schedulerConsumerUtils")){
                //For what ever reason the following call resulting in Dispatcher has no subscribers for channel error.
                //TODO fix the above issue and enable the following call.
                context.getBean(SchedulerConsumerUtils.class).registerOrRestartConsumerJobs();
            }
        }
    }

}
</code>```

During our debug sessions, we found out org.springframework.boot.SpringApplication.run(..) Aspect was called several times during the bootstrap process. First when the aspect was called we got result value as null, after some time spring boot calls the same aspect this time result is not null. Even after getting result not null there is no grantee the component is completely initialized that's why you see a check for  context.containsBean("schedulerConsumerUtils").  However after the bean initialization we are seeing output channels are not completely bound.

What is the best way to get handle on Spring Cloud Stream Kafka output/input channel binding completion ?

Why the component invocation works fine in SpringBoot Application but not through Aspect? I struggled on this few days couldn't find the right solution. Any help greatly appreciated.

答:
I followed the suggestion from this post Spring cloud stream - send message after application initalization and used the 3rd option ApplicationRunner. The first two options didn't work for me.</p>

```<code>@Component
public class AppStartup implements ApplicationRunner {
    @Autowired
    protected ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if(applicationContext!=null){
            applicationContext.getBean(SchedulerConsumerUtils.class).registerOrRestartConsumerJobs();
        }
    }
}
</code>```

Body:
Spring Cloud Stream Dispatcher has no subscribers Error.

After a successful spring boot container start up we need to put few notification messages on a Kafka topic and several of our microservices does same function and for this reason we wrote a common jar that contains out put channel definitions and dispatch utils. And the functionality works as expected as long as we invoke the util right after the SpringApplication.run call.

Following is one of our microservices Application class sample.

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context =SpringApplication.run(Application.class, args);
        context.getBean(SchedulerConsumerUtils.class).registerOrRestartConsumerJobs();
    }
}

The above set up works as expected, however this puts unnecessary burden the developer to write the boiler template code on every microservice. So to avoid this, we wrote an Aspect implementation to do the same function, however with our aspect approach we are running into the following error.

org.springframework.context.ApplicationContextException: Failed to start bean 'outputBindingLifecycle'; nested exception is org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'schedulertestsvcs:dev:1180.scheduledJobExecutionResponseOutput'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers

We tried several approaches like Spring SmartLifeCycle to get a handle on all Kafka Output/Input channel startup completion but all of them are running into the same error.

Following is our Aspect implementation on org.springframework.boot.SpringApplication.run(..)

@Aspect
@Component
public class SchedulerConsumerAspect {

    @Autowired
    protected ApplicationContext applicationContext;
    @AfterReturning(value = "execution(* org.springframework.boot.SpringApplication.run(..))",returning = "result")
    public void afterConsumerApplicationStartup(JoinPoint pjp, Object result) throws Throwable {
        if(result!=null){
            ConfigurableApplicationContext context=(ConfigurableApplicationContext) result;
            if(context.containsBean("schedulerConsumerUtils")){
                //For what ever reason the following call resulting in Dispatcher has no subscribers for channel error.
                //TODO fix the above issue and enable the following call.
                context.getBean(SchedulerConsumerUtils.class).registerOrRestartConsumerJobs();
            }
        }
    }

}

During our debug sessions, we found out org.springframework.boot.SpringApplication.run(..) Aspect was called several times during the bootstrap process. First when the aspect was called we got result value as null, after some time spring boot calls the same aspect this time result is not null. Even after getting result not null there is no grantee the component is completely initialized that's why you see a check for  context.containsBean("schedulerConsumerUtils").  However after the bean initialization we are seeing output channels are not completely bound.

What is the best way to get handle on Spring Cloud Stream Kafka output/input channel binding completion ?

Why the component invocation works fine in SpringBoot Application but not through Aspect? I struggled on this few days couldn't find the right solution. Any help greatly appreciated.

Body:
I followed the suggestion from this post Spring cloud stream - send message after application initalization and used the 3rd option ApplicationRunner. The first two options didn't work for me.

@Component
public class AppStartup implements ApplicationRunner {
    @Autowired
    protected ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if(applicationContext!=null){
            applicationContext.getBean(SchedulerConsumerUtils.class).registerOrRestartConsumerJobs();
        }
    }
}


问:
Android Opengl ES dark pixels on edge of objects
I would like to draw you attention to the following pictures

First the original image

then how it is rendered on the  screen

as you can see on the original everything is nice and yellow, the edges have a slight transparency to look smooth.

but when I render I have some darkened pixels that appear.

To avoid the usual answer I get

I use

```<code>gl.glTexImage2D(GL10.GL_TEXTURE_2D, level, GL10.GL_RGBA, width, height, 0, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixelBuffer);
</code>```

and not the glutil tool

also

```<code>gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
</code>```

Anybody has a solution for that ?

Thanks

Jason

Edit

I did some digging. in the original image my background is already the same color as the coin and I use an alpha mask.
I've also checked, when I load the bitmap it seems that all the bitmap who have an alpha 0 are automatically set to 0,0,0,0. this might be the problem.

edit
actually it seems to be the issue. I checked the values of the bitmap I open, the values for transparent pixels are 0,0,0,0 instead of the color I set. Is this a problem with Bitmap or how I created my image?

```<code>// Load up, and flip the texture:
            Bitmap temp = BitmapFactory.decodeResource(context.getResources(), resource, opts);
            Bitmap bmp = Bitmap.createBitmap(temp, 0, 0, temp.getWidth(), temp.getHeight(), flip, true);
            temp.recycle();
</code>```

答:
What is the background color of your image? i.e. what does it look like when you remove the alpha channel? I'll guess - it's black? Try giving the background color the same color as your logo (i.e. yellowish) and try again.

EDIT: May as well edit the answer based on the comments. Even if you properly set the RGB color of the surrounding pixels, some image compression formats might still "optimize" that out and turn all completely transparent pixels into (0,0,0,0), which will cause the problems you describe when using bilinear filtering. Try using a different file format, or do research to see if you can turn this feature off in that particular compression, or consider fixing up the image in code after loading.

Body:
I would like to draw you attention to the following pictures

First the original image

then how it is rendered on the  screen

as you can see on the original everything is nice and yellow, the edges have a slight transparency to look smooth.

but when I render I have some darkened pixels that appear.

To avoid the usual answer I get

I use

gl.glTexImage2D(GL10.GL_TEXTURE_2D, level, GL10.GL_RGBA, width, height, 0, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixelBuffer);

and not the glutil tool

also

gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

Anybody has a solution for that ?

Thanks

Jason

Edit

I did some digging. in the original image my background is already the same color as the coin and I use an alpha mask.
I've also checked, when I load the bitmap it seems that all the bitmap who have an alpha 0 are automatically set to 0,0,0,0. this might be the problem.

edit
actually it seems to be the issue. I checked the values of the bitmap I open, the values for transparent pixels are 0,0,0,0 instead of the color I set. Is this a problem with Bitmap or how I created my image?

// Load up, and flip the texture:
            Bitmap temp = BitmapFactory.decodeResource(context.getResources(), resource, opts);
            Bitmap bmp = Bitmap.createBitmap(temp, 0, 0, temp.getWidth(), temp.getHeight(), flip, true);
            temp.recycle();


问:
Angular2 : how to call main component function from a child component
How to call main component function from a child component when I have deep nested hierarchy?

I have 3 components, button component I'm including inside browser component and browser component I'm including inside main component.

On click of button I need to call a function which is inside main component.

Button Component

```<code>@Component({
    selector: 'cb-button',
    templateUrl: 'cb-button.component.html',
    styleUrls: ['cb-button.component.scss']
})

export class CbButtonComponent {

     @Output() onClick: EventEmitter<any> = new EventEmitter();

     onBtnClick(): void {
        this.onClick.emit();
    }
}
</code>```

button component html

```<code><div (click)="onBtnClick()">
    <button>btn</button>
</div>
</code>```

browser component

```<code>@Component({
    selector: 'topology-browser',
    templateUrl: 'topology-browser.component.html',
    styleUrls: ['topology-browser.component.scss']
})

export class TopologyBrowserComponent {

   @Input('campus') campus: Campus;
}
</code>```

browser component html

```<code><div>
<h1>browser title</h1>
<cb-button (click)="editCampus()"></cb-button>
</div>
</code>```

and finally in main component i'm including browser component

main-component.ts

```<code>editCampus() {
  alert('clicked');
}
</code>```

html

```<code><topology-browser [campus]="campus"></topology-browser>
</code>```

when I click button I'm getting below error

Errorself.parentView.context.editCampus is not a function

答:
As I know there are two ways for your situation:

inject the parent component to child component

use EventEmitter

Since you have more than two layers, injecting MainComponent to ButtonComponent is much more simply to implement:

```<code>import {Component, Inject, forwardRef} from '@angular/core';

// change the MainComponent to your real component name
constructor(@Inject(forwardRef(() => MainComponent)) private main:MainComponent)
</code>```

Body:
How to call main component function from a child component when I have deep nested hierarchy?

I have 3 components, button component I'm including inside browser component and browser component I'm including inside main component.

On click of button I need to call a function which is inside main component.

Button Component

@Component({
    selector: 'cb-button',
    templateUrl: 'cb-button.component.html',
    styleUrls: ['cb-button.component.scss']
})

export class CbButtonComponent {

     @Output() onClick: EventEmitter<any> = new EventEmitter();

     onBtnClick(): void {
        this.onClick.emit();
    }
}

button component html

    <button>btn</button>

browser component

@Component({
    selector: 'topology-browser',
    templateUrl: 'topology-browser.component.html',
    styleUrls: ['topology-browser.component.scss']
})

export class TopologyBrowserComponent {

   @Input('campus') campus: Campus;
}

browser component html

browser title

<cb-button (click)="editCampus()"></cb-button>

and finally in main component i'm including browser component

main-component.ts

editCampus() {
  alert('clicked');
}

html

<topology-browser [campus]="campus"></topology-browser>

when I click button I'm getting below error

Errorself.parentView.context.editCampus is not a function

Body:
As I know there are two ways for your situation:

inject the parent component to child component

use EventEmitter

Since you have more than two layers, injecting MainComponent to ButtonComponent is much more simply to implement:

import {Component, Inject, forwardRef} from '@angular/core';

// change the MainComponent to your real component name
constructor(@Inject(forwardRef(() => MainComponent)) private main:MainComponent)


问:
How to get all dependency files for a program
I make a program in Go and after completing the code, if I want to run this code on other pc or VM, then it does not get all the dependency package files. How can I get all dependency files?</p>

答:
Try

```<code>go list -f '{{ join .Imports "\n" }}'
</code>```

or

```<code>go list -f '{{ join .Deps "\n" }}'
</code>```

The second will list all subdependencies, the first only the directly imported packages.

Body:
Try

go list -f '{{ join .Imports "\n" }}'

or

go list -f '{{ join .Deps "\n" }}'

The second will list all subdependencies, the first only the directly imported packages.


问:
AngularJs $http.post() does not send data
Could anyone tell me why the following statement does not send the post data to the designated url? The url is called but on the server when I print $_POST - I get an empty array. If I print message in the console before adding it to the data - it shows the correct content.

```<code>$http.post('request-url',  { 'message' : message });
</code>```

I've also tried it with the data as string (with the same outcome):

```<code>$http.post('request-url',  "message=" + message);
</code>```

It seem to be working when I use it in the following format:

```<code>$http({
    method: 'POST',
    url: 'request-url',
    data: "message=" + message,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
</code>```

but is there a way of doing it with the $http.post() - and do I always have to include the header in order for it to work? I believe that the above content type is specifying format of the sent data, but can I send it as javascript object?

答:
Found the simple solution on

http://jasonwatmore.com/post/2014/04/18/post-a-simple-string-value-from-angularjs-to-net-web-api

```<code>return $http.post(Config.apiUrl + '/example/processfile', '"' + fileName + '"');
</code>```

Body:
Could anyone tell me why the following statement does not send the post data to the designated url? The url is called but on the server when I print $_POST - I get an empty array. If I print message in the console before adding it to the data - it shows the correct content.

$http.post('request-url',  { 'message' : message });

I've also tried it with the data as string (with the same outcome):

$http.post('request-url',  "message=" + message);

It seem to be working when I use it in the following format:

$http({
    method: 'POST',
    url: 'request-url',
    data: "message=" + message,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

but is there a way of doing it with the $http.post() - and do I always have to include the header in order for it to work? I believe that the above content type is specifying format of the sent data, but can I send it as javascript object?

Body:
Found the simple solution on

http://jasonwatmore.com/post/2014/04/18/post-a-simple-string-value-from-angularjs-to-net-web-api

return $http.post(Config.apiUrl + '/example/processfile', '"' + fileName + '"');