答:
you are getting a blank list because the driver couldn't find the element match the locator strategy (By.ID, 'SearchResultsGrid').

It's inside a frame, you need to switch to the frame first and then find the element

Title: Python Selenium Can't see data

Body:
OK, so I'm new to programming with Python and HTML/Javascript but I have managed to scrape a website or two so far.  However, I have come across this site and its driving me round the bend.

My Code is:

#import libraries
from urllib.request import urlopen as ureq
from bs4 import BeautifulSoup as soup
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

#set chromepath to include .exe
chrome_path = r"C:\Program Files\Python37\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)

#set variables
myurl='http://www.ctbar.org/search/newsearch.asp'
driver.get(myurl) # loads the 1st page into the browser

element = driver.find_elements(By.ID, 'SearchResultsGrid')

print (element)
print('Done')

driver.quit()

The only output I get is:

[]
Done

What bit(s) am I getting wrong??

Please help before I give up in frustration:-)


来源: stackexchange

问:
org.xml.sax.SAXParseException: Content is not allowed in prolog
I have a Java based web service client connected to Java web service (implemented on the Axis1 framework).

I am getting following exception in my log file:

```<code>Caused by: org.xml.sax.SAXParseException: Content is not allowed in prolog.
    at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
    at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
    at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
    at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
    at org.apache.ws.axis.security.WSDoAllReceiver.invoke(WSDoAllReceiver.java:114)
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.client.AxisClient.invoke(AxisClient.java:198)
    at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
    at org.apache.axis.client.Call.invoke(Call.java:2767)
    at org.apache.axis.client.Call.invoke(Call.java:2443)
    at org.apache.axis.client.Call.invoke(Call.java:2366)
    at org.apache.axis.client.Call.invoke(Call.java:1812)
</code>```

答:
Sometimes it's the code, not the XML

The following code,

```<code>Document doc = dBuilder.parse(new InputSource(new StringReader("file.xml")));
</code>```

will also result in this error,

[Fatal Error] :1:1: Content is not allowed in prolog.org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.

because it's attempting to parse the string literal, "file.xml" (not the contents of the file.xml file) and failing because "file.xml" as a string is not well-formed XML.

Fix: Remove StringReader():

```<code>Document doc = dBuilder.parse(new InputSource("file.xml"));
</code>```

Similarly, dirty buffer problems can leave residual junk ahead of the actual XML.  If you've carefully checked your XML and are still getting this error, log the exact contents being passed to the parser; sometimes what's actually being (tried to be) parsed is surprising.

ContentLicense: CC BY-SA 3.0

Body:
I have a Java based web service client connected to Java web service (implemented on the Axis1 framework).

I am getting following exception in my log file:

Caused by: org.xml.sax.SAXParseException: Content is not allowed in prolog.
    at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
    at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
    at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
    at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
    at org.apache.ws.axis.security.WSDoAllReceiver.invoke(WSDoAllReceiver.java:114)
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.client.AxisClient.invoke(AxisClient.java:198)
    at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
    at org.apache.axis.client.Call.invoke(Call.java:2767)
    at org.apache.axis.client.Call.invoke(Call.java:2443)
    at org.apache.axis.client.Call.invoke(Call.java:2366)
    at org.apache.axis.client.Call.invoke(Call.java:1812)

Body:
Sometimes it's the code, not the XML

The following code,

Document doc = dBuilder.parse(new InputSource(new StringReader("file.xml")));

will also result in this error,

[Fatal Error] :1:1: Content is not allowed in prolog.org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.

because it's attempting to parse the string literal, "file.xml" (not the contents of the file.xml file) and failing because "file.xml" as a string is not well-formed XML.

Fix: Remove StringReader():

Document doc = dBuilder.parse(new InputSource("file.xml"));

Similarly, dirty buffer problems can leave residual junk ahead of the actual XML.  If you've carefully checked your XML and are still getting this error, log the exact contents being passed to the parser; sometimes what's actually being (tried to be) parsed is surprising.


问:
How do I get a JQuery object inside a template literal?
So often I have a JQuery object such as

```<code>var element = $('<h1>Title</h1>');
</code>```

I will make some operations on it, and later, I want to embed it inside of a template literal, so it displays as if it were using the $().append from jquery. Here is my attempt

```<code>var secondElement = $(`<div><div>${element}</div></div>`);
$('#someRandomDiv').append(secondElement);
</code>```

This, as expected, outputs

```<code><div><div>[Object object]</div></div>
</code>```

as it is referencing an object, not actually the HTML of the element. However I want it to be .

```<code><div><div><h1>Title</h1></div</div>
</code>```

Is there a way of doing this? Optimally it would still use the template literals, and of course, it is best if it uses native js/jquery functionality, rather than workarounds.

答:
You can access the underlying HTMLElement object by accessing element[0], then what you want is the html string, which you can get with .outerHTML. So:

var element = $('
Title
');

var secondElement = $(`<div><div>${element[0].outerHTML}</div></div>`);

console.log(secondElement[0].outerHTML)
// Logs:

Title

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
So often I have a JQuery object such as

var element = $('
Title
');

I will make some operations on it, and later, I want to embed it inside of a template literal, so it displays as if it were using the $().append from jquery. Here is my attempt

var secondElement = $(`<div><div>${element}</div></div>`);
$('#someRandomDiv').append(secondElement);

This, as expected, outputs

[Object object]

as it is referencing an object, not actually the HTML of the element. However I want it to be .

Title
</div

Is there a way of doing this? Optimally it would still use the template literals, and of course, it is best if it uses native js/jquery functionality, rather than workarounds.

Body:
You can access the underlying HTMLElement object by accessing element[0], then what you want is the html string, which you can get with .outerHTML. So:

var element = $('<h1>Title</h1>');

var secondElement = $(`<div><div>${element[0].outerHTML}</div></div>`);

console.log(secondElement[0].outerHTML)
// Logs: <div><div><h1>Title</h1></div></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
React with custom routing (on Symfony backend)
Just started new React project (still beginner in React) and I have to deal with new problem concerning routing.

Website is based on Symfony backend and there React used on front. When launching page, I have to go to URL where slug is required and it's controlled by Symfony routing and it's OK:

```<code>//domain.com/slug
</code>```

But then I have react app where everything happens on single page. On this single page I have container in which I have to switch components depending on user actions (like simple clicking links). Not whole page is reloading, only components container part. It's simple as this part of MainPage component (root):

```<code><header>some header</header>
<div id="content-wrapper">
    <div class="switch-components-inside">
        <ComponentsWrapper page={this.state.subPage} />
    </div>
</div>
<footer>footer!</footer>
</code>```

And to be honest I am confused, because I have no idea how to use react-router to construct such structure. Maybe I should do url modifications by my own? I want to be able to use URLs like this (can be with hash after slug of course), but all of them should direct to same component (MainPage) and only part of site should load different component.

```<code>//domain.com/slug#/news
//domain.com/slug#/news/some-news
//domain.com/slug#/authors
//domain.com/slug#/authors/some-author
</code>```

Thanks for help.

答:
Use react-router's HashRouter for hash-based routing.

A <Router> that uses the hash portion of the URL (i.e.
  window.location.hash) to keep your UI in sync with the URL.

IMPORTANT NOTE: Hash history does not support location.key or
  location.state. In previous versions we attempted to shim the behavior
  but there were edge-cases we couldn't solve. Any code or plugin that
  needs this behavior won't work. As this technique is only intended to
  support legacy browsers, we encourage you to configure your server to
  work with  instead.

So in your case you might have:

```<code>const App = () => {
  return (
    <HashRouter>
      <div>
        <header>some header</header>
        <div id="content-wrapper">
          <Switch>
            <Route path="/news" component={NewsComponent}/>
            <Route path="/authors" component={AuthorsComponent}/>
          </Switch>
        </div>
        <footer>footer!</footer>
      </div>
    </HashRouter>
  )
};
</code>```

Based on the IMPORTANT NOTE, though, it would be better to configure your backend to ignore routes nested under the //domain.com/slug and instead use <BrowserRouter basename="/slug">

Body:
Just started new React project (still beginner in React) and I have to deal with new problem concerning routing.

Website is based on Symfony backend and there React used on front. When launching page, I have to go to URL where slug is required and it's controlled by Symfony routing and it's OK:

//domain.com/slug

But then I have react app where everything happens on single page. On this single page I have container in which I have to switch components depending on user actions (like simple clicking links). Not whole page is reloading, only components container part. It's simple as this part of MainPage component (root):

some header

        <ComponentsWrapper page={this.state.subPage} />

footer!

And to be honest I am confused, because I have no idea how to use react-router to construct such structure. Maybe I should do url modifications by my own? I want to be able to use URLs like this (can be with hash after slug of course), but all of them should direct to same component (MainPage) and only part of site should load different component.

//domain.com/slug#/news
//domain.com/slug#/news/some-news
//domain.com/slug#/authors
//domain.com/slug#/authors/some-author

Thanks for help.

Body:
Use react-router's HashRouter for hash-based routing.

A <Router> that uses the hash portion of the URL (i.e.
  window.location.hash) to keep your UI in sync with the URL.

IMPORTANT NOTE: Hash history does not support location.key or
  location.state. In previous versions we attempted to shim the behavior
  but there were edge-cases we couldn't solve. Any code or plugin that
  needs this behavior won't work. As this technique is only intended to
  support legacy browsers, we encourage you to configure your server to
  work with  instead.

So in your case you might have:

const App = () => {
  return (
    <HashRouter>
      <div>
        <header>some header</header>
        <div id="content-wrapper">
          <Switch>
            <Route path="/news" component={NewsComponent}/>
            <Route path="/authors" component={AuthorsComponent}/>
          </Switch>
        </div>
        <footer>footer!</footer>
      </div>
    </HashRouter>
  )
};

Based on the IMPORTANT NOTE, though, it would be better to configure your backend to ignore routes nested under the //domain.com/slug and instead use <BrowserRouter basename="/slug">


问:
Overflow error using LMS algorithm from Neupy with example
I tried the example for LMS algorithm:

```<code>import numpy as np
from neupy import algorithms

input_data = np.array([[1, 0], [2, 2], [3, 3], [0, 0]])
target_data = np.array([[1], [0], [0], [1]])

lmsnet = algorithms.LMS((2, 1), step=0.5)

lmsnet.train(input_data, target_data, epochs=200)
lmsnet.predict(np.array([[4, 4], [0, 0]]))
</code>```

But I get "OverflowError: cannot convert float infinity to integer" error in this line (file:summary_info.py):

```<code>scale = math.ceil(self.delay_limit / average_delay)
</code>```

I can't relate the input parameters from the example to the error, I know that a division by zero get there but I can't figure out how to fix this. I don't want to modify library files to fix the problem.

答:
Your example works perfectly fine for me

You can overcome this issue, if you train your network in a loop, like this

```<code>import numpy as np
from neupy import algorithms

input_data = np.array([[1, 0], [2, 2], [3, 3], [0, 0]])
target_data = np.array([[1], [0], [0], [1]])

# Used smaller step since 0.5 is too big
lmsnet = algorithms.LMS((2, 1), step=0.1)

for _ in range(200):
    lmsnet.train(input_data, target_data, epochs=1)

lmsnet.predict(np.array([[4, 4], [0, 0]]))
</code>```

Body:
I tried the example for LMS algorithm:

import numpy as np
from neupy import algorithms

input_data = np.array([[1, 0], [2, 2], [3, 3], [0, 0]])
target_data = np.array([[1], [0], [0], [1]])

lmsnet = algorithms.LMS((2, 1), step=0.5)

lmsnet.train(input_data, target_data, epochs=200)
lmsnet.predict(np.array([[4, 4], [0, 0]]))

But I get "OverflowError: cannot convert float infinity to integer" error in this line (file:summary_info.py):

scale = math.ceil(self.delay_limit / average_delay)

I can't relate the input parameters from the example to the error, I know that a division by zero get there but I can't figure out how to fix this. I don't want to modify library files to fix the problem.

Body:
Your example works perfectly fine for me

You can overcome this issue, if you train your network in a loop, like this

import numpy as np
from neupy import algorithms

input_data = np.array([[1, 0], [2, 2], [3, 3], [0, 0]])
target_data = np.array([[1], [0], [0], [1]])

# Used smaller step since 0.5 is too big
lmsnet = algorithms.LMS((2, 1), step=0.1)

for _ in range(200):
    lmsnet.train(input_data, target_data, epochs=1)

lmsnet.predict(np.array([[4, 4], [0, 0]]))


问:
I'm developing a hangman guessing algorithm and wanted a clear explanation of something I saw
So far in my algorithm I have filtered the following to deduce the correct words

if i guess a letter and it isn't there, filter all words with that letter

if i guess a letter and it is there, filter any words without that letter in that specific placement

filter out words that don't match the length of the word being guessed

What I wanted clarification on, was how and if peeking into the next letter would help improve my algorithm, (I saw this in another post and wasn't sure how this would help improve the algorithm, if at all)

It was suggested that you could guess letters based on the resultant word bank after the filter went through I quote:

"you might be able to run a look-ahead. If we choose "A" at this level what options does that present for the next level? This is an O(x^n) algorithm, obviously you can't go too far down that path."

Can someone help explain to me how this would be implemented and how it would improve my code?

答: Symbol sequences are not random in any natural language.  A simple case is that in English "Q" is almost always followed by "U".  Thus, when you have a correct letter, you can now look through all the remaining words to see what letters most frequently follow (or just appear with) the one(s) you know already.  Use the new letter frequencies to make your next guess.


问:
Does Redux Use Persistent Data Structure?
What type of data structure does redux use for making the data persist in Angular and React.js? I am assuming it uses persistent data structures.</p>

答: Redux doesn't actually use any data structures itself.  The "current state" value is whatever you return from your root reducer function.  That could be a simple counter value, a plain JS array or object, an Immutable.js Map or List, or something else.


问:
Simple Lambda for Alexa
I'm trying to do something rather simple, or at least I thought it was going to be simple.

I want Alexa to use a Lambda I create from scratch. I want to be able to set certain actions depending on the date. I started with Dec 24 as it's rather easy. I'm trying to set the code to say if it is Dec 24 and at or later than 2100, then do this or else do that.

```<code>exports.handler = (event, context, callback) => {
// TODO implement
var dateTime = new Date();
var day = dateTime.getDate();
var mon = dateTime.getMonth();
var hour = dateTime.getHour();
var answer = "";

if(day == 24 && month == 11 && hour >= 20) {
    answer = 'working';
    console.log(answer);
} else {
    answer = 'not working';
    console.log(answer);
}

callback(answer, 'Hello from Lambda');
};
</code>```

I'm not a Node expert and didn't want to run a million tests, but I get this error:

```<code>{
  "errorMessage": "RequestId: ff577333-cb51-11e7-8d87-6d7ffdfe6f08 Process exited before completing request"
}
</code>```

Is my code wrong or am I missing something? Here's another version I thought about using:

```<code>exports.handler = (event, context, callback) => {
// TODO implement
var dateTime = new Date();
var day = dateTime.getDate();
var mon = dateTime.getMonth();
var hour = dateTime.getHour();
var answer = "";

if(month == 11) {
    if(day == 24) {
        if(hour >= 20) {
            answer = 'working';
    console.log(answer);
        }
    }
} else {
    answer = 'not working';
    console.log(answer);
}

callback(answer, 'Hello from Lambda');
};
</code>```

This is my test event that I'm using:

```<code>{
   "key3": "11, 9, 21",
   "key2": "12,24, 22",
   "key1": "5, 5, 5"
}
</code>```

Maybe I'm using the wrong way to test. Hoping for some guidance.

Thanks everyone in advance.

答:
For starters the format of your response isn't going to work for an Alexa skill. Also, as @TomG103 mentioned in his comment, the first argument of your callback should be null.

I did a video that will show you how to create a simple Alexa skill that should be easy for you to adapt for what you're trying to do.

Here is a link to the video. https://youtu.be/UlEhXDOIPvU

I hope it helps.

ContentLicense: CC BY-SA 4.0

Title: Simple Lambda for Alexa

Body:
I'm trying to do something rather simple, or at least I thought it was going to be simple.

I want Alexa to use a Lambda I create from scratch. I want to be able to set certain actions depending on the date. I started with Dec 24 as it's rather easy. I'm trying to set the code to say if it is Dec 24 and at or later than 2100, then do this or else do that.

exports.handler = (event, context, callback) => {
// TODO implement
var dateTime = new Date();
var day = dateTime.getDate();
var mon = dateTime.getMonth();
var hour = dateTime.getHour();
var answer = "";

if(day == 24 && month == 11 && hour >= 20) {
    answer = 'working';
    console.log(answer);
} else {
    answer = 'not working';
    console.log(answer);
}

callback(answer, 'Hello from Lambda');
};

I'm not a Node expert and didn't want to run a million tests, but I get this error:

{
  "errorMessage": "RequestId: ff577333-cb51-11e7-8d87-6d7ffdfe6f08 Process exited before completing request"
}

Is my code wrong or am I missing something? Here's another version I thought about using:

exports.handler = (event, context, callback) => {
// TODO implement
var dateTime = new Date();
var day = dateTime.getDate();
var mon = dateTime.getMonth();
var hour = dateTime.getHour();
var answer = "";

if(month == 11) {
    if(day == 24) {
        if(hour >= 20) {
            answer = 'working';
    console.log(answer);
        }
    }
} else {
    answer = 'not working';
    console.log(answer);
}

callback(answer, 'Hello from Lambda');
};

This is my test event that I'm using:

{
   "key3": "11, 9, 21",
   "key2": "12,24, 22",
   "key1": "5, 5, 5"
}

Maybe I'm using the wrong way to test. Hoping for some guidance.

Thanks everyone in advance.


问:
How to determine appropriate file extension from MIME Type in Objective-C
I'm using NSData object to store different kind of data. Object contains MIME format string as well. But in order to use [UIDocumentInteractionController interactionControllerWithURL:] method, I need to save the NSData object to the file system.

The problem is how to specify the file extension based on the MIME format?

答:
Credit goes to @makadev for this link which he posted as a comment, but I thought I would add it as an actual answer.  Here's some code derived from that article, which worked on iOS 11.  Note that you'll need to link with / import the MobileCoreServices framework.  The value you fill in for the mimetype token below should be an NSString*.

```<code>NSString* uti = (__bridge_transfer NSString*)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (__bridge CFStringRef)<#mimetype#>, NULL);
NSString* extension = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)uti, kUTTagClassFilenameExtension);
</code>```

Body:
Credit goes to @makadev for this link which he posted as a comment, but I thought I would add it as an actual answer.  Here's some code derived from that article, which worked on iOS 11.  Note that you'll need to link with / import the MobileCoreServices framework.  The value you fill in for the mimetype token below should be an NSString*.

NSString* uti = (__bridge_transfer NSString*)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (__bridge CFStringRef)<#mimetype#>, NULL);
NSString* extension = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)uti, kUTTagClassFilenameExtension);


问:
Stack smashing detected after closing the sf::RenderWindow
I'm writing both my first chip8 interpreter and multi-threaded program and ran into this problem: as soon as I close the window I get stack smashing detected. I've been inspecting the code for quite some time but I can't find the problem. Would really like some help or advice.

emulator.hpp

```<code>#ifndef CHEAP8_SRC_EMULATOR_HPP
#define CHEAP8_SRC_EMULATOR_HPP

#include "chip8.hpp"
#include "ui-settings.hpp"

#include <SFML/Graphics.hpp>

#include <atomic>
#include <memory>
#include <mutex>
#include <string>
#include <thread>

#ifdef _WIN32
#define OS_PATH_SEP '\\'
#else
#define OS_PATH_SEP '/'
#endif

class Emulator
{
    //misc
    const std::string gamePath;
    const std::string gameTitle;

    //emulator
    unsigned char memory[chip8::kMemSize] = {0};

    //flags
    bool gameLoaded = false;
    std::atomic<bool> gameRunning{false};

    //ui
    const double kPixelSize = 12.5;
    std::shared_ptr<sf::RenderWindow> window;
    const UiSettings uiSettings;

    //threading
    std::thread uiThread;
    std::mutex mutex;

    void loadGame();
    void loadFonts();
public:
    explicit Emulator(char*);
    ~Emulator();
    void run();
};

#endif //CHEAP8_SRC_EMULATOR_HPP
</code>```

emulator.cpp

```<code>#include "emulator.hpp"

#include <chrono> //================
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>

void launchUi(std::shared_ptr<sf::RenderWindow> window,
              const UiSettings& uiSettings,
              std::atomic<bool>& gameRunning)
{
    window = std::make_shared<sf::RenderWindow>();
    window->create(sf::VideoMode(uiSettings.width, uiSettings.height),
                   uiSettings.title,
                   sf::Style::Titlebar | sf::Style::Close);
    window->setVerticalSyncEnabled(true);
    window->setKeyRepeatEnabled(false);
    const auto screenParams = sf::VideoMode::getDesktopMode();
    window->setPosition(sf::Vector2i(screenParams.width / 2 - uiSettings.width / 2,
                                     screenParams.height / 2 - uiSettings.height / 2));

    sf::Event event;
    while (window->isOpen()) {
        while (window->pollEvent(event)) {
            switch (event.type) {
                case sf::Event::Closed:
                    window->close();
                    gameRunning.store(false);
                break;

                default:
                break;
            }
        }
    }
}

Emulator::Emulator(char* path)
    : gamePath(path),
      gameTitle(gamePath.substr(gamePath.find_last_of(OS_PATH_SEP) + 1)),
      uiSettings(kPixelSize, chip8::kScreenWidth, chip8::kScreenHeight, gameTitle),
      uiThread(launchUi, window, std::ref(uiSettings), std::ref(gameRunning))
{
    loadGame();
    loadFonts();
}

Emulator::~Emulator()
{
    uiThread.join();
}

void Emulator::loadGame()
{
    std::ifstream file(gamePath, std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Couldn't open the game." << std::endl;
        return;
    }

    std::vector<unsigned char> gameData;
    gameData.insert(gameData.begin(),
                std::istream_iterator<unsigned char>(file),
                std::istream_iterator<unsigned char>());

    if (gameData.size() > chip8::kAllowedGameSize) {
        std::cerr << "The game is too big to fit into memory." << std::endl;
        return;
    }

    for (size_t i = 0; i < gameData.size(); ++i) {
        memory[i + chip8::kMemStart] = gameData[i];
    }

    gameLoaded = true;
    std::cout << "Game loaded. Size: " << gameData.size() << '\n';
}

void Emulator::loadFonts()
{
    for (int i = 0; i < chip8::kFontsetSize; ++i) {
        memory[i] = chip8::kFontset[i];
    }
    std::cout << "Fontset loaded." << '\n';
}

void Emulator::run()
{
    if (!gameLoaded) {
        return;
    }

    gameRunning.store(true);
    while (gameRunning.load()) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}
</code>```

EDIT:

```<code>#include "emulator.hpp"

#include <iostream>

int main(int argc, char *argv[])
{
    if (argc != 2) {
        std::cerr << "Usage: ./" << OS_PATH_SEP << "cheap8 game." << std::endl;
        return 1;
    }

    Emulator emu(argv[1]);
    emu.run();

    return 0;
}
</code>```

答:
Your instance of Emulator is being created on the stack, so it will use stack space sufficient to store all its member variables.

This one is pretty big:

```<code>unsigned char memory[chip8::kMemSize] = {0};
</code>```

You might change that to a std::vector so that it stores the data on the heap and the class instance only contains metadata (size, pointer to data).

It will also change the effect of out-of-bounds access to your memory array -- instead of messing with the stack and changing things like return addresses, any corruption will be done to pure data objects.

To ensure there are no out-of-bounds accesses, you could use vector's at() member function.

Body:
I'm writing both my first chip8 interpreter and multi-threaded program and ran into this problem: as soon as I close the window I get stack smashing detected. I've been inspecting the code for quite some time but I can't find the problem. Would really like some help or advice.

emulator.hpp

#ifndef CHEAP8_SRC_EMULATOR_HPP
#define CHEAP8_SRC_EMULATOR_HPP

#include "chip8.hpp"
#include "ui-settings.hpp"

#include <SFML/Graphics.hpp>

#include <atomic>
#include <memory>
#include <mutex>
#include <string>
#include <thread>

#ifdef _WIN32
#define OS_PATH_SEP '\\'
#else
#define OS_PATH_SEP '/'
#endif

class Emulator
{
    //misc
    const std::string gamePath;
    const std::string gameTitle;

    //emulator
    unsigned char memory[chip8::kMemSize] = {0};

    //flags
    bool gameLoaded = false;
    std::atomic<bool> gameRunning{false};

    //ui
    const double kPixelSize = 12.5;
    std::shared_ptr<sf::RenderWindow> window;
    const UiSettings uiSettings;

    //threading
    std::thread uiThread;
    std::mutex mutex;

    void loadGame();
    void loadFonts();
public:
    explicit Emulator(char*);
    ~Emulator();
    void run();
};

#endif //CHEAP8_SRC_EMULATOR_HPP

emulator.cpp

#include "emulator.hpp"

#include <chrono> //================
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>

void launchUi(std::shared_ptr<sf::RenderWindow> window,
              const UiSettings& uiSettings,
              std::atomic<bool>& gameRunning)
{
    window = std::make_shared<sf::RenderWindow>();
    window->create(sf::VideoMode(uiSettings.width, uiSettings.height),
                   uiSettings.title,
                   sf::Style::Titlebar | sf::Style::Close);
    window->setVerticalSyncEnabled(true);
    window->setKeyRepeatEnabled(false);
    const auto screenParams = sf::VideoMode::getDesktopMode();
    window->setPosition(sf::Vector2i(screenParams.width / 2 - uiSettings.width / 2,
                                     screenParams.height / 2 - uiSettings.height / 2));

    sf::Event event;
    while (window->isOpen()) {
        while (window->pollEvent(event)) {
            switch (event.type) {
                case sf::Event::Closed:
                    window->close();
                    gameRunning.store(false);
                break;

                default:
                break;
            }
        }
    }
}

Emulator::Emulator(char* path)
    : gamePath(path),
      gameTitle(gamePath.substr(gamePath.find_last_of(OS_PATH_SEP) + 1)),
      uiSettings(kPixelSize, chip8::kScreenWidth, chip8::kScreenHeight, gameTitle),
      uiThread(launchUi, window, std::ref(uiSettings), std::ref(gameRunning))
{
    loadGame();
    loadFonts();
}

Emulator::~Emulator()
{
    uiThread.join();
}

void Emulator::loadGame()
{
    std::ifstream file(gamePath, std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Couldn't open the game." << std::endl;
        return;
    }

    std::vector<unsigned char> gameData;
    gameData.insert(gameData.begin(),
                std::istream_iterator<unsigned char>(file),
                std::istream_iterator<unsigned char>());

    if (gameData.size() > chip8::kAllowedGameSize) {
        std::cerr << "The game is too big to fit into memory." << std::endl;
        return;
    }

    for (size_t i = 0; i < gameData.size(); ++i) {
        memory[i + chip8::kMemStart] = gameData[i];
    }

    gameLoaded = true;
    std::cout << "Game loaded. Size: " << gameData.size() << '\n';
}

void Emulator::loadFonts()
{
    for (int i = 0; i < chip8::kFontsetSize; ++i) {
        memory[i] = chip8::kFontset[i];
    }
    std::cout << "Fontset loaded." << '\n';
}

void Emulator::run()
{
    if (!gameLoaded) {
        return;
    }

    gameRunning.store(true);
    while (gameRunning.load()) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

EDIT:

#include "emulator.hpp"

#include <iostream>

int main(int argc, char *argv[])
{
    if (argc != 2) {
        std::cerr << "Usage: ./" << OS_PATH_SEP << "cheap8 game." << std::endl;
        return 1;
    }

    Emulator emu(argv[1]);
    emu.run();

    return 0;
}

Body:
Your instance of Emulator is being created on the stack, so it will use stack space sufficient to store all its member variables.

This one is pretty big:

unsigned char memory[chip8::kMemSize] = {0};

You might change that to a std::vector so that it stores the data on the heap and the class instance only contains metadata (size, pointer to data).

It will also change the effect of out-of-bounds access to your memory array -- instead of messing with the stack and changing things like return addresses, any corruption will be done to pure data objects.

To ensure there are no out-of-bounds accesses, you could use vector's at() member function.


问:
Draw a plot using R that represent variation compared to a first value
I am making some small tests for the speed of execution of a program. I have a fixed size table, and the table get filled with random numbers and get sorted by an algorithm.
My tests vary the number of threads used to sort this table. Here is a sample of the results I output :

```<code>size;time;nb_thread;run_id
100000;0.013522;1;1
100000;0.013639;1;2
100000;0.013170;1;3
100000;0.012947;1;4
100000;0.012299;1;5
100000;0.012281;1;6
</code>```

I want to display the improvement (or not) of using N threads on a chart. I am able to display the changes in execution time according to their mean, but the result is not visually speaking. You get the illusion that there is a tremendous improvement of using 2 threads instead of one, but in fact even if there is an improvement it is pretty small.

So I want to display the variation between the runs with only one thread, and then the subsequent ones.
I don't even know the name of what I am looking for. How can I do this ?

答:
This plot shows all the values compared to the first value.

```<code>library(ggplot2)

ggplot(dt, aes(x = factor(run_id), y = time)) +
  geom_point(size = 3) +
  geom_hline(aes(yintercept = time[1]), color = "blue", size = 2) +
  geom_segment(aes(xend = factor(run_id), yend = time[1]),
               size = 1, color = "red", linetype = "dashed") +
  scale_x_discrete(name = "Run ID") +
  scale_y_continuous(name = "Time") +
  theme_bw() +
  theme(panel.grid = element_blank())
</code>```

DATA

```<code>dt <- read.table(text = "size;time;nb_thread;run_id
100000;0.013522;1;1
                 100000;0.013639;1;2
                 100000;0.013170;1;3
                 100000;0.012947;1;4
                 100000;0.012299;1;5
                 100000;0.012281;1;6",
                 header = TRUE, sep = ";")
</code>```

Body:
I am making some small tests for the speed of execution of a program. I have a fixed size table, and the table get filled with random numbers and get sorted by an algorithm.
My tests vary the number of threads used to sort this table. Here is a sample of the results I output :

size;time;nb_thread;run_id
100000;0.013522;1;1
100000;0.013639;1;2
100000;0.013170;1;3
100000;0.012947;1;4
100000;0.012299;1;5
100000;0.012281;1;6

I want to display the improvement (or not) of using N threads on a chart. I am able to display the changes in execution time according to their mean, but the result is not visually speaking. You get the illusion that there is a tremendous improvement of using 2 threads instead of one, but in fact even if there is an improvement it is pretty small.

So I want to display the variation between the runs with only one thread, and then the subsequent ones.
I don't even know the name of what I am looking for. How can I do this ?

Body:
This plot shows all the values compared to the first value.

library(ggplot2)

ggplot(dt, aes(x = factor(run_id), y = time)) +
  geom_point(size = 3) +
  geom_hline(aes(yintercept = time[1]), color = "blue", size = 2) +
  geom_segment(aes(xend = factor(run_id), yend = time[1]),
               size = 1, color = "red", linetype = "dashed") +
  scale_x_discrete(name = "Run ID") +
  scale_y_continuous(name = "Time") +
  theme_bw() +
  theme(panel.grid = element_blank())

DATA

dt <- read.table(text = "size;time;nb_thread;run_id
100000;0.013522;1;1
                 100000;0.013639;1;2
                 100000;0.013170;1;3
                 100000;0.012947;1;4
                 100000;0.012299;1;5
                 100000;0.012281;1;6",
                 header = TRUE, sep = ";")


问:
ngFor in ngFor set active class on click?
```<code> <div *ngFor="let position of positions" [ngClass]="{active :  position===selected.row }">

    <div *ngFor="let item of items[position], let i = index"   class="flow-one-item" (click)="selectItem(item)"> </div> </div>
</code>```

I have ngFor in ngFor what i want is to set active class on second ngFor on click. Any suggestion how can i do that??
I tried to add selectedItem == item but its not working,i think because of this items[position].

答:
That is because you are selecting the item of the main array "Positions" you have to change your code of the click event to sent the current position, not the item. Something like this</p>

```<code><div *ngFor="let position of positions"
     [ngClass]="{active :  position===selected.row }">

     <div *ngFor="let item of items[position], let i = index"
           class="flow-one-item" (click)="selectItem(position)"></div>
</div>
</code>```

Body:
That is because you are selecting the item of the main array "Positions" you have to change your code of the click event to sent the current position, not the item. Something like this

<div *ngFor="let position of positions"
     [ngClass]="{active :  position===selected.row }">

     <div *ngFor="let item of items[position], let i = index"
           class="flow-one-item" (click)="selectItem(position)"></div>
</div>


问:
How m[-1,-50] works on matrix in R?
It's from the Doc's example of persp function, like this:

```<code>x <- seq(-1.95, 1.95, length = 30)
y <- seq(-1.95, 1.95, length = 35)
z <- outer(x, y, function(a, b) a*b^2)
nrz <- nrow(z)
ncz <- ncol(z)
# Create a function interpolating colors in the range of specified colors
jet.colors <- colorRampPalette( c("blue", "green") )
# Generate the desired number of colors from this palette
nbcol <- 100
color <- jet.colors(nbcol)
# Compute the z-value at the facet centres
zfacet <- z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz]
# Recode facet z-values into color indices
facetcol <- cut(zfacet, nbcol)
persp(x, y, z, col = color[facetcol], phi = 30, theta = -30)
</code>```

So you can see, it creates a new matrix, which is important for generating the graph color, but I still don't understand what's the meaning of z[-1, -ncz] is (the ncz is a big number like 50) and what the new matrix zfacet meaning finally?

Thank you!

答:
Consider this:

```<code>R> x <- 1:5
R> x[-3]
[1] 1 2 4 5
R> x[-c(2,4)]
[1] 1 3 5
R>
</code>```

In R, a negative index excludes the element(s) at that index position.

Title: How m[-1,-50] works on matrix in R?

Body:
It's from the Doc's example of persp function, like this:

x <- seq(-1.95, 1.95, length = 30)
y <- seq(-1.95, 1.95, length = 35)
z <- outer(x, y, function(a, b) a*b^2)
nrz <- nrow(z)
ncz <- ncol(z)
# Create a function interpolating colors in the range of specified colors
jet.colors <- colorRampPalette( c("blue", "green") )
# Generate the desired number of colors from this palette
nbcol <- 100
color <- jet.colors(nbcol)
# Compute the z-value at the facet centres
zfacet <- z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz]
# Recode facet z-values into color indices
facetcol <- cut(zfacet, nbcol)
persp(x, y, z, col = color[facetcol], phi = 30, theta = -30)

So you can see, it creates a new matrix, which is important for generating the graph color, but I still don't understand what's the meaning of z[-1, -ncz] is (the ncz is a big number like 50) and what the new matrix zfacet meaning finally?

Thank you!

Body:
Consider this:

R> x <- 1:5
R> x[-3]
[1] 1 2 4 5
R> x[-c(2,4)]
[1] 1 3 5
R>

In R, a negative index excludes the element(s) at that index position.


问:
Using awk for headings
So I'm looking for some help with my headings for a text file.

A sample data file:

```<code>$ cat filename.txt
Consoling,ST,DWC,0900
Scribing,RA,DWC,1000
Gloater,AU,DWC,1100
Crimp,DI,DWC,1200
Moving,TI,DWC,1300
Handbook,EN,EBS,0900
Stifling,BA,EBS,1000
Unclothed,CR,EBS,1100
Until,IC,EBS,1200
</code>```

This is the awk code that i have.

```<code>sort -t, -k3 -k4 filename.txt |
column -ts, |
awk ' { printf "%-8s %-2s %-3s %-3s\n" , "Family Name", "Initals", "Interviewer Initals", "Interview Time" }
{ printf "%-8s %-2s %-3s %3d\n", $1,$2,$3,$4 }
'
</code>```

Which is outputting like this

```<code>Family Name Initals Interviewer Initals Interview Time
Consoling ST DWC 900
Family Name Initals Interviewer Initals Interview Time
Scribing RA DWC 1000
Family Name Initals Interviewer Initals Interview Time
Gloater  AU DWC 1100
Family Name Initals Interviewer Initals Interview Time
Crimp    DI DWC 1200
Family Name Initals Interviewer Initals Interview Time
Moving   TI DWC 1300
Family Name Initals Interviewer Initals Interview Time
Handbook EN EBS 900
Family Name Initals Interviewer Initals Interview Time
Stifling BA EBS 1000
Family Name Initals Interviewer Initals Interview Time
Unclothed CR EBS 1100
Family Name Initals Interviewer Initals Interview Time
Until    IC EBS 1200
</code>```

But what i want it to look like is this.

```<code>Family Name Initals Interviewer Initals Interview Time

Consoling   ST      DWC                 0900
Scribing    RA      DWC                 1000
Gloater     AU      DWC                 1100
Crimp       DI      DWC                 1200
Moving      TI      DWC                 1300

Handbook    EN      EBS                 0900
Stifling    BA      EBS                 1000
Unclothed   CR      EBS                 1100
Until       IC      EBS                 1200
</code>```

Does anyone know what i would have to change? Thanks

答:
To print the header once, place the header-specific printf command in a BEGIN block, eg:

```<code>awk '
BEGIN { printf ... header info... }
{ printf ... each data line ... }
'
</code>```

And if you find yourself wanting to print something after processing the file, use an END block.

As for the rest of the output, I'm assuming you want to print a new line each time you see a new/different interviewer.

```<code>{ if ( last_interviewer != $3 ) { printf "\n" ; last_interviewr=$3 }
  printf ... each data line
}
</code>```

So, pulling it all together ...

The data file:

```<code>$ cat filename.txt
Consoling,ST,DWC,0900
Scribing,RA,DWC,1000
Gloater,AU,DWC,1100
Crimp,DI,DWC,1200
Moving,TI,DWC,1300
Handbook,EN,EBS,0900
Stifling,BA,EBS,1000
Unclothed,CR,EBS,1100
Until,IC,EBS,1200
</code>```

And our awk solution:

```<code>$ sort -t, -k3 -k4 filename.txt |
column -ts, |
awk '
# print our header line once, before processing the actual data file:
BEGIN { printf "%-11s %-8s %-20s %-14s\n" , "Family Name", "Initials", "Interviewer Initials", "Interview Time" }

# now process our data file:
{ # if interviewer has changed, print an empty line and make note of our new last_interviewer:
  if ( last_interviewer != $3 )
     { printf "\n" ; last_interviewer=$3 }

  # print our current data line:
  printf "%-11s %-8s %-20s %04d\n", $1,$2,$3,$4
}'

Family Name Initials Interviewer Initials Interview Time

Consoling   ST       DWC                  0900
Scribing    RA       DWC                  1000
Gloater     AU       DWC                  1100
Crimp       DI       DWC                  1200
Moving      TI       DWC                  1300

Handbook    EN       EBS                  0900
Stifling    BA       EBS                  1000
Unclothed   CR       EBS                  1100
Until       IC       EBS                  1200
</code>```

NOTE: Updated the a couple of the printf formats to address the wider headers and to left pad the 4th column with zero's.

Title: Using awk for headings

Body:
So I'm looking for some help with my headings for a text file.

A sample data file:

$ cat filename.txt
Consoling,ST,DWC,0900
Scribing,RA,DWC,1000
Gloater,AU,DWC,1100
Crimp,DI,DWC,1200
Moving,TI,DWC,1300
Handbook,EN,EBS,0900
Stifling,BA,EBS,1000
Unclothed,CR,EBS,1100
Until,IC,EBS,1200

This is the awk code that i have.

sort -t, -k3 -k4 filename.txt |
column -ts, |
awk ' { printf "%-8s %-2s %-3s %-3s\n" , "Family Name", "Initals", "Interviewer Initals", "Interview Time" }
{ printf "%-8s %-2s %-3s %3d\n", $1,$2,$3,$4 }
'

Which is outputting like this

Family Name Initals Interviewer Initals Interview Time
Consoling ST DWC 900
Family Name Initals Interviewer Initals Interview Time
Scribing RA DWC 1000
Family Name Initals Interviewer Initals Interview Time
Gloater  AU DWC 1100
Family Name Initals Interviewer Initals Interview Time
Crimp    DI DWC 1200
Family Name Initals Interviewer Initals Interview Time
Moving   TI DWC 1300
Family Name Initals Interviewer Initals Interview Time
Handbook EN EBS 900
Family Name Initals Interviewer Initals Interview Time
Stifling BA EBS 1000
Family Name Initals Interviewer Initals Interview Time
Unclothed CR EBS 1100
Family Name Initals Interviewer Initals Interview Time
Until    IC EBS 1200

But what i want it to look like is this.

Family Name Initals Interviewer Initals Interview Time

Consoling   ST      DWC                 0900
Scribing    RA      DWC                 1000
Gloater     AU      DWC                 1100
Crimp       DI      DWC                 1200
Moving      TI      DWC                 1300

Handbook    EN      EBS                 0900
Stifling    BA      EBS                 1000
Unclothed   CR      EBS                 1100
Until       IC      EBS                 1200

Does anyone know what i would have to change? Thanks

Body:
To print the header once, place the header-specific printf command in a BEGIN block, eg:

awk '
BEGIN { printf ... header info... }
{ printf ... each data line ... }
'

And if you find yourself wanting to print something after processing the file, use an END block.

As for the rest of the output, I'm assuming you want to print a new line each time you see a new/different interviewer.

{ if ( last_interviewer != $3 ) { printf "\n" ; last_interviewr=$3 }
  printf ... each data line
}

So, pulling it all together ...

The data file:

$ cat filename.txt
Consoling,ST,DWC,0900
Scribing,RA,DWC,1000
Gloater,AU,DWC,1100
Crimp,DI,DWC,1200
Moving,TI,DWC,1300
Handbook,EN,EBS,0900
Stifling,BA,EBS,1000
Unclothed,CR,EBS,1100
Until,IC,EBS,1200

And our awk solution:

$ sort -t, -k3 -k4 filename.txt |
column -ts, |
awk '
# print our header line once, before processing the actual data file:
BEGIN { printf "%-11s %-8s %-20s %-14s\n" , "Family Name", "Initials", "Interviewer Initials", "Interview Time" }

# now process our data file:
{ # if interviewer has changed, print an empty line and make note of our new last_interviewer:
  if ( last_interviewer != $3 )
     { printf "\n" ; last_interviewer=$3 }

  # print our current data line:
  printf "%-11s %-8s %-20s %04d\n", $1,$2,$3,$4
}'

Family Name Initials Interviewer Initials Interview Time

Consoling   ST       DWC                  0900
Scribing    RA       DWC                  1000
Gloater     AU       DWC                  1100
Crimp       DI       DWC                  1200
Moving      TI       DWC                  1300

Handbook    EN       EBS                  0900
Stifling    BA       EBS                  1000
Unclothed   CR       EBS                  1100
Until       IC       EBS                  1200

NOTE: Updated the a couple of the printf formats to address the wider headers and to left pad the 4th column with zero's.


问:
Exporting files from a Javascript based phonegap app - options or ideas?
I'm currently writing a mobile app (hopefully iOS or android) using the jquery mobile framework and phonegap.
It'll need to export/send csv files in some way to the users, but I'd be interested to hear ideas or suggestions about the best way of doing so. If this can be done on the js side of the app that'd be ideal as it's what I'm most familiar with. A couple of options I've considered are:

Uploading the file using the google docs api

Writing the file to the file system (then export e.g. via iTunes)

I'm new to this so any suggestions gratefully received! Thanks for your help

答: As Dave pointed out you can write files with the FILE API. I have used the file api on iOs to write custom log files and havent found any yikes so far.</p>

ContentLicense: CC BY-SA 2.5


问:
Prevent IIS Recycling for specific change in files
I have a column in my grid view with images of a progress bar. These images are created on each render and written to my 'write' folder.
However, after Microsft's patch KB3052480, IIS resets once files in the application's directory have been created, changed, or overwritten.
This can be changed in IIS's settings so that it never resets on update . However this means the application would need to manually be restarted when any patch is applied (not an acceptable outcome).
Is there a way to keep the setting (so that IIS still resets on updates such as changes to .dll files) but still create and write images without it resetting.
I have looked around a lot but there is not much information on this particular issue.
What I was thinking is- somehow stop monitoring changes to file right before the save takes place. And then resume monitoring again.
How would this be done, or is there another way to prevent IIS from recycling after this specific change?</p>

答: To answer your question mentioned in the comment, which I think is your real question, to prevent the app domain from recycling on file save don't put the files you are saving inside the websites' folder. Instead have it in some other path that is not part of the application.</p>


问:
How to trigger a multi-configuration job periodically on jenkins?
I have set up a multi-configuration job which runs on different locales and environments in parallel. I have a configuration matrix setup and the different combinations are selected before we trigger the build. Not sure how to trigger these periodically(nightly build). Do i need any plugin on jenkins to achieve this?</p>

答: You can select Build periodically option from the Build Triggers


问:
Swift: One UITimePicker, Multiple Textfields
I have a single UIDatePicker variable that has only the time. I want that to be able to set different times to different TextFields. The way I have it set up is that when I change one time, they all change.

Code:

```<code>*@IBOutlets for all the UITextFields...*

private var datePicker = UIDatePicker()

override func viewDidLoad() {
    super.viewDidLoad()

    self.setupDatePicker()
    self.setupTextFields()
}

func setupDatePicker() {
    self.datePicker.frame = CGRect(x: 0, y: 50, width: self.view.frame.width, height: 200)
    self.datePicker.timeZone = NSTimeZone.local
    self.datePicker.datePickerMode = .time
    self.datePicker.minuteInterval = 30
    self.datePicker.backgroundColor = .white
    self.datePicker.addTarget(self, action: #selector(self.timeValueChanged(_:)), for: .valueChanged)
}

func setupTextFields() {
    self.mondayOpenTF.inputView = self.datePicker
    self.mondayCloseTF.inputView = self.datePicker
    self.tuesdayOpenTF.inputView = self.datePicker
    self.tuesdayCloseTF.inputView = self.datePicker
    self.wednesdayOpenTF.inputView = self.datePicker
    self.wednesdayCloseTF.inputView = self.datePicker
    self.thursdayOpenTF.inputView = self.datePicker
    self.thursdayCloseTF.inputView = self.datePicker
    self.fridayOpenTF.inputView = self.datePicker
    self.fridayCloseTF.inputView = self.datePicker
    self.saturdayOpenTF.inputView = self.datePicker
    self.saturdayCloseTF.inputView = self.datePicker
    self.sundayOpenTF.inputView = self.datePicker
    self.sundayCloseTF.inputView = self.datePicker
}

@objc
func timeValueChanged(_ sender: UIDatePicker) {
    let dateFormatter: DateFormatter = DateFormatter()
    dateFormatter.dateFormat = "h:mm a"
    let date: String = dateFormatter.string(from: sender.date)

    self.mondayOpenTF.text = date as String
    self.mondayCloseTF.text = date as String
    self.tuesdayOpenTF.text = date as String
    self.tuesdayCloseTF.text = date as String
    self.wednesdayOpenTF.text = date as String
    self.wednesdayCloseTF.text = date as String
    self.thursdayOpenTF.text = date as String
    self.thursdayCloseTF.text = date as String
    self.fridayOpenTF.text = date as String
    self.fridayCloseTF.text = date as String
    self.saturdayOpenTF.text = date as String
    self.saturdayCloseTF.text = date as String
    self.sundayOpenTF.text = date as String
    self.sundayCloseTF.text = date as String
}
</code>```

Is it possible to have one UIDatePicker to manage all the times seperately, or do I have to create 14 different ones to fill for each textfield?

答:
So If you only want to populate the currently selected textfield with the date provided, AND all of your textfields are located within your ViewController's MAIN view (or which ever view you specify, you just have to make sure that the view whose subviews you're looping throw contains your UITextFields), you could just check for whichever textfield is the first responder, and then add data to it, like this:

```<code>@objc
func timeValueChanged(_ sender: UIDatePicker) {
    let dateFormatter: DateFormatter = DateFormatter()
    dateFormatter.dateFormat = "h:mm a"
    let date: String = dateFormatter.string(from: sender.date)

    if let textfield = view.subviews.first(where: { $0 is UITextField }) as? UITextView, textfield.isFirstResponder {
        textfield.text = date
    }
}
</code>```

Also, you could potentially clean up your setup code with a similar method, like so:

```<code>setupTextFields() {

    for textfield in (view.subviews.map {$0 as? UITextField}.flatMap{$0}) {
        textfield.inputView = datePicker
    }
}
</code>```

Body:
I have a single UIDatePicker variable that has only the time. I want that to be able to set different times to different TextFields. The way I have it set up is that when I change one time, they all change.

Code:

*@IBOutlets for all the UITextFields...*

private var datePicker = UIDatePicker()

override func viewDidLoad() {
    super.viewDidLoad()

    self.setupDatePicker()
    self.setupTextFields()
}

func setupDatePicker() {
    self.datePicker.frame = CGRect(x: 0, y: 50, width: self.view.frame.width, height: 200)
    self.datePicker.timeZone = NSTimeZone.local
    self.datePicker.datePickerMode = .time
    self.datePicker.minuteInterval = 30
    self.datePicker.backgroundColor = .white
    self.datePicker.addTarget(self, action: #selector(self.timeValueChanged(_:)), for: .valueChanged)
}

func setupTextFields() {
    self.mondayOpenTF.inputView = self.datePicker
    self.mondayCloseTF.inputView = self.datePicker
    self.tuesdayOpenTF.inputView = self.datePicker
    self.tuesdayCloseTF.inputView = self.datePicker
    self.wednesdayOpenTF.inputView = self.datePicker
    self.wednesdayCloseTF.inputView = self.datePicker
    self.thursdayOpenTF.inputView = self.datePicker
    self.thursdayCloseTF.inputView = self.datePicker
    self.fridayOpenTF.inputView = self.datePicker
    self.fridayCloseTF.inputView = self.datePicker
    self.saturdayOpenTF.inputView = self.datePicker
    self.saturdayCloseTF.inputView = self.datePicker
    self.sundayOpenTF.inputView = self.datePicker
    self.sundayCloseTF.inputView = self.datePicker
}

@objc
func timeValueChanged(_ sender: UIDatePicker) {
    let dateFormatter: DateFormatter = DateFormatter()
    dateFormatter.dateFormat = "h:mm a"
    let date: String = dateFormatter.string(from: sender.date)

    self.mondayOpenTF.text = date as String
    self.mondayCloseTF.text = date as String
    self.tuesdayOpenTF.text = date as String
    self.tuesdayCloseTF.text = date as String
    self.wednesdayOpenTF.text = date as String
    self.wednesdayCloseTF.text = date as String
    self.thursdayOpenTF.text = date as String
    self.thursdayCloseTF.text = date as String
    self.fridayOpenTF.text = date as String
    self.fridayCloseTF.text = date as String
    self.saturdayOpenTF.text = date as String
    self.saturdayCloseTF.text = date as String
    self.sundayOpenTF.text = date as String
    self.sundayCloseTF.text = date as String
}

Is it possible to have one UIDatePicker to manage all the times seperately, or do I have to create 14 different ones to fill for each textfield?

Body:
So If you only want to populate the currently selected textfield with the date provided, AND all of your textfields are located within your ViewController's MAIN view (or which ever view you specify, you just have to make sure that the view whose subviews you're looping throw contains your UITextFields), you could just check for whichever textfield is the first responder, and then add data to it, like this:

@objc
func timeValueChanged(_ sender: UIDatePicker) {
    let dateFormatter: DateFormatter = DateFormatter()
    dateFormatter.dateFormat = "h:mm a"
    let date: String = dateFormatter.string(from: sender.date)

    if let textfield = view.subviews.first(where: { $0 is UITextField }) as? UITextView, textfield.isFirstResponder {
        textfield.text = date
    }
}

Also, you could potentially clean up your setup code with a similar method, like so:

setupTextFields() {

    for textfield in (view.subviews.map {$0 as? UITextField}.flatMap{$0}) {
        textfield.inputView = datePicker
    }
}


问:
Can I safely delete calico-* pods from my cluster?
After updating container cluster node version to 1.7.6 new pods called calico-* appeared on my cluster. The question is - can I safely delete them?

I'm not sure if this is a bug or not, but those node appeared on my 2 clusters:

first (my staging env), after update from 1.7.5 to 1.7.6

second (my prod env), after update from 1.6.5 to 1.7.6

However, when I've created new cluster with version 1.7.5 and update it to 1.7.6 those pods have not appeared.

Mentiones pods are:

calico-node

calico-node-vertical-autoscaler

calico-typha

calico-typha-horizontal-autoscaler

calico-typha-vertical-autoscaler

edit:

答: It looks like Google provided a way to get rid of calico PODs via Google Cloud Console. Please see the screen below.


问:
The domain name is resolving to our service but has not been added to a user account
I am getting this message in my website.I am using facebook and twitter applications in this page.I am not able to figure it out....The canvas URL for facebook application and callback url for twitter are correct.

Domain name not found in any user account.
  The domain name is resolving to our service but has not been added to a user account. If you are the owner of this domain name, you may log in and add the domain name to your user account.

Thanks in advance

答: You have to tell your hosting service that you want it to host the domain. Just changing the name server entries in the domain registrar isn't enough, you also have to go create an account for it at the hosting service. Log onto your hosting service control panel and look for something like "Add-on domain", "Create acount", etc. There you can specify the domain name to use.</p>


问:
Q-learning (multiple goals)
i have just started to study Q-learning and see the possibilities of using Q-learning to solve my problem.

Problem: I am supposed to detect a certain combination of data, i have four matrices that acts as an input to my system, i have already categorised the inputs ( each input can either be Low (L) , or High (H) ). I need to detect certain types of input for example LLLH, LLHH, HHHH etc

NOTE:
1)LLLH means the first input in L, second input is L, third input is L and the fourth input is H!
2)I have labelled each type of input type as state, for example LLLL is state 1, LLLH is state 2, so on.

What i have studied in Q-learning is that most of the time you have one goal (only one state as a goal) which makes it easier for the agent to learn and create the Q-matrix from the R-matrix . Now in my problem i have many goal ( many states act as goal and need to be detected). I dont know how to design the states, how to create the Reward-matrix by having many goals and how the agent will learn. Can you please help me how can i use Q-learning in this kind of situation. Taking into account i have like 16 goals in 20+ states!

as i have mentioned above, i know what is q-learning, how the states and the goal works, the calculation of Q_matrix (how it learns).... but the problem is now i have many goals, i dont really know how to relate my problem to q-learning.. how many states do i need, and how to label the Rewards as i have many goals.

I need help on at least how can i create reward matrix with many goals

答:
Multiple goals are being investigated as it does solve some critical RL problems.

Here is a great article where the goal is to deliver packages or recharge the battery... If you don't recharge the deliveries will fail, but if you constantly charge, you will not make any deliveries.  It is a balance between these two important goals.

The author talk you through the logic and approach in TensorFlow:
https://www.oreilly.com/ideas/reinforcement-learning-for-complex-goals-using-tensorflow

Title: Q-learning (multiple goals)


问:
Angular 4 Animation not working in Edge
I created an animation that I use throughout the project, but it is not working in Edge browser. This is the code I am using, anyone knows what I can do to fix it?</p>

```<code>import {animate, state, style, transition, trigger} from '@angular/core';

export const animation = trigger('slideInOutAnimation', [

  state('*', style({

  })),
  transition(':enter', [
    style({
      '-webkit-transform': 'translateY(-50%)',
      transform: 'translateY(-50%)',
    }),
    animate('.5s ease-in-out', style({
      '-webkit-transform': 'translateY(0)',
      transform: 'translateY(0)',
    }))
  ]),
  transition(':leave', [
    animate('.5s ease-in-out', style({
      '-webkit-transform': 'translateY(-50%)',
      transform: 'translateY(-50%)',
    }))
  ])
]);
</code>```

答:
From pollyfills.ts please uncomment import 'web-animations-js'; and run command npm install --save web-animations-js.

If you don't have any pollyfills file please refer to official link to create one

Title: Angular 4 Animation not working in Edge

Body:
I created an animation that I use throughout the project, but it is not working in Edge browser. This is the code I am using, anyone knows what I can do to fix it?

import {animate, state, style, transition, trigger} from '@angular/core';

export const animation = trigger('slideInOutAnimation', [

  state('*', style({

  })),
  transition(':enter', [
    style({
      '-webkit-transform': 'translateY(-50%)',
      transform: 'translateY(-50%)',
    }),
    animate('.5s ease-in-out', style({
      '-webkit-transform': 'translateY(0)',
      transform: 'translateY(0)',
    }))
  ]),
  transition(':leave', [
    animate('.5s ease-in-out', style({
      '-webkit-transform': 'translateY(-50%)',
      transform: 'translateY(-50%)',
    }))
  ])
]);


问:
Animation not working in ReactVR
It seems I'm missing one thing somewhere as I'm not seeing any errors in the console but the animation doesn't seem to be running or my scene is too heavy that the animation runs before the model is actually loaded...anything I'm missing in my code?</p>

```<code>import React from 'react';
import { asset, View, StyleSheet, Model, Animated } from 'react-vr';

const AnimatedModel = Animated.createAnimatedComponent(Model);

export default class Loral extends React.Component {
   constructor(props) {
     super(props);
    this.state = {
      satelliteTransX: new Animated.Value(3),
      satelliteRotY: -45,
    };
  }

  componentDidMount() {
     this.state.satelliteTransX.setValue(3);
     Animated.timing(
       this.state.satelliteTransX,
      {
        toValue: 10,
        duration: 1000,
        delay: 1000
      }
     ).start();
   }

   render() {
     return (
       <View>
         <AnimatedModel
           source={{
             obj: asset('/Loral-1300Com-obj/Loral-1300Com-main.obj'),
             mtl: asset('/Loral-1300Com-obj/Loral-1300Com-main.mtl')
           }}
           style={{
                 transform: [
                {translate: [this.state.satelliteTransX, 0, -10]},
                { scale: 0.01 },
                { rotateX: 30},
                { rotateY: this.state.satelliteRotY }
             ]
           }}
         />
      </View>
     );
  }
};
</code>```

答:
Try setting your translate individually by axis so instead of this:

```<code> style={{
    transform: [
       {translate: [this.state.satelliteTransX, 0, -10]},
       { scale: 0.01 },
       { rotateX: 30},
       { rotateY: this.state.satelliteRotY }
    ]
 }}
</code>```

try this

```<code> style={{
    transform: [
       {translateX: this.state.satelliteTransX},
       {translateY: 0},
       {translateZ: -10},
       { scale: 0.01 },
       { rotateX: 30},
       { rotateY: this.state.satelliteRotY }
    ]
 }}
</code>```

That should do the trick for you. I have experienced this issue for all animated  properties referenced in an array like you have above.

Title: Animation not working in ReactVR

Body:
It seems I'm missing one thing somewhere as I'm not seeing any errors in the console but the animation doesn't seem to be running or my scene is too heavy that the animation runs before the model is actually loaded...anything I'm missing in my code?

import React from 'react';
import { asset, View, StyleSheet, Model, Animated } from 'react-vr';

const AnimatedModel = Animated.createAnimatedComponent(Model);

export default class Loral extends React.Component {
   constructor(props) {
     super(props);
    this.state = {
      satelliteTransX: new Animated.Value(3),
      satelliteRotY: -45,
    };
  }

  componentDidMount() {
     this.state.satelliteTransX.setValue(3);
     Animated.timing(
       this.state.satelliteTransX,
      {
        toValue: 10,
        duration: 1000,
        delay: 1000
      }
     ).start();
   }

   render() {
     return (
       <View>
         <AnimatedModel
           source={{
             obj: asset('/Loral-1300Com-obj/Loral-1300Com-main.obj'),
             mtl: asset('/Loral-1300Com-obj/Loral-1300Com-main.mtl')
           }}
           style={{
                 transform: [
                {translate: [this.state.satelliteTransX, 0, -10]},
                { scale: 0.01 },
                { rotateX: 30},
                { rotateY: this.state.satelliteRotY }
             ]
           }}
         />
      </View>
     );
  }
};

Body:
Try setting your translate individually by axis so instead of this:

 style={{
    transform: [
       {translate: [this.state.satelliteTransX, 0, -10]},
       { scale: 0.01 },
       { rotateX: 30},
       { rotateY: this.state.satelliteRotY }
    ]
 }}

try this

 style={{
    transform: [
       {translateX: this.state.satelliteTransX},
       {translateY: 0},
       {translateZ: -10},
       { scale: 0.01 },
       { rotateX: 30},
       { rotateY: this.state.satelliteRotY }
    ]
 }}

That should do the trick for you. I have experienced this issue for all animated  properties referenced in an array like you have above.


问:
Finding a set that contains all values of an original set in a SPARQL query
I'm trying to build a SPARQL query that gets the students of one teacher and finds all the teachers with all those students (they can have more students).

This is what I have so far:

```<code>SELECT ?otherTeacher
WHERE {
VALUES ?teacher {$teacher}
  ?teacher hasStudent ?student .
  ?otherTeacher hasStudent ?student .
  FILTER(?teacher <> ?otherTeacher)
}
</code>```

Here are the expected cases with the below data:

 - If teacher1 is given, only teacher3 should show up (teacher3 teaches all the students that teacher1 teaches).

 - If teacher2 is given, both teacher1 and teacher3 should show up (both teacher1 and teacher3 teach all the students teacher2 teaches).

 - If teacher3 is given, no teachers should show up (no other teacher teaches all the students teacher3 teaches).

```<code><teacher1> <hasStudent> "Alice" .
<teacher1> <hasStudent> "Bob" .
<teacher1> <hasStudent> "Charlie" .
<teacher2> <hasStudent> "Alice" .
<teacher2> <hasStudent> "Dan" .
<teacher3> <hasStudent> "Alice" .
<teacher3> <hasStudent> "Bob" .
<teacher3> <hasStudent> "Charlie" .
<teacher3> <hasStudent> "Dan" .
</code>```

How do I add a requirement that ?otherTeacher has all the students that ?teacher has (that the new set contains at least all the elements of the original set)?

答:
Not an elegant solution since it involves nesting multiple queries. There should be a better way of solving this problem.

This solution uses a nested query to get the maximum of the counts.

Line 13 is to only include students for otherTeacher that teacher also teaches (to remove students like Dan from the count).

```<code>select distinct ?otherTeacher
where{
  {
    select (max(?count) as ?max)
      where{
        {
          SELECT DISTINCT ?otherTeacher (COUNT(?student) as ?count)
          WHERE {
          VALUES ?teacher {<teacher1> }
            ?otherTeacher <hasStudent> ?student .
            FILTER(?teacher != ?otherTeacher)
            FILTER EXISTS {
              ?teacher <hasStudent> ?student .
            }
          }
          group by ?otherTeacher
       }
    }
  }
  {
    SELECT DISTINCT ?otherTeacher (COUNT(?student) as ?count)
    WHERE {
    VALUES ?teacher {<teacher1> }
      ?otherTeacher <hasStudent> ?student .
      FILTER(?teacher != ?otherTeacher)
      FILTER EXISTS {
        ?teacher <hasStudent> ?student .
      }
    }
    group by ?otherTeacher
  }
  filter(?count >= ?max) # epsilon error/no match if it's equal?
}
</code>```

Body:
I'm trying to build a SPARQL query that gets the students of one teacher and finds all the teachers with all those students (they can have more students).

This is what I have so far:

SELECT ?otherTeacher
WHERE {
VALUES ?teacher {$teacher}
  ?teacher hasStudent ?student .
  ?otherTeacher hasStudent ?student .
  FILTER(?teacher <> ?otherTeacher)
}

Here are the expected cases with the below data:

 - If teacher1 is given, only teacher3 should show up (teacher3 teaches all the students that teacher1 teaches).

 - If teacher2 is given, both teacher1 and teacher3 should show up (both teacher1 and teacher3 teach all the students teacher2 teaches).

 - If teacher3 is given, no teachers should show up (no other teacher teaches all the students teacher3 teaches).

<teacher1> <hasStudent> "Alice" .
<teacher1> <hasStudent> "Bob" .
<teacher1> <hasStudent> "Charlie" .
<teacher2> <hasStudent> "Alice" .
<teacher2> <hasStudent> "Dan" .
<teacher3> <hasStudent> "Alice" .
<teacher3> <hasStudent> "Bob" .
<teacher3> <hasStudent> "Charlie" .
<teacher3> <hasStudent> "Dan" .

How do I add a requirement that ?otherTeacher has all the students that ?teacher has (that the new set contains at least all the elements of the original set)?

Body:
Not an elegant solution since it involves nesting multiple queries. There should be a better way of solving this problem.

This solution uses a nested query to get the maximum of the counts.

Line 13 is to only include students for otherTeacher that teacher also teaches (to remove students like Dan from the count).

select distinct ?otherTeacher
where{
  {
    select (max(?count) as ?max)
      where{
        {
          SELECT DISTINCT ?otherTeacher (COUNT(?student) as ?count)
          WHERE {
          VALUES ?teacher {<teacher1> }
            ?otherTeacher <hasStudent> ?student .
            FILTER(?teacher != ?otherTeacher)
            FILTER EXISTS {
              ?teacher <hasStudent> ?student .
            }
          }
          group by ?otherTeacher
       }
    }
  }
  {
    SELECT DISTINCT ?otherTeacher (COUNT(?student) as ?count)
    WHERE {
    VALUES ?teacher {<teacher1> }
      ?otherTeacher <hasStudent> ?student .
      FILTER(?teacher != ?otherTeacher)
      FILTER EXISTS {
        ?teacher <hasStudent> ?student .
      }
    }
    group by ?otherTeacher
  }
  filter(?count >= ?max) # epsilon error/no match if it's equal?
}


问:
How to STANDALONE execute the following bitbake script in DISTRO="poky" context?
I created the following bitbake script (kind of), but I would like to execute it independently in DISTRO="poky" context:

```<code>BBLAYERS ?= " \
  /home/user/YOCTO/oe_core_embedded/poky/meta \
  /home/user/YOCTO/oe_core_embedded/poky/meta-poky \
  /home/user/YOCTO/oe_core_embedded/poky/meta-yocto-bsp \
  "

for layer in ${BBLAYERS}; do
        cd $layer
        echo -n "$(basename $layer) = "  >> ${D}${sysconfdir}/gitinfo
        git rev-parse HEAD >> ${D}${sysconfdir}/gitinfo
done
</code>```

Explicitly, I do NOT want this script to be part of any recipe .bb, NOT at all?!

How I can do execution of this script standalone?

Thank you,
nobody

答:
For me, what you are trying to do is pretty much identical to buildinfo feature?

If you add

```<code> INHERIT += "image-buildinfo"
</code>```

to your conf file, you will have those info in /etc/build file.

See https://mender.io/blog/build-info-yocto-2 for more information for example.

If you want to do a standalone script, you can inspire you from poky/scripts/*.py for instance.

Body:
I created the following bitbake script (kind of), but I would like to execute it independently in DISTRO="poky" context:

BBLAYERS ?= " \
  /home/user/YOCTO/oe_core_embedded/poky/meta \
  /home/user/YOCTO/oe_core_embedded/poky/meta-poky \
  /home/user/YOCTO/oe_core_embedded/poky/meta-yocto-bsp \
  "

for layer in ${BBLAYERS}; do
        cd $layer
        echo -n "$(basename $layer) = "  >> ${D}${sysconfdir}/gitinfo
        git rev-parse HEAD >> ${D}${sysconfdir}/gitinfo
done

Explicitly, I do NOT want this script to be part of any recipe .bb, NOT at all?!

How I can do execution of this script standalone?

Thank you,
nobody

Body:
For me, what you are trying to do is pretty much identical to buildinfo feature?

If you add

 INHERIT += "image-buildinfo"

to your conf file, you will have those info in /etc/build file.

See https://mender.io/blog/build-info-yocto-2 for more information for example.

If you want to do a standalone script, you can inspire you from poky/scripts/*.py for instance.


问:
Correct way to use Actions to create menus, toolbars, and other components in Java
The naive way of writing building a menu in a Java Swing app is to do something like:

```<code>JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open...");
openItem.addActionListener(new ActionListener() { /* action listener stuff */ } )
fileMenu.addMenuItem(openItem);
</code>```

A more experienced developer will recognize that actions can be accessed through a variety of mechanisms - menus, toolbar buttons, maybe even other workflows in the system.  That person is more likely to write:

```<code>Action openAction = new AbstractAction();
openAction.setName("Open...");
openAction.addActionListener(new ActionListener() { /* action listener stuff */ } )
...
JMenuItem openItem = new JMenuItem(openAction);
</code>```

My question is, what is the best way to manage these Action objects so they can be used across menus, toolbars, etc?

Create a factory class that returns specific actions?

Declare all of the actions as private static final Action in some utility class?

Take advantage of a Java application framework?

Something else?

答:
Action is a bad abstraction - an ActionListener welded to a poor man's Map.

Certainly do not assign them to a static as they are mutable and also need some context to operate usefully.

My general advice for GUI programming is to note that it is actually much the same as any other area of programming. Follow the usual good practices. Notably, layering, separation of concerns, use (implementation) inheritance rarely and don't write a big ball of mud.

OwnerDisplayName: David

Body:
The naive way of writing building a menu in a Java Swing app is to do something like:

JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open...");
openItem.addActionListener(new ActionListener() { /* action listener stuff */ } )
fileMenu.addMenuItem(openItem);

A more experienced developer will recognize that actions can be accessed through a variety of mechanisms - menus, toolbar buttons, maybe even other workflows in the system.  That person is more likely to write:

Action openAction = new AbstractAction();
openAction.setName("Open...");
openAction.addActionListener(new ActionListener() { /* action listener stuff */ } )
...
JMenuItem openItem = new JMenuItem(openAction);

My question is, what is the best way to manage these Action objects so they can be used across menus, toolbars, etc?

Create a factory class that returns specific actions?

Declare all of the actions as private static final Action in some utility class?

Take advantage of a Java application framework?

Something else?

LastEditorDisplayName: David

OwnerDisplayName: Tom Hawtin - tackline


问:
Mirth performance benchmark
We are using mirth connect for message transformation from hl7 to text and storing the transformed messages to azure sql database. Our current performance is 45000 messages per hour .

machine  configuration is
8 GB RAM and 2 core CPU. Memory assigned to mirth is -XMS = 6122MB

We don't have any idea about what could be performance parameters for Mirth with above configurations. Anyone have idea about performance benchmarks for Mirth connect?

答:
I'd recommend looking into the Max Processing Threads option in version 3.4 and above. It's configurable in the Source Settings (Source tab). By default it's set to 1, which means only one message can process through the channel's main processing thread at any given time. This is important for certain interfaces where order of messages is paramount, but obviously it limits throughput.

Note that whatever client is sending your channel messages also needs to be reconfigured to send multiple messages in parallel. For example if you have a single-threaded process that is sending your channel messages via TCP/MLLP one after another in sequence, increasing the max processing threads isn't necessarily going to help because the client is still single-threaded. But, for example, if you stand up 10 clients all sending to your channel simultaneously, then you'll definitely reap the benefits of increasing the max processing threads.

If your source connector is a polling type, like a File Reader, you can still benefit from this by turning the Source Queue on and increasing the Max Processing Threads. When the source queue is enabled and you have multiple processing threads, multiple queue consumers are started and all read and process from the source queue at the same time.

Another thing to look at is destination queuing. In the Advanced (wrench icon) queue settings, there is a similar option to increase the number of Destination Queue Threads. By default when you have destination queuing enabled, there's just a single queue thread that processes messages in a FIFO sequence. Again, good for message order but hampers throughput.

If you do need messages to be ordered and want to maximize parallel throughput (AKA have your cake and eat it too), you can use the Thread Assignment Variable in conjunction with multiple destination Queue Threads. This allows you to preserve order among messages with the same unique identifier, while messages pertaining to different identifiers can process simultaneously. A common use-case is to use the patient MRN for this, so that all messages for a given patient are guaranteed to process in the order they were received, but messages longitudinally across different patients can process simultaneously.

Title: Mirth performance benchmark


问:
c# Marshal null-terminated string array
I am trying to import the following:

```<code>const char * const *object_get_prop_names(propobject_t *ocr);
</code>```

as:

```<code>[DllImport("vender.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern IntPtr object_get_prop_names(int* osr);
</code>```

based on: https://limbioliong.wordpress.com/2011/08/14/returning-an-array-of-strings-from-c-to-c-part-1/

I've tried the following:

```<code>var pNames = object_get_prop_names(hdl);

int StringCount = 200; //how do I know string count?

IntPtr[] pIntPtrArray = new IntPtr[StringCount];
ManagedStringArray = new string[StringCount];

Marshal.Copy(pNames, pIntPtrArray, 0, StringCount);

for (int i = 0; i < StringCount; i++)
{
    ManagedStringArray[i] = Marshal.PtrToStringAnsi(pIntPtrArray[i]);
    //Marshal.FreeCoTaskMem(pIntPtrArray[i]); crashes
}

//Marshal.FreeCoTaskMem(pUnmanagedStringArray); crashes
</code>```

This works but I am guessing that I have memory leaks and accessing memory I shouldn't.

How should I free the memory?

How do I know the count? This is from a vendor and they will not modify the dll for little ol' me. :)

Also forgive me for delving into something I know very little about.

答:
Following Hans' suggestions:

```<code>var pNames = object_get_prop_names(hdl);
if (h == IntPtr.Zero)
{
    return null;
}

var nameList = new List<string>();
int elementSize = Marshal.SizeOf(typeof(IntPtr));

for (int i = 0; i < 200; i++) //don't know length, pick large number
{
    var ptr = Marshal.ReadIntPtr(pNames, i * elementSize);
    var str = Marshal.PtrToStringAnsi(ptr);
    if (!string.IsNullOrWhiteSpace(str))
    {
        nameList.Add(str);
    }
    else //end of pNames
    {
        break;
    }
}
</code>```

Works great. I have no way of knowing how many property names there are so I just  have to pick a larger number than the possible number of property names.

Title: c# Marshal null-terminated string array

Body:
I am trying to import the following:

const char * const *object_get_prop_names(propobject_t *ocr);

as:

[DllImport("vender.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern IntPtr object_get_prop_names(int* osr);

based on: https://limbioliong.wordpress.com/2011/08/14/returning-an-array-of-strings-from-c-to-c-part-1/

I've tried the following:

var pNames = object_get_prop_names(hdl);

int StringCount = 200; //how do I know string count?

IntPtr[] pIntPtrArray = new IntPtr[StringCount];
ManagedStringArray = new string[StringCount];

Marshal.Copy(pNames, pIntPtrArray, 0, StringCount);

for (int i = 0; i < StringCount; i++)
{
    ManagedStringArray[i] = Marshal.PtrToStringAnsi(pIntPtrArray[i]);
    //Marshal.FreeCoTaskMem(pIntPtrArray[i]); crashes
}

//Marshal.FreeCoTaskMem(pUnmanagedStringArray); crashes

This works but I am guessing that I have memory leaks and accessing memory I shouldn't.

How should I free the memory?

How do I know the count? This is from a vendor and they will not modify the dll for little ol' me. :)

Also forgive me for delving into something I know very little about.

Body:
Following Hans' suggestions:

var pNames = object_get_prop_names(hdl);
if (h == IntPtr.Zero)
{
    return null;
}

var nameList = new List<string>();
int elementSize = Marshal.SizeOf(typeof(IntPtr));

for (int i = 0; i < 200; i++) //don't know length, pick large number
{
    var ptr = Marshal.ReadIntPtr(pNames, i * elementSize);
    var str = Marshal.PtrToStringAnsi(ptr);
    if (!string.IsNullOrWhiteSpace(str))
    {
        nameList.Add(str);
    }
    else //end of pNames
    {
        break;
    }
}

Works great. I have no way of knowing how many property names there are so I just  have to pick a larger number than the possible number of property names.


问:
How to run TestNG tests in parallel using Eclipse?
I am new to test-ng, I am using eclipse plugin to run test cases.
I have an excel file for data. when I am running, it is executing 1 by 1. I know we can execute parallel through cmd by setting parallel="methods" thread-count="2", But it not working in Eclipse plugin. So please tell me how to run TestNG parallel in Eclipse.

Thanks.

答:
It seems here is the exact question and the answer to it:

When you are running an XML file, you can specify all the settings you want for this run in the XML file, but what if you want to run a package in parallel mode with specific listeners? How can you configure the settings for all the launches that are not done from an XML file?

In order to give you access to the most flexibility, TestNG lets you specify an XML suite file for all these launches, which you can find in the Preferences menu: screenshot.

If you specify a valid suite file as "XML template file", TestNG will reuse all the settings found in this XML file, such as parallel, name, listeners, thread pool size, etc... Only the <test> tags in this file will be ignored since the plug-in will replace these by a generated <test> tag that represents the launch you chose.

— TestNG - Eclipse.

Long story short, it is necessary to have the suite XML file.

Also, please see the documentation on the appropriate part of the suite XML file schema: TestNG: 5.10 - Parallelism and time-outs.


问:
Using ngFor item as key in an Observable list
I'm extremely new to Angular and really excited so far at how powerful it is.
I'm using the angularfire2 library to retrieve two separate lists from firebase (*.ts):

```<code>this.list1= this.db.list("list1").valueChanges();
this.list2= this.db.list("list2").valueChanges();
</code>```

While looping over the first list with *ngFor, I want to use list1.val as a key in obtaining a list2 value

```<code>(list2[list1.val].name).
</code>```

I run into lots of different errors when trying different things, but the most prominent is this error:

```<code>TypeError: Cannot read property 'party' of undefined
</code>```

This is what my *.html file looks like currently (was attempting some magic with async):

```<code><ion-row *ngFor="let item1 of list1| async">
  <ion-col>{{item1.val}}</ion-col>
  <!--different attempts-->
  <ion-col>{{(list2|async)[item1.val].name}}</ion-col>
  <ion-col>{{(list2[item1.val].name| async)}}</ion-col>
  </ion-col>
</ion-row>
</code>```

I'm thinking that ngFor is somehow changing the structure of list1 from:

```<code>Observable<any[]>
</code>```

to an object that's more consumable. Without that, my list2 object is actually something that cannot be indexed unless some sort of transformation happens? Help :)

答:
So I was able to figure this out with some help from this post: Nested Observables in Angular2 using AngularFire2 not rendering in view

The trick was to make a map function which mapped an object observable to my second node:

```<code>this.list1= this.db.list("list1").snapshotChanges().map(changes => {
  return changes.map(list1Obj => ({
    l1Key: list1Obj.payload.key,
    list2Obj: this.db.object('list2/' + list1Obj.payload.key).valueChanges()
  }));
});
</code>```

Then, I was able to display it in the html like so:

```<code>  <ion-row *ngFor="let item1 of list1| async">
    <ion-col>{{item1.l1Key}}</ion-col>
    <ion-col>{{((item1.list2Obj | async)?.name)}}</ion-col>
  </ion-row>
</code>```

Body:
I'm extremely new to Angular and really excited so far at how powerful it is.
I'm using the angularfire2 library to retrieve two separate lists from firebase (*.ts):

this.list1= this.db.list("list1").valueChanges();
this.list2= this.db.list("list2").valueChanges();

While looping over the first list with *ngFor, I want to use list1.val as a key in obtaining a list2 value

(list2[list1.val].name).

I run into lots of different errors when trying different things, but the most prominent is this error:

TypeError: Cannot read property 'party' of undefined

This is what my *.html file looks like currently (was attempting some magic with async):

<ion-row *ngFor="let item1 of list1| async">
  <ion-col>{{item1.val}}</ion-col>

  <ion-col>{{(list2|async)[item1.val].name}}</ion-col>
  <ion-col>{{(list2[item1.val].name| async)}}</ion-col>
  </ion-col>
</ion-row>

I'm thinking that ngFor is somehow changing the structure of list1 from:

Observable<any[]>

to an object that's more consumable. Without that, my list2 object is actually something that cannot be indexed unless some sort of transformation happens? Help :)

Body:
So I was able to figure this out with some help from this post: Nested Observables in Angular2 using AngularFire2 not rendering in view

The trick was to make a map function which mapped an object observable to my second node:

this.list1= this.db.list("list1").snapshotChanges().map(changes => {
  return changes.map(list1Obj => ({
    l1Key: list1Obj.payload.key,
    list2Obj: this.db.object('list2/' + list1Obj.payload.key).valueChanges()
  }));
});

Then, I was able to display it in the html like so:

  <ion-row *ngFor="let item1 of list1| async">
    <ion-col>{{item1.l1Key}}</ion-col>
    <ion-col>{{((item1.list2Obj | async)?.name)}}</ion-col>
  </ion-row>