text:
Q: Sensu server can't connect to RabbitMQ I've been trying to install Sensu for a while, I've been following the installation guide, everything was going well while installing, but when I was adding the example checks from the docs, Sensu suddenly couldn't connect to RabbitMQ. Specifically, when I added the check_cron.json config. I tried restarting and removing the config (and restarting again after that), but Sensu is consistently timing out. It's worth noting that RabbitMQ is installed and running, it's even possible to navigate trough the management interface, however Sensu doesn't seem to recognize that.
Below is my server log:
{"timestamp":"2014-07-03T11:39:00.254061-0300","level":"warn","message":"config file applied changes","config_file":"/etc/sensu/conf.d/check_cron.json","changes":{"checks":{"cron_check":[null,{"handlers":["default"],"command":"/etc/sensu/plugins/check-proc.rb -p crond -C 1","interval":30,"subscribers":["webservers"]}]}}}
{"timestamp":"2014-07-03T11:39:00.254279-0300","level":"warn","message":"config file applied changes","config_file":"/etc/sensu/conf.d/client.json","changes":{"client":[null,{"name":"sensu-test","address":"127.0.0.1","subscriptions":["test","webservers"]}]}}
{"timestamp":"2014-07-03T11:39:00.262568-0300","level":"info","message":"loaded extension","type":"mutator","name":"only_check_output","description":"returns check output"}
{"timestamp":"2014-07-03T11:39:00.265246-0300","level":"info","message":"loaded extension","type":"handler","name":"debug","description":"outputs json event data"}
{"timestamp":"2014-07-03T11:39:00.313486-0300","level":"info","message":"i am the master"}
{"timestamp":"2014-07-03T11:39:03.326913-0300","level":"warn","message":"reconnecting to rabbitmq"}
{"timestamp":"2014-07-03T11:39:03.327281-0300","level":"warn","message":"unsubscribing from keepalive and result queues"}
{"timestamp":"2014-07-03T11:39:03.327463-0300","level":"warn","message":"resigning as master"}
{"timestamp":"2014-07-03T11:39:03.328908-0300","level":"info","message":"removed master lock"}
{"timestamp":"2014-07-03T11:39:11.343859-0300","level":"warn","message":"reconnecting to rabbitmq"}
{"timestamp":"2014-07-03T11:39:19.366786-0300","level":"warn","message":"reconnecting to rabbitmq"}
{"timestamp":"2014-07-03T11:39:20.294332-0300","level":"fatal","message":"rabbitmq connection error","error":"timed out while attempting to connect"}
{"timestamp":"2014-07-03T11:39:20.294816-0300","level":"warn","message":"stopping"}
{"timestamp":"2014-07-03T11:39:20.294959-0300","level":"warn","message":"unsubscribing from keepalive and result queues"}
{"timestamp":"2014-07-03T11:39:20.295122-0300","level":"info","message":"completing handlers in progress","handlers_in_progress_count":0}
{"timestamp":"2014-07-03T11:39:20.796222-0300","level":"warn","message":"stopping reactor"}
{"timestamp":"2014-07-03T11:50:59.786233-0300","level":"warn","message":"config file applied changes","config_file":"/etc/sensu/conf.d/client.json","changes":{"client":[null,{"name":"sensu-test","address":"127.0.0.1","subscriptions":["test","webservers"]}]}}
{"timestamp":"2014-07-03T11:50:59.808513-0300","level":"info","message":"loaded extension","type":"mutator","name":"only_check_output","description":"returns check output"}
{"timestamp":"2014-07-03T11:50:59.811049-0300","level":"info","message":"loaded extension","type":"handler","name":"debug","description":"outputs json event data"}
{"timestamp":"2014-07-03T11:50:59.858109-0300","level":"info","message":"i am the master"}
{"timestamp":"2014-07-03T11:51:02.867913-0300","level":"warn","message":"reconnecting to rabbitmq"}
{"timestamp":"2014-07-03T11:51:02.868369-0300","level":"warn","message":"unsubscribing from keepalive and result queues"}
{"timestamp":"2014-07-03T11:51:02.868466-0300","level":"warn","message":"resigning as master"}
{"timestamp":"2014-07-03T11:51:02.869157-0300","level":"info","message":"removed master lock"}
{"timestamp":"2014-07-03T11:51:10.889055-0300","level":"warn","message":"reconnecting to rabbitmq"}
{"timestamp":"2014-07-03T11:51:18.910561-0300","level":"warn","message":"reconnecting to rabbitmq"}
{"timestamp":"2014-07-03T11:51:19.842039-0300","level":"fatal","message":"rabbitmq connection error","error":"timed out while attempting to connect"}
{"timestamp":"2014-07-03T11:51:19.842408-0300","level":"warn","message":"stopping"}
{"timestamp":"2014-07-03T11:51:19.842551-0300","level":"warn","message":"unsubscribing from keepalive and result queues"}
{"timestamp":"2014-07-03T11:51:19.842714-0300","level":"info","message":"completing handlers in progress","handlers_in_progress_count":0}
{"timestamp":"2014-07-03T11:51:20.343916-0300","level":"warn","message":"stopping reactor"}

A: If you are using ssl certificates on your rabbitmq server then you probably have a problem with the certificates. There is a script on github clone it and run the following commands:
git clone git://github.com/joemiller/joemiller.me-intro-to-sensu.git
cd joemiller.me-intro-to-sensu/

./ssl_certs.sh clean
./ssl_certs.sh generate

And then configure the Rabbitmq to use these certificates:
mkdir /etc/rabbitmq/ssl
cp server_key.pem /etc/rabbitmq/ssl/
cp server_cert.pem /etc/rabbitmq/ssl/
cp testca/cacert.pem /etc/rabbitmq/ssl/

And add this configuration to /etc/rabbitmq/rabbitmq.config:
[
  {rabbit, [
    {ssl_listeners, [5671]},
    {ssl_options, [{cacertfile,"/etc/rabbitmq/ssl/cacert.pem"},
                   {certfile,"/etc/rabbitmq/ssl/server_cert.pem"},
                   {keyfile,"/etc/rabbitmq/ssl/server_key.pem"},
                   {verify,verify_peer},
                   {fail_if_no_peer_cert,true}]}
  ]}
].

here you tell rabbitmq which certificates it will be using, make sure the paths of the certificates are the same as the ones you copied the certificates to.
update-rc.d sensu-server defaults
update-rc.d sensu-api defaults
update-rc.d sensu-client defaults
update-rc.d sensu-dashboard defaults

And then copy the SSL client_key and certificate as you have done earlier using:
cp client_key.pem client_cert.pem  /etc/sensu/ssl/

And then add the different configurations to /etc/sensu/config.json.


text:
Q: How to add page header without first page itext 7 I created document using pdfHTMl in Text 7. I want to add page header for every pages without first page. I used PdfDocumentEvent.END_PAGE event. But it applies for every pages with first page. How to remove page header from the first page?
Thank You.

A: This is an example of an event handler that adds a header:
protected class MyEventHandler implements IEventHandler {

    PdfFont helvetica;

    public MyEventHandler() throws IOException {
        helvetica = PdfFontFactory.createFont();
    }

    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdfDoc = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        Rectangle pageSize = page.getPageSize();
        int pageNumber = pdfDoc.getPageNumber(page);
        if (pageNumber == 1) return;
        PdfCanvas pdfCanvas = new PdfCanvas(
            page.newContentStreamBefore(), page.getResources(), pdfDoc);
        pdfCanvas.beginText()
            .setFontAndSize(helvetica, 9)
            .moveText(pageSize.getWidth() / 2 - 30, pageSize.getTop() - 20)
            .showText("THIS IS A HEADER!")
            .endText();
        pdfCanvas.release();
    }
}

Because of the if (pageNumber == 1) return; there won't be any header added. so there's no need to remove the header. As you can see in the screen shot, there is no header on page one, but a header on each following page.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Script js not updating in laravel I already have web app develop with laravel, after i edited some line on my javascript file, and save it, it doesn't change when i check on my browser.
i put my javascript file on public folder.
@push('scripts')
<script src="{{ asset('public/myJavascript.js') }}"></script>
@endpush

i already tried clear cache on browser, but it doesn't work as well
this app already on live server, i code it via winSCP.
I have no idea what was going on here, Thank you in advance

A: it already solved now, i need to run this command below
php artisan clear-compiled
php artisan view:clear
php artisan cache:clear

thank you


text:
Q: Removing rows with 'junk data' Is there a way to remove the rows containing 'junk' data? In this case, junk data would be defined as having punctuation, symbols or letters. So once the junk data has been removed, the only data left should be those that are numeric.
test<-c(12,123,2435,1231,121,'a!12','12fb','gr32#')
x<-data.frame(test)

A: You could convert the data to numeric and then remove NA values
x <- data.frame(test, stringsAsFactors = FALSE)
x[!is.na(as.numeric(x$test)), , drop =  FALSE]

#  test
#1   12
#2  123
#3 2435
#4 1231
#5  121

Or using regular expressions, we can drop rows which contain anything other than numbers.
x[!grepl("[^0-9]", x$test), , drop = FALSE]
#OR
#x[grep("[^0-9]", x$test, invert = TRUE), , drop = FALSE]

data
x <- data.frame(test, stringsAsFactors = FALSE)

A: We can use regex to select only digits ([0-9]+) from start (^) to end ($) in filter and then convert to numeric (if needed).
library(dplyr)
library(stringr)
x %>%
   filter(str_detect(test, "^[0-9]+$"))
# test
#1   12
#2  123
#3 2435
#4 1231
#5  121

Or with subset and grepl from base R
subset(x, grepl("^[0-9]+$", test))


text:
Q: Here Maps Routing API V8 - mutiple waypoints I am very new to the Here Maps Routing API v8.
I have tried the example provided here:
https://developer.here.com/documentation/maps/3.1.15.1/dev_guide/topics/routing.html
I have used the routingParameters as shown below:
var routingParameters = {
  'routingMode': 'fast',
  'transportMode': 'car',
  'origin': '50.1120,8.6834',
  'destination': '52.5309,13.3846',
  'return': 'polyline'
};

Now I want to add multiple waypoints in the routingParameters and I tried the below format for the same:
'via' : ['50.1234,8.7654', '51.2234,9.1123']
But the request is failing when I use the above line in the routingParameters.
Can you please suggest the correct format of the request with multiple waypoints ?

A: Check the version of the HERE Maps JS API you are using. This is supported starting from version 3.1.19.0.
So the way to calculate a route with multiple waypoints would be:
// departure point (origin)
var start = '52.550464,13.384223';

// collection of waypoints
var waypoints = [
  '52.529791,13.401389'
  '52.513079,13.424392'
  '52.487581,13.425079'
];

// end point (destination)
var end = '52.477545,13.447395'

// routing parameters
var routingParameters = {
  'origin': start,
  'destination': end,
  'via': new H.service.Url.MultiValueQueryParameter( waypoints ),

  'routingMode': 'fast',
  'transportMode': 'car',

  'return': 'polyline'
};

// Get an instance of the routing service version 8:
var router = platform.getRoutingService(null, 8);

// Call `calculateRoute` with the routing parameters,
// the success callback and an error callback function
// The implementation of the two callback functions is left out for brevity
// see documentation link below for callback examples
router.calculateRoute(routingParameters, onResultCallback, onErrorCallback)

Calculate routes with HERE Maps JS API: documentation

A: In JS, the correct way to add multiple waypoints is with H.service.Url.MultiValueQueryParameter:
var routingParameters = {
  'routingMode': 'fast',
  'transportMode': 'car',
  'origin': '50.1120,8.6834',
  'via': new H.service.Url.MultiValueQueryParameter(['50.1234,8.7654', '51.2234,9.1123']);
  'destination': '52.5309,13.3846',
  'return': 'polyline'
};

For more information check documentation at https://developer.here.com/documentation/maps/3.1.19.2/api_reference/H.service.Url.MultiValueQueryParameter.html


text:
Q: URL masking? maybe? Have a .net webapp running on IIS.
I have run across something I haven't had to really deal with before. we have partners or clients that have their own "pages" on our domain. currently the URL is www.mydomain.com/?code=partnercode, but for ease of use on business cards and such they want it to be more like www.mydomain.com/partnername and I am not sure how to do this.
I know we can do something like the following in the htaccess in Apache
RewriteRule ^partnername$ index.php?code=partnerid [L]

I am wondering if there is some way to do this in the web.config? there has got to be something, but I am unsure where to look to find it. I have tried those online htaccess to web.config code converters and it failed miserably. The other thing is I would prefer to not have to change the partnerID that we already have in the DB.
I found this on another question on this site but I don't think it will do what I need it to. It will change the URL in the browser one the user hits the page but I also want it to be accessible using the www.mydomain.com/partnername URL as well.
if ( $_SERVER['REQUEST_URI'] == '/index.php?code=partnerid') {
echo '<script type="text/javascript">window.history.pushState("", "", "/partnername");</script>';
}

A: IIS has extension that partially supports your scenario, it is called URL Rewrite.
I said partially, because you can use it to rewrite URLs from www.mydomain.com/partnername to www.mydomain.com/?code=partnername. What it doesn't support (at least I don't think it does) is mapping a partner name to partner code (unless you have small number of partners and you can add rewrite rule for every partner).
And here is an article showing a fraction of what you can do with URL Rewrite.
In your case if you want to rewrite www.mydomain.com/partnername to www.mydomain.com/?code=partnername, your rule configuration could look something like this (not tested on IIS):
<rewrite>
  <rules>
    <rule name="Rewrite to query string">
      <!-- I'm using hardcoded text, but it is regular expression and you can
           write very advanced conditions -->
      <match url="^(partner)" />
      <!-- changes incoming url /partner to ?code=partner -->
      <action type="Rewrite" url="?code={R:1}" />
    </rule>
  </rules>
</rewrite>


text:
Q: GitLab CI java springboot microservices connect to docker test evironment I wanted to implement an integration test in Java Maven Spring-Boot application using my docker-compose setup. but when I try to connect to the gateway service in my docker environment from my "mvn test" then I get the error

java.net.ConnectException: Failed to connect to docker/172.17.0.3:4000.
and if I try to use localhost instead of docker I get this error:

java.net.ConnectException: Failed to connect to localhost/[0:0:0:0:0:0:0:1]:4000.
does anyone have any idea what I could try to solve this issue?
here is the code that tries to connect to the gateway docker container:
    public Response sendHTTPMessage(String uri, RequestBody body, HTTPMethods method) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        Request request = new Request.Builder()
                .url("http://docker:4000" + uri)
                .method(method.value(), body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", (this.token == null ? "" : "Bearer " + this.token))
                .build();

        return client.newCall(request).execute();
    }

here is my project repo with the GitLab-ci and docker-compose files that I use to set up the test environment (I use the default shared GitLab runners): https://gitlab.com/kwetter_jack/Kwetter_posts/-/blob/test_integration
here are the log files (the error is at the bottom of the log file)
log of the localhost URL test
log of the docker URL test


text:
Q: How do the different compression levels of gzip differ? I am trying to better understand how different compression levels  (1-9) of gzip differ in the way that encoding is implemented.
I've looked the zlib C source code and it seems that it has to do with how exhaustive the search for the longest matching string is, but looking for more specific information.
For example, do the levels yield any differences in the assignment of Huffman codes?

A: The levels differ only in how hard deflate looks for matching strings, as you observed. The Huffman coding is done on a chosen fixed number of symbols (literals and length/distance pairs), producing a "block", where that number is defined by the memory level, not the compression level. The Huffman codes generated will necessarily differ, since the symbols being coded will differ.
The choice of memory level also has some effect on compression, as a larger number of symbols spreads the cost of the code description for a block over more symbols, but too many symbols may prevent adaptation of the Huffman codes to local changes in the statistics of the symbols. The default memory level is 8 (resulting in 16,383 symbols per block), since testing indicated that that gave better compression than level 9 (32,767 symbols per block). However your mileage may vary.

A: From what I recall, yes, it is mainly based on the size of the buffer you'll be allocating. The larger the buffer, the better you can compress. If you can allocate a buffer with a size of about input file size × 1.2, then, in most cases, you will get the best compression possible with Huffman.
The reason is that the Huffman table will encompass all the bytes with the best possible outcome when you have such a large buffer. When the algorithm runs out of buffer space, then it needs to reset its table (there is a code in the stream added for that) and that means you start a new encoding table from scratch, which means you lose bytes to redesign that new table...
Although there are cases where resetting can be beneficial (i.e. many bytes set to value X in the first half of your file, and then many more that have value Y in the second half), it is rare that would happens.


text:
Q: JavaScript Library to show tooltips with keyboard shortcuts when holding down alt/ctrl Is there a JavaScript library that, when the user holds down ctrl/alt, will display tooltips over elements on the page that have associated keyboard shortcuts (via an accesskey attribute) that use that key?
ctrl

A: This is what I was looking for: KeyCandy. Although I'll have to fix the flicker when Ctrl is held down.
I knew I'd seen something like this before. Not sure if it's the same one. Anyone got a better one?

A: I think KeyTips is the one I'd seen before. It's certainly looks better than KeyCandy, although I like how KeyCandy makes Ctrl the modifier for accesskeys.
Here's what it looks like:

There are some issues with browser reserved shortcuts but as this is an internal intranet site if I make it a hosted app for chrome it would be able to handle any shortcut

A: You don't require any library for keyboard shortcuts. Simply use the keys in the Object passed in the keydown object. For instance:
var element = document.querySelector("#element");
element.addEventListener("keydown", function (event) {
    //Ctrl+Alt+Del
    if (event.key === "Delete" && event.ctrlKey === true && event.altKey === true) {
        //Disables Ctrl+Alt+Del
        event.preventDefault();
        alert("You pressed Ctrl+Alt+Del, too bad!");
    }
    //Win+R (On Windows, it opens up the Run Prompt)
    else if (event.key === "r" && event.metaKey === true) {
        //Disable it once again
        event.preventDefault();
        alert("You can never 'run' from me!!");
    }
    //Create A Save Prompt When Users Ctrl+S
    else if (event.key === "s" && event.ctrlKey === true) {
        event.preventDefault();
        //Give The User Options
        alert("First choose an option to save, then continue.");
    }
});

And then, from there, simply add the title attribute to the element, to create a browser generated tooltip, and simply focus() on the element when the shortcut is pressed.
JavaScript:
var element = document.querySelector("#element");

if (event.key === "h" && event.ctrlKey === true) {
    event.preventDefault();
    element.focus();
}

HTML:

Help Help Help

Hope that helps!


text:
Q: How can a Chrome user with a small screen resolution make websites (like StackOverflow) more usable? I am using PowerToys to split my ultrascreen into multiple panels. One of my panels has a resolution of 1024x1080, which I guess is "small".
A browser in this panel is fairly painful to use. Here's for example stack overflow:

The left and right panels take up almost all of the real estate. What would be great is a way to collapse those panels so that the content has more space. Is this possible?
Another example is google.com, which, while the main content is visible, the google apps button is far away in the corner, leading to an ugly horizontal scrollbar.

A: You may emulate a device with a small screen, such as the iPad.
All websites that are designed to work with small screens will then act accordingly.
Here are a couple of Chrome extensions that might help:

*

*User-Agent Switcher for Chrome

*Mobile View Switcher

*The following post is highly upvoted but didn't work for me:
How can I view the mobile version of a webpage in Google Chrome for Desktop?


text:
Q: How to call javascript functions from native c++ without touching the browser in Windows without using any library I have some html files and there are java script functions in html files.
I have to call java script functions from Native C++ without touching the browser.
I don't have to use any frameworks and I can't use internet explorer under the my code because internet explorer doesn't support all java script functions.
So please give me a reasonable advise.


text:
Q: RJDBC works fine on windows but not on centos I am trying to connect to Oracle using RJDBC. My R code works fine on windows environment, When I put it on centos VM, I am facing error. JAVA_HOME is properly set. Required packages RJDBC, rJava are also installed properly.
Here is my code:
library(RJDBC)
jdbcDriver <- JDBC(driverClass="oracle.jdbc.OracleDriver", classPath="/users/myusername/tmp/ojdbc6.jar")

dbConnect(jdbcDriver, "jdbc:oracle:thin:@hostname:1521:service", "myusername", "mypwd")

First 2 statements work fine, but dbConnect fails with following error:

Error in .jcall(drv@jdrv, "Ljava/sql/Connection;", "connect",
  as.character(url)[1],  :   java.sql.SQLRecoverableException: IO Error:
  The Network Adapter could not establish the connection

This looks like a common RJDBC problem. I found few questions related to this issue but so far I have not been able to find the solution.


text:
Q: CasperJS randomly fails simple tests I am working on test suite and it's now passing most of the time but not always! Here is a sample of 5 very basic tests (index related tests). In those tests, the two lasts ones (assert url tests) are randomly passing (sometimes both fails, sometimes both succeed, sometime one works and the other fails). I can't find any pattern in the way they pass/fail to re-produce the working conditions, even in debug mode. My first though was a race condition, but it seems like it's not, since the problem persists even with wait() timers. So I though, maybe my implementation of the test/understanding of casper is not correct.
Feel free to give me feedback on the implementation of this test, or any potential improvement allowing the last two tests to pass 100% of the time. Current MMVC framework is backbone and tests are compiled before running, I can provide à compiled (js) version of the test if needed.
Test:
{t} = require '../helpers'
{baseUrl} = require '../config'

mouse = require('mouse').create(casper)

casper.options.loadImages = false
casper.options.verbose = true
casper.options.logLevel = 'debug'

casper.test.begin 'Home page loads correctly', 3, (test) ->
  casper.start "#{baseUrl}page/log-out"
  casper.thenOpen baseUrl, ->
    test.assertHttpStatus 200, 'Status code is 200'
  casper.then ->
    test.assertTitle t('siteName'), "Title is '#{t 'siteName'}'"
  casper.then ->
    test.assertTextExists t('home:featureWhatIsBitcoinTitle'), 'Page body contains intro text'
  casper.run ->
    test.done()

casper.test.begin 'Home page links to sign up page', 1, (test) ->
  casper.start "#{baseUrl}page/log-out"
  casper.thenOpen baseUrl, ->
    @evaluate -> document.querySelector('#signup').click()
  casper.then ->
    test.assertUrlMatch /\/page\/sign-up/, 'Url matches sign up page'
  casper.run ->
    test.done()

casper.test.begin 'Home page links to log in page', 1, (test) ->
  casper.start "#{baseUrl}page/log-out"
  casper.thenOpen baseUrl, ->
    @evaluate -> document.querySelector('a[href="/page/log-in"]').click()
  casper.then ->
    test.assertUrlMatch /\/page\/log-in/, 'Url matches log in page'
  casper.run ->
    test.done()

Stack trace:
casperjs test tests/integration/compiled/tests/home.js
Test file: tests/integration/compiled/tests/home.js
# Home page loads correctly
[info] [phantom] Starting...
[info] [phantom] Running suite: 6 steps
PASS Home page loads correctly (3 tests)
[debug] [phantom] opening url: http://something.dev/page/log-out, HTTP GET
[debug] [phantom] Navigation requested: url=http://something.dev/page/log-out, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] url changed to "http://something.dev/page/log-out"
[debug] [phantom] Navigation requested: url=https://platform.twitter.com/widgets/follow_button.html?screen_name=something&show_screen_name=false, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=https://www.facebook.com/plugins/like.php?href=https%3A%2F%2Fwww.facebook.com%2Fsomething&width&layout=button_count&action=like&show_faces=false&share=false&height=35&appId=000000000000, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=https://www.google.com/recaptcha/api/fallback?k=LOLILOLILOLILOLILOLILOLILOLILOL&hl=en&v=r000000000&t=0&ff=true, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Successfully injected Casper client-side utilities
[debug] [phantom] start page is loaded
[debug] [phantom] opening url: http://something.dev/, HTTP GET
[debug] [phantom] Navigation requested: url=http://something.dev/, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] url changed to "http://something.dev/"
[debug] [phantom] Successfully injected Casper client-side utilities
[info] [phantom] Step anonymous 4/6 http://something.dev/ (HTTP 200)
PASS Status code is 200
[info] [phantom] Step anonymous 4/6: done in 3149ms.
[info] [phantom] Step anonymous 5/6 http://something.dev/ (HTTP 200)
PASS Title is 'NVM | SOMETHING'
[info] [phantom] Step anonymous 5/6: done in 3469ms.
[debug] [phantom] Navigation requested: url=https://platform.twitter.com/widgets/follow_button.html?screen_name=something&show_screen_name=false, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=https://www.facebook.com/plugins/like.php?href=https%3A%2F%2Fwww.facebook.com%2Fsomething&width&layout=button_count&action=like&show_faces=false&share=false&height=35&appId=000000000000, type=Other, willNavigate=true, isMainFrame=false
[info] [phantom] Step anonymous 6/6 http://something.dev/ (HTTP 200)
PASS Page body contains intro text
[info] [phantom] Step anonymous 6/6: done in 3666ms.
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=false
[info] [phantom] Done 6 steps in 3685ms
# Home page links to sign up page
[info] [phantom] Starting...
[info] [phantom] Running suite: 5 steps
PASS Home page links to sign up page (1 test)
[debug] [phantom] opening url: http://something.dev/page/log-out, HTTP GET
[debug] [phantom] Navigation requested: url=http://something.dev/page/log-out, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] url changed to "http://something.dev/page/log-out"
[debug] [phantom] Successfully injected Casper client-side utilities
[debug] [phantom] start page is loaded
[debug] [phantom] opening url: http://something.dev/, HTTP GET
[debug] [phantom] Navigation requested: url=http://something.dev/, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] Navigation requested: url=https://platform.twitter.com/widgets/follow_button.html?screen_name=something&show_screen_name=false, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=https://www.facebook.com/plugins/like.php?href=https%3A%2F%2Fwww.facebook.com%2Fsomething&width&layout=button_count&action=like&show_faces=false&share=false&height=35&appId=000000000000, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] url changed to "http://something.dev/"
[debug] [phantom] Successfully injected Casper client-side utilities
[info] [phantom] Step anonymous 4/5 http://something.dev/ (HTTP 200)
[info] [phantom] Step anonymous 4/5: done in 524ms.
[info] [phantom] Step anonymous 5/5 http://something.dev/ (HTTP 200)
FAIL Url matches sign up page
#    type: assertUrlMatch
#    file: tests/integration/compiled/tests/home.js
#    subject: false
#    currentUrl: "http://something.dev/"
#    pattern: "/\\/page\\/sign-up/"
[info] [phantom] Step anonymous 5/5: done in 651ms.
[debug] [phantom] Navigation requested: url=https://platform.twitter.com/widgets/follow_button.html?screen_name=something&show_screen_name=false, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=https://www.facebook.com/plugins/like.php?href=https%3A%2F%2Fwww.facebook.com%2Fsomething&width&layout=button_count&action=like&show_faces=false&share=false&height=35&appId=000000000000, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=false
[info] [phantom] Done 5 steps in 866ms
# Home page links to log in page
[info] [phantom] Starting...
[info] [phantom] Running suite: 5 steps
PASS Home page links to log in page (1 test)
[debug] [phantom] opening url: http://something.dev/page/log-out, HTTP GET
[debug] [phantom] Navigation requested: url=http://something.dev/page/log-out, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] url changed to "http://something.dev/page/log-out"
[debug] [phantom] Successfully injected Casper client-side utilities
[debug] [phantom] start page is loaded
[debug] [phantom] opening url: http://something.dev/, HTTP GET
[debug] [phantom] Navigation requested: url=http://something.dev/, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] Navigation requested: url=https://platform.twitter.com/widgets/follow_button.html?screen_name=something&show_screen_name=false, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=https://www.facebook.com/plugins/like.php?href=https%3A%2F%2Fwww.facebook.com%2Fsomething&width&layout=button_count&action=like&show_faces=false&share=false&height=35&appId=000000000000, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] url changed to "http://something.dev/"
[debug] [phantom] Successfully injected Casper client-side utilities
[info] [phantom] Step anonymous 4/5 http://something.dev/ (HTTP 200)
[debug] [phantom] url changed to "http://something.dev/page/log-in"
[info] [phantom] Step anonymous 4/5: done in 717ms.
[debug] [phantom] Navigation requested: url=https://platform.twitter.com/widgets/follow_button.html?screen_name=something&show_screen_name=false, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=https://www.facebook.com/plugins/like.php?href=https%3A%2F%2Fwww.facebook.com%2Fsomething&width&layout=button_count&action=like&show_faces=false&share=false&height=35&appId=000000000000, type=Other, willNavigate=true, isMainFrame=false
[info] [phantom] Step anonymous 5/5 http://something.dev/page/log-in (HTTP 200)
PASS Url matches log in page
[info] [phantom] Step anonymous 5/5: done in 761ms.
[debug] [phantom] Navigation requested: url=https://www.google.com/recaptcha/api/fallback?k=LOLILOLILOLILOLILOLILOLILOL=en&v=r000000000&t=0&ff=true, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=false
[info] [phantom] Done 5 steps in 949ms
FAIL 5 tests executed in 5.344s, 4 passed, 1 failed, 0 dubious, 0 skipped.

Details for the 1 failed test:

In tests/integration/compiled/tests/home.js
  Home page links to sign up page
    assertUrlMatch: Url matches sign up page
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] url changed to "about:blank"


text:
Q: CreateMaterialTopTabNavigator navigation is slow CreateMaterialTobTabNavigator is very laggy when navigating between the tabs .
I have used three navigators in my code. drawer Navigator has stack and tab navigator, and the default loading is the 'tab navigator' made with createMaterialTopTabNavigator.
While navigator between the tabs of the tabnavigator , there is some glitches and jittering , which clearly is very annoying .
Tested  in both android and ios devices.


text:
Q: Mixins in TypeScript I'm playing around with TypeScript, and I've got a couple functional mixins, Eventable and Settable, that I'd like to mixin to a Model class (pretend it's something like a Backbone.js model):
function asSettable() {
  this.get = function(key: string) {
    return this[key];
  };
  this.set = function(key: string, value) {
    this[key] = value;
    return this;
  };
}

function asEventable() {
  this.on = function(name: string, callback) {
    this._events = this._events || {};
    this._events[name] = callback;
  };
  this.trigger = function(name: string) {
    this._events[name].call(this);
  }
}

class Model {
  constructor (properties = {}) {
  };
}

asSettable.call(Model.prototype);
asEventable.call(Model.prototype);

The code above works fine, but would not compile if I tried to use one of the mixed-in methods like (new Model()).set('foo', 'bar').
I can work around this by

*

*adding interface declarations for the mixins

*declaring dummy get/set/on/trigger methods in the Model declaration

Is there a clean way around the dummy declarations?

A: The cleanest way to do it, althought it still requires double type declarations, is to define the mixin as a module:
module Mixin {
    export function on(test) {
        alert(test);
    }
};

class TestMixin implements Mixin {
    on: (test) => void;
};

var mixed = _.extend(new TestMixin(), Mixin); // Or manually copy properties
mixed.on("hi");

An alternative to using interfaces is to hack it with classes (Although because of multiple-inheritance, you'll need to create a common-interface for the mixins):
var _:any;
var __mixes_in = _.extend; // Lookup underscore.js' extend-metod. Simply copies properties from a to b

class asSettable {
    getx(key:string) { // renamed because of token-clash in asEventAndSettable
        return this[key];
    }
    setx(key:string, value) {
        this[key] = value;
        return this;
    }
}

class asEventable {
    _events: any;
    on(name:string, callback) {
        this._events = this._events || {};
        this._events[name] = callback;
    }
    trigger(name:string) {
        this._events[name].call(this);
  }
}

class asEventAndSettable {
   // Substitute these for real type definitions
   on:any;
   trigger:any;
   getx: any;
   setx: any;
}

class Model extends asEventAndSettable {
    /// ...
}

var m = __mixes_in(new Model(), asEventable, asSettable);

// m now has all methods mixed in.

As I commented on Steven's answer, mixins really should be a TypeScript feature.

A: There is a new way that was build into Typescript a few years ago, called "mixin classes". It's not well covered in the docs, but they do have a well-commented example to describe the pattern well. Applied to your situation it could look something like:
type Constructor = new (...args: any[]) => {}

function Settable<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    _props: Record<string, any> = {};

    get(key: string) {
      return this._props[key];
    }

    set(key: string, value: any) {
      this._props[key] = value;
      return this;
    }
  }
}

function Eventable<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    _events: Record<string, () => void> = {};

    on(name: string, callback: () => void) {
      this._events[name] = callback;
    }

    trigger(name: string) {
      this._events[name].call(this);
    }
  }
}

class Model extends Settable(Eventable(Object)) {
  constructor(properties = {}) {
    super();
  }
}

This gets you the typing you wanted, so that e.g. you are able to call (new Model()).set('boo', 'bar') with full typing support. No dummy declarations.

A: Here's one way to approach mixins using interfaces and a static create() method.  Interfaces support multiple inheritance so that prevents you from having to redefine the interfaces for your mixins and the static create() method takes care of giving you back an instance of Model() as an IModel (the <any> cast is needed to supress a compiler warning.)  You'll need to duplicate all of your member definitions for Model on IModel which sucks but it seems like the cleanest way to achieve what you want in the current version of TypeScript.
edit: I've identified a slightly simpler approach to supporting mixins and have even created a helper class for defining them.  Details can be found over here.
function asSettable() {
  this.get = function(key: string) {
    return this[key];
  };
  this.set = function(key: string, value) {
    this[key] = value;
    return this;
  };
}

function asEventable() {
  this.on = function(name: string, callback) {
    this._events = this._events || {};
    this._events[name] = callback;
  };
  this.trigger = function(name: string) {
    this._events[name].call(this);
  }
}

class Model {
  constructor (properties = {}) {
  };

  static create(): IModel {
      return <any>new Model();
  }
}

asSettable.call(Model.prototype);
asEventable.call(Model.prototype);

interface ISettable {
    get(key: string);
    set(key: string, value);
}

interface IEvents {
    on(name: string, callback);
    trigger(name: string);
}

interface IModel extends ISettable, IEvents {
}

var x = Model.create();
x.set('foo', 'bar');

A: One solution is to not use the typescript class system , but just the systeme of types and interfaces, in addition to the keyword 'new'.
    //the function that create class
function Class(construct : Function, proto : Object, ...mixins : Function[]) : Function {
        //...
        return function(){};
}

module Test {

     //the type of A
    export interface IA {
        a(str1 : string) : void;
    }

    //the class A
    //<new () => IA>  === cast to an anonyme function constructor that create an object of type IA,
    // the signature of the constructor is placed here, but refactoring should not work
    //Class(<IA> { === cast an anonyme object with the signature of IA (for refactoring, but the rename IDE method not work )
    export var A = <new () => IA> Class(

        //the constructor with the same signature that the cast just above
        function() { } ,

        <IA> {
            //!! the IDE does not check that the object implement all members of the interface, but create an error if an membre is not in the interface
            a : function(str : string){}
        }
    );

    //the type of B
    export interface IB {
        b() : void;
    }
    //the implementation of IB
    export class B implements IB {
        b() { }
    }

    //the type of C
    export interface IC extends IA, IB{
        c() : void;
        mystring: string;
    }

     //the implementation of IC
    export var C = <new (mystring : string) => IC> Class(

        //public key word not work
        function(mystring : string) {

            //problem with 'this', doesn't reference an object of type IC, why??
            //but google compiler replace self by this !!
            var self = (<IC> this);
            self.mystring = mystring;
        } ,

        <IC> {

            c : function (){},

            //override a , and call the inherited method
            a: function (str: string) {

                (<IA> A.prototype).a.call(null, 5);//problem with call and apply, signature of call and apply are static, but should be dynamic

                //so, the 'Class' function must create an method for that
                (<IA> this.$super(A)).a('');
            }

        },
        //mixins
        A, B
    );

}

var c = new Test.C('');
c.a('');
c.b();
c.c();
c.d();//ok error !


text:
Q: How to share the screen in a multiplayer game? I made a game in java all the GUI and key events etc are done using javafx.
The game is Battle City http://nintendo8.com/game/245/battle_city/
Now I have made it multiplayer using RMI.(client and server)
The other player movement etc is fine.
I am now stuck as to how I can share the screen between client and the server.
I have thought of serializing the root node and all the objects in it and sending it over to client in a while loop, but is this doable? Will it work?
And is there any better option?


text:
Q: How do I extract the metadata of a local image in Javascript? I would like to get the metadata of an image that a user drags and drops into a webpage. I have the drag and drop set up. However, the image isn't actually uploaded to a server. It's accessed locally. Can I still get the metadata from the image using Javascript? If so, how do I do this? What good libraries are there?
If not, do I absolutely have to upload the image in order to extract the metadata? What's the fastest way to upload an image in Javascript?

A: There is a library: ImageInfo - read image metadata with JavaScript. Between that and local file access in HTML5 you should be able to get it.
UPDATE
New link for the imageinfo library.

A: Basically, JavaScript cannot "touch" your local file, you just can do that using HTML5 + JavaScript or using Flash ActionScript


text:
Q: How to manage production and development credentials using Facebook iOS SDK Symptoms
My app is using Facebook to let users log in. It works fine while debugging from XCode and testing through AdHoc deployment, in order to have external testers we submitted our app for review but it seems that Facebook is complaining during the OAuth Process "App Not Setup: The developers of this app have not setup this app properly for Facebook Login".
Hypothesis
The FacebookDisplayName and FacebookAppId present in the Custom iOS target properties in the info section of my target in XCode are matching the Facebook app development version. Somehow, the SDK must detect that during the review the app is not anymore in development and an error occures.
Question
How do I define in that target some Custom iOS target properties with different release and debug values?

A: You can add a user defined setting in Target's settings with different values for each scheme (Debug, Release, Ad-Hoc, AppStore etc) and use the user defined variable in info.plist file (or as you call it Custom iOS target properties).
Here is an example of how i did it for an app's bundle identifier. I wanted separate bundle identifier and server URLs for the Debug and AdHoc versions so both could be installed and tested on same device:

*

*Add required data as a user defined settings in Target Settings.

*Set different values for the variable for different scheme. (Make sure to check the target settings reflects the changes and not just project settings.):
EDIT: Detailed image for adding user defined settings:

*In above image, BUNDLE_ID_PREFIX and BUNDLE_ID_SUFFIX have different values for each scheme.

*Use this variable instead of default values in info.plist:

You will by default use debug scheme for running the app from xcode. If you use release scheme for archiving the app for upload, it will automatically pick up the correct value from target settings.


text:
Q: How to add unique column in sybase? I have a sybase db table in which i need to add a new column.
The conditions: The column must not allow nulls and be unique.
what is the alter table sql to achieve this?
EDIT:
It is a varchar type column.Yes the table as of now is empty, but when filled it is ensured that unique values would be filled in.
I tired executing
alter table Test add Name varchar not null unique

i get error saying default value must be specified as not null is given.
but i want to add unique constraint so do i really need to specify default?
thanks

A: Unique values are specified as part of an index on the column, not in the column definition itself.
Try:
alter table Test add Name varchar not null
create unique index index_name_unique on Test (Name)

The ASE reference manual can help with more detail.

A: Once a table has been created Sybase ASE does not allow addition of NOT NULL column directly unless a default is specified for the column. However, if the table is still empty you can do the following -

*

*First add the new column as a NULL column to the table using alter table command -

alter table Test add Name varchar(100) null

*

*Once this has been done, try modifying the same column Name in the table Test using the alter table script -

alter table Test modify Name varchar(100) NOT NULL
and you will see that you are able to modify the Name column to a NOT NULL column using these steps. This is because at this time Sybase server checks as there is no data in the table hence the NOT NULL constraint is not checked and the column is made NOT NULL. Hence, we are able to skip the default constraint.
In case there would have been some data already present in the table Test, then we need to add one more step in between steps 1 and 2 which will add default values to the existing rows in the table. This can be done via a script for previous data and then following the step 2.
To make the column only allow unique values for the column you need to add a unique key constraint using the following syntax -
alter table Test add constraint UK1 unique(Name)


text:
Q: How do I activate C++ 11 in CMake? When I try to run a CMake generated makefile to compile my program, I get the error that

range based for loops are not supported in C++ 98 mode.

I tried adding add_definitions(-std=c++0x) to my CMakeLists.txt, but it did not help.
I tried this too:
if(CMAKE_COMPILER_IS_GNUCXX)
    add_definitions(-std=gnu++0x)
endif()

When I do g++ --version, I get:

g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1

I have also tried SET(CMAKE_CXX_FLAGS "-std=c++0x"), which also does not work.
I do not understand how I can activate C++ 11 features using CMake.

A: I am using
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
        message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()

But if you want to play with C++11, g++ 4.6.1 is pretty old.
Try to get a newer g++ version.

A: The easiest way to set the Cxx standard is:
 set_property(TARGET tgt PROPERTY CXX_STANDARD 11)

See the CMake documentation for more details.

A: Modern cmake offers simpler ways to configure compilers to use a specific version of C++. The only thing anyone needs to do is set the relevant target properties. Among the properties supported by cmake, the ones that are used to determine how to configure compilers to support a specific version of C++ are the following:

*

*CXX_STANDARD sets the C++ standard whose features are requested to build the target. Set this as 11 to target C++11.

*CXX_EXTENSIONS, a boolean specifying whether compiler specific extensions are requested.  Setting this as Off disables support for any compiler-specific extension.
To demonstrate, here is a minimal working example of a CMakeLists.txt.
cmake_minimum_required(VERSION 3.1)

project(testproject LANGUAGES CXX )

set(testproject_SOURCES
    main.c++
    )

add_executable(testproject ${testproject_SOURCES})

set_target_properties(testproject
    PROPERTIES
    CXX_STANDARD 11
    CXX_EXTENSIONS off
    )

A: In case you want to always activate the latest C++ standard, here's my extension of David Grayson's answer, in light of the recent (CMake 3.8 and CMake 3.11) additions of values of 17 and 20 for CMAKE_CXX_STANDARD):
IF (CMAKE_VERSION VERSION_LESS "3.8")
    SET(CMAKE_CXX_STANDARD 14)
ELSEIF (CMAKE_VERSION VERSION_LESS "3.11")
    SET(CMAKE_CXX_STANDARD 17)
ELSE()
    SET(CMAKE_CXX_STANDARD 20)
ENDIF()

# Typically, you'll also want to turn off compiler-specific extensions:
SET(CMAKE_CXX_EXTENSIONS OFF)

(Use that code in the place of set (CMAKE_CXX_STANDARD 11) in the linked answer.)

A: CMake 3.1 introduced the CMAKE_CXX_STANDARD variable that you can use.  If you know that you will always have CMake 3.1 or later available, you can just write this in your top-level CMakeLists.txt file, or put it right before any new target is defined:
set (CMAKE_CXX_STANDARD 11)

If you need to support older versions of CMake (quite unlikely these days), here is a macro I came up with that you can use:
macro(use_cxx11)
  if (CMAKE_VERSION VERSION_LESS "3.1")
    if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
      set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")
    endif ()
  else ()
    set (CMAKE_CXX_STANDARD 11)
  endif ()
endmacro(use_cxx11)

The macro only supports GCC right now, but it should be straight-forward to expand it to other compilers.
Then you could write use_cxx11() at the top of any CMakeLists.txt file that defines a target that uses C++11.
CMake issue #15943 for clang users targeting macOS
If you are using CMake and clang to target macOS there is a bug that can cause the CMAKE_CXX_STANDARD feature to simply not work (not add any compiler flags).  Make sure that you do one of the following things:

*

*Use cmake_minimum_required to require CMake 3.0 or later, or

*Set policy CMP0025 to NEW with the following code at the top of your CMakeLists.txt file before the project command:
  # Fix behavior of CMAKE_CXX_STANDARD when targeting macOS.
  if (POLICY CMP0025)
    cmake_policy(SET CMP0025 NEW)
  endif ()

A: On modern CMake (>= 3.1) the best way to set global requirements is:
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

It translates to "I want C++11 for all targets, it's not optional, I don't want to use any GNU or Microsoft  extensions."
As of C++17, this still is IMHO the best way.
Source: Enabling C++11 And Later In CMake

A: As it turns out, SET(CMAKE_CXX_FLAGS "-std=c++0x") does activate many C++11 features. The reason it did not work was that the statement looked like this:
set(CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS} -g -ftest-coverage -fprofile-arcs")

Following this approach, somehow the -std=c++0x flag was overwritten and it did not work. Setting the flags one by one or using a list method is working.
list( APPEND CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS} -g -ftest-coverage -fprofile-arcs")

A: For CMake 3.8 and newer you can use
target_compile_features(target PUBLIC cxx_std_11)

If you want the generation step to fail if the toolchain cannot adhere to this standard, you can make this required.
set_target_properties(target PROPERTIES CXX_STANDARD_REQUIRED ON)

If you want strict adherence to standard C++ i.e. avoid C++ extensions offered by your compiler (like GCC's -std=gnu++17), additionally set
set_target_properties(target PROPERTIES CXX_EXTENSIONS OFF)

This is documented in detail at An Introduction to Modern CMake -> Adding Features -> C++11 and Beyond.  It also offers advice on how to achieve this on older versions of CMake if you're constrained to those.

A: What works for me is to set the following line in your CMakeLists.txt:
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

Setting this command activates the C++11 features for the compiler and after executing the cmake .. command, you should be able to use range based for loops in your code and compile it without any errors.

A: I think just these two lines are enough.
set(CMAKE_CXX_STANDARD 11)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

A: The modern way is to specify the minimum required standard to C++11 with:
target_compile_features(foo PUBLIC cxx_std_11)

This way:

*

*CMake can honor default C++ standard of the compiler if it's greater than C++11

*You can clearly specify whether C++ standard is required at build time, consume time, or both. This is nice for libraries.

*Public compile features are propagated to downstream targets, so it comes for free in those targets even if they don't directly use this feature.

*Users can externally set another C++ standard (more recent basically), with CMAKE_CXX_STANDARD, either from command line or CMake presets. If you hardcode CMAKE_CXX_STANDARD in a CMakeLists, nobody can override the C++ standard without editing your CMakeLists, which is not very pleasant.

It requires CMake >= 3.8

A: The CMake command target_compile_features() is used to specify the required C++ feature cxx_range_for. CMake will then induce the C++ standard to be used.
cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)
project(foobar CXX)
add_executable(foobar main.cc)
target_compile_features(foobar PRIVATE cxx_range_for)

There is no need to use add_definitions(-std=c++11) or to modify the CMake variable CMAKE_CXX_FLAGS, because CMake will make sure the C++ compiler is invoked with the appropriate command line flags.
Maybe your C++ program uses other C++ features than cxx_range_for. The CMake global property CMAKE_CXX_KNOWN_FEATURES lists the C++ features you can choose from.
Instead of using target_compile_features() you can also specify the C++ standard explicitly by setting the CMake properties
CXX_STANDARD
and
CXX_STANDARD_REQUIRED for your CMake target.
See also my more detailed answer.

A: The easiest way:
add_compile_options(-std=c++11)

A: This is another way of enabling C++11 support,
ADD_DEFINITIONS(
    -std=c++11 # Or -std=c++0x
    # Other flags
)

I have encountered instances where only this method works and other methods fail. Maybe it has something to do with the latest version of CMake.

A: You can use the following. This automatically modifies the feature based on your environment.
target_compile_features(your_target INTERFACE cxx_std_20)

For example,

*

*on Gnu/Linux the following adds -std=gnu++20

*on Windows with Clang/Ninja it becomes -std=c++20

*on Windows with MSVC it becomes /std=c++20
So you support as many as environments possible.

A: In case you stumble on that same error using cmake as i did.
You need to set
set (CMAKE_CXX_STANDARD 11)

to activate threading because it is only supported from c++11 ++
hope that helps

A: OS X and Homebrew LLVM related:
Don't forget to call cmake_minimum_required(VERSION 3.3) and project() after it!
Or CMake will insert project() implicitly before line 1, causing trouble with Clang version detection and possibly other sorts of troubles. Here is a related issue.


text:
Q: Touch event while display off Sorry for stupid question, but can I listening touch events from android phone, while display is off? Or touch system works only when display is ON..?

A: Only when the display is on since the touchscreen needs power to detect touches.
However, there is some research to re-register the sensors when the screen is off, so maybe you'll have some luck if you follow that route.
Useful Resources:

*

*Getting Android Sensor Events While The Screen is Off

*Android docs - Partial wake lock

*Example app on gitHub


text:
Q: What does "Touchpad mode" change in Flight Control HD? Flight Control HD, available for Windows and Mac OS X, has a little option called Touchpad mode. The in-game help says: Ensure "Trackpad mode" is enabled in the options for optimized controls.
Well, "optimized controls" is too vague for me. I want to know (exactly) how it changes the gameplay interaction.
From the few minutes I played with it enabled, I didn't notice any difference.

A: In order to draw a path for a plane with Trackpad mode OFF:

*

*You must press and hold down the left mouse button while drawing.

In order to draw a path for a plane with Trackpad mode ON:

*

*You can either press and hold down the left mouse button while drawing.

*Or you can click on a plane and then move the mouse without any button pressed.

In other words:

*

*Trackpad mode OFF: Click-and-drag.

*Trackpad mode ON: Either click-and-drag or click-move-click.


text:
Q: Natbib giving single character instead of author-year I am using MiKTeX 2.9/TeXmaker. When I cite(\citep{}) with the natbib package, I get random characters e.g [a],[x] etc, instead of e.g [John1998]. I ran PdfLatex->Bibtex->Pdflatex->Pdflatex, but still getting the same result. I am writing my first document in LaTeX and its my thesis, so please forgive if I overlooked any minor error or method.
\documentclass[a4paper,12pt]{book}
\usepackage[square,authoryear]{natbib}
\usepackage{hyperref}

\begin{document}
Photonic crystals are a class of materials
that are either man made\citep{Yablonovitch1993} or
naturally found\citep{Zi2003}
.
.
.
.
.
\backmatter
\bibliographystyle{plainnat}
\bibliography{references}
\end{document}

Output:

Photonic crystals are a class of materials that are either man made[b,
  a] or naturally found [e, i].

Within BibTeX file
@ARTICLE{Yablonovitch1993,
  author = {Yablonovitch, E.},
  title = {Photonic band-gap structures},
  journal = {J. Opt. Soc. Am. B},
  year = {1993},
  volume = {10},
  pages = {283-295},
  number = {2}
}

@ARTICLE{Zi2003,
  author = {Zi, Jian and Yu, Xindi and Li, Yizhou and Hu, Xinhua and Xu, Chun
    and Wang, Xingjun and Liu, Xiaohan and Fu, Rongtang},
  title = {Coloration strategies in peacock feathers},
  journal = {Proceedings of the National Academy of Sciences},
  year = {2003},
  volume = {100},
  pages = {12576-12578},
  number = {22},
  abstract = {We report the mechanism of color production in peacock feathers. We
    find that the cortex in differently colored barbules, which contains
    a 2D photonic-crystal structure, is responsible for coloration. Simulations
    reveal that the photonic-crystal structure possesses a partial photonic
    bandgap along the direction normal to the cortex surface, for frequencies
    within which light is strongly reflected. Coloration strategies in
    peacock feathers are very ingenious and simple: controlling the lattice
    constant and the number of periods in the photonic-crystal structure.
    Varying the lattice constant produces diversified colors. The reduction
    of the number of periods brings additional colors, causing mixed
    coloration.}
}

.bbl file contents (Only the above two references are shown. I deleted the references from other parts of my document for convenience):
\begin{thebibliography}{29}
\providecommand{\natexlab}[1]{#1}
\providecommand{\url}[1]{\texttt{#1}}
\expandafter\ifx\csname urlstyle\endcsname\relax
  \providecommand{\doi}[1]{doi: #1}\else
  \providecommand{\doi}{doi: \begingroup \urlstyle{rm}\Url}\fi

\bibitem[Yablonovitch(1993)]{Yablonovitch1993}
E.~Yablonovitch.
\newblock Photonic band-gap structures.
\newblock \emph{J. Opt. Soc. Am. B}, 10\penalty0 (2):\penalty0 283--295, 1993.

\bibitem[Zi et~al.(2003)Zi, Yu, Li, Hu, Xu, Wang, Liu, and Fu]{Zi2003}
Jian Zi, Xindi Yu, Yizhou Li, Xinhua Hu, Chun Xu, Xingjun Wang, Xiaohan Liu,
  and Rongtang Fu.
\newblock Coloration strategies in peacock feathers.
\newblock \emph{Proceedings of the National Academy of Sciences}, 100\penalty0
  (22):\penalty0 12576--12578, 2003.

\end{thebibliography}

A: I carefully sifted through the code, removing bits and pieces and checked for the output. It seems \usepackage{newclude} was the culprit. Without newclude, the citation is displayed perfectly as desired i.e. Author-year.


text:
Q: Blender python convert color to 255 scale I'm doing a bit of blender scripting atm. I have a python script that works with numpy and opencv to do some image processing and I wanna use that script within blender. The main issue is that when I read an image from blender it comes with pixel values in sRGB. OpenCV is bad with sRGB and therefore I cannot use it properly.
I need a way to convert those sRGB pixels to RGB on the 255 scale or to HEX. I have checked online thoroughly and could not find much relevant to this conversion, apart from sRGB to linear RGB function which only makes the numbers much smaller. Initially I thought that blender stores the pixels in [0,1) range which can be converted to [0,255] by just multiplying, but obv I was wrong as that doesn't work.
Would be nice if somebody familiar with sRGB could explain how you get from those small values to a HEX code or a RGB value on a 255 scale.
Thanks!
Original Image:
original pix
Some Code Examples:
converted to numpy array with shape(w,h,3) also multiplying by 255
img = bpy.data.images.load(finalpath,True)
pixelsImg = np.array(img.pixels)
pixelsImg.shape = (img.size[0],img.size[1],4)
pixelsImg = np.delete(np.dot(pixelsImg,255),3,2)
cv2.imshow('pix2',pixelsImg)

Image now looks like this:
after converting to opencv readable format
the function meant to convert sRGB to linear RGB:
def s2lin(x):
a = 0.055
if x <=0.04045 :
    y = x * (1.0 / 12.92)
else:
    y = pow( (x + a) * (1.0 / (1 + a)), 2.4)
return y

after applying the function:
pixelsImg = np.array(img.pixels)
pixelsImg.shape = (img.size[0],img.size[1],4)

result =np.vectorize(s2lin)
resultList = result(pixelsImg)

cv2.imshow('p',resultList)
cv2.waitKey()
cv2.destroyAllWindows()

The resulting image is fully black.


text:
Q: How to move some hook in separate file ? React hook I want to separate my function with hook because i have a lot of in one file....
example of code:
  const collectOrganisationUnitNode = useCallback((treeData) => {
       // someLogic
  }, []);

  const handleCancelClick = useCallback(() => {
     .../some logic
  }, [hideModal, selected, multiselect, tree]);

I want to remove from index.js and set to another file then just import and using inside index.js
is that possible ?

A: You could make a custom hook that returns these functions.
const customHook = () => {
  const collectOrganisationUnitNode = useCallback((treeData) => {
    // someLogic
  }, []);

  const handleCancelClick = useCallback(() => {
    //some logic
  }, [hideModal, selected, multiselect, tree]);
  return {
    collectOrganisationUnitNode,
    handleCancelClick
  }
};

Then used like so inside your component
  const { collectOrganisationUnitNode, handleCancelClick } = customHook();


text:
Q: Bootable usb not recognized in UEFI disabled mode unable to dual boot I want to dual boot my laptop(lenovo G580). It currently has windows 8.1(unactivated). Now I also want to install ubuntu 14.04 64-bit, so basically I was trying to dual boot using bootable usb drive. When I first try booting ubuntu, in the process, it says no previous OS installed i.e., its not recognizing windows 8.1, so I search google and somewhere found that I need to disable UEFI mode. After disabling UEFI mode I again tried to install ubuntu, but this time the usb stick is not getting recognized(or OS inside is not getting recognized, bcoz the boot manager recognizes HDD and tries to boot from it) and this below statement on a black screen comes out and then nothing happened.

"An operating system wasn't found. Try disconnecting any drives that don't contain an operating system.
Press any key to restart. "

Please some one help I want to install ubuntu over windows.
Also, please do tell me if any other info is required!

A: The advice you received to disable UEFI-mode booting was probably bad. Pre-installed Windows 8 and later are almost always installed in EFI/UEFI mode, and setting up a BIOS/EFI-mode dual-boot is almost always much more hassle than setting up an EFI/EFI-mode dual-boot. In other words, you're creating problems for yourself by doing what you did.
An exception to the preceding is if you installed (or re-installed) Windows 8.1 yourself. In this case, if you did the installation in BIOS/CSM/legacy mode, it could be you've got leftover GPT data on an MBR disk. This Web page of mine covers this topic.
Your initial problem ("it says no previous OS installed") is probably just a matter that requires use of the "Something Else" installation option, as described in this askubuntu.com question and answers. If you get into the partitioner and it shows the disk as being unpartitioned, though, then you've got some other problem -- probably either stray RAID data or partition table trouble. See my Web page, referenced earlier, for information on such problems. If you suspect partition table trouble and you aren't sure how to proceed, you'll need to post more detailed information, such as the output of:
sudo gparted /dev/sda print
sudo gdisk -l /dev/sda
sudo fdisk -l /dev/sda

These commands all assume you've got one disk (/dev/sda). If you've got multiple disks, you must repeat each command for all your disks.


text:
Q: How to run R script containing interactive user options from a batch file I have written an interactive R Script which gives the user certain options using which the rest of the execution takes place. These inputs have to be optional as required by the user. One other requirement from the user was that he did not want to manually select the entire script in RStudio just to execute it. I tried to create a BAT file for this execution. However, the program does not execute. Below is an example user interactive script.
FYI_Splitter <- winDialog(type = "yesno","Do you want to remove FYI from base file?

Yes = Remove FYI
No = Do Not Remove FYI")

Below is what I am using to execute the BAT file.
"C:\Program Files\R\R-3.4.2\bin\Rscript.exe" "<Path_of_file>\Test_Program.R"

I came to know that batch file execution does not support interactive sessions. Is there any way to make interactive sessions in R execute without selecting the entire code in RStudio? Any help on this would be appreciated.

A: You could try
echo source("<Path_of_file>\Test_Program.R") | R.exe --ess --vanilla

The interactive() command in R then returns TRUE for me.


text:
Q: c# linq join parent and child in generic extension method i've got many ef core entities with a possibility to join a shared child table ( without FK-s). I created a generic join extension method, but got a bit stuck returning the main parent entity with the child mapped to it.
Heres what i've got :
public interface IBaseEntity
    {
        int Id { get; set; }
    }

public interface IBaseAttachmentEntity:IBaseEntity
    {
         ICollection<ResourceAttachment> ResourceAttachment { get; set; }
    }
public  class ResourceAttachment:BaseEntity
{
    //PK- Id of the parent table
    public long ParentId { get; set; }
    // type or enum of a parent table. Should point to which table it points to
    public string ResourceType { get; set; }

    public string AttachmentType { get; set; }

    public string Value { get; set; }
}

public static class EFCoreExtension
            {
    //this must be a generic method, want to use it for ~30 tables where the entity inherits IBaseAttachmentEntity
                public static IQueryable<TEntity> IncludeResourceAttachment<TEntity>
                    (this IQueryable<TEntity> queryable,IServiceProvider serviceProvider) where TEntity : class,IBaseAttachmentEntity
                {
                    var className = queryable.ElementType.Name;
                    var attachmentRepository = serviceProvider.GetRequiredService<IResourceAttachmentRepository>();
                    var attachments = attachmentRepository
                        .FindAllQueriable(x => x.ResourceType == className); //this part is fine

                    var joined = (from q in queryable
                            join a in attachments on q.Id equals a.ParentId into qa
                            from a in qa.DefaultIfEmpty()
                            select  new {Parent=q,Attachments = qa}); // joining the child table, ending up with a tuple like result

                    return joined.Select(x => x.Parent); // need to return the Parent together with Parent.ResourceAttachment which id defined in the
                }

            }

want to use the extension like this:
   var result =  _deviceServiceService.FindAllQueriable(CurrentUserId(), matchFilter)
                .IncludeResourceAttachment(_serviceProvider).ToList();

EDIT:
i have also created a minimal sample project to run. Uses In memory Db with data seeding
https://github.com/rauntska/EFGenericChildJoin
Thanks!

A: THis might not be what you want, but you might have to settle for it:
public static IEnumerable<TEntity> IncludeResourceAttachment<TEntity>
    (this IQueryable<TEntity> queryable, IServiceProvider serviceProvider) where TEntity : class, IBaseAttachmentEntity
{
    var className = queryable.ElementType.Name;
    var dataContext = serviceProvider.GetRequiredService<DataContext>();
    var attachments = dataContext.Set<ResourceAttachment>().Where(x => x.ResourceType == className);

    var joined =
        from q in queryable
        join a in attachments on q.Id equals a.ParentId into qa
        select new { Parent = q, Attachments = qa };

    foreach (var x in joined)
        foreach (var y in x.Attachments)
            x.Parent.ResourceAttachment.Add(y);

    return joined.Select(x => x.Parent);
}


text:
Q: Responsive header menu with background image I'm trying to create a responsive header with a background image. When I add the off-canvass menu hamburger icon, I get a band of body background displayed at the top of the viewport.
What am I doing wrong?

  html,
  body {
    margin: 0;
    padding: 0;
    height: 100%;
    position: relative;
    background: red;
    font: 16px/1.75 Verdana, Arial, Helvetica, sans-serif
  }
  .toggle {
    position: absolute;
    right: 0.15em;
    cursor: pointer;
    color: white
  }
  .wrapper {
    max-width: 78.75em;
    margin: auto;
    -webkit-transform: translate(0, 0);
    -ms-transform: translate(0, 0);
    transform: translate(0, 0)
  }
  .container {
    background: yellow;
    min-height: 100%;
    padding: 0;
    margin: 0
  }
  #header label {
    padding: 0 0.125em;
    font: 2.875em/1.4375em Arial
  }
  #header label:hover,
  #menu label:hover {
    color: grey
  }
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />

        ≡

Test header 4

Lorem ipsum dolor sit amet, no pro mundi graeco pertinacia, et lorem conceptam complectitur sea. Eam no persecuti scriptorem. Ius an sadipscing consectetuer. Purto nostrum mel in. Ne sea congue homero.

A:
I think problem is solved, have a look

html,
  body {
    margin: 0;
    padding: 0;
    height: 100%;
    position: relative;
    background: red;
    font: 16px/1.75 Verdana, Arial, Helvetica, sans-serif
  }
  .toggle {
    position: absolute;
    right: 0.15em;
    cursor: pointer;
    color: white
  }
  .wrapper {
    max-width: 78.75em;
    margin: auto;
    -webkit-transform: translate(0, 0);
    -ms-transform: translate(0, 0);
    transform: translate(0, 0)
  }
  .container {
    background: yellow;
    min-height: 100%;
    padding: 0;
    margin: 0
  }
  #header label {
    padding: 0 0.125em;
    font: 2.875em/1.4375em Arial
  }
  #header label:hover,
  #menu label:hover {
    color: grey
  }
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />

        ≡

Test header 4

Lorem ipsum dolor sit amet, no pro mundi graeco pertinacia, et lorem conceptam complectitur sea. Eam no persecuti scriptorem. Ius an sadipscing consectetuer. Purto nostrum mel in. Ne sea congue homero.


text:
Q: Animating clipping area in  element I've used stackoverflow.com as a source of inspiration and problem-solving for many months now. I've just never run into a problem without a solution so far, which is the reason why I'd first like to introduce myself hereby, and to share my problem with everyone who's interested.
For the past couple of weeks I've tried animating certain shapes and lines on a canvas element, in order to create some interesting effects - such as handwriting or similar.
In order to achieve this, I use some technique which utilizes the .clip() command of the canvas element, to hide and gradually reveal areas under which a pre-rendered image (forms, lines...) "waits".
The problem I run into here, has to do with the variables which determine the clipping area in the canvas element. It seems to have some strange problem with increasing (but not decreasing) the values in the animation.
And since all this sounds very weird, which I am aware of, here is the relevant part of the code I am talking about.
$(document).ready(function() {
    var ctx = $( "#canvas" )[0].getContext("2d");
    ctx.fillStyle = "#a00";
    var recW = 200;

    function animate() {
        ctx.clearRect(0,0,400,400);

        ctx.beginPath();
        ctx.rect(50,50,recW,100);
        ctx.clip();

        ctx.beginPath();
        ctx.arc(250,100,90,0,Math.PI*2,true);
        ctx.fill();

        recW--;

        if (recW == 150) clearInterval(run);
    }
    var run = setInterval(function() { animate(); },60);
});

The above code works perfectly fine. It draws a rectangle in a 400*400 canvas, uses it as a clipping region, draws the circle afterwards, and this circle is then clipped accordingly. Through the animation Interval, the length of the clipping-rectangle is then decreased to a test-value of 150. So far, so good. But here comes the part which has kept me riddled for hours on end:
$(document).ready(function() {
    var ctx = $( "#canvas" )[0].getContext("2d");
    ctx.fillStyle = "#a00";
    var recW = 150;

    function animate() {
        ctx.clearRect(0,0,400,400);

        ctx.beginPath();
        ctx.rect(50,50,recW,100);
        ctx.clip();

        ctx.beginPath();
        ctx.arc(250,100,90,0,Math.PI*2,true);
        ctx.fill();

        recW++;

        if (recW == 200) clearInterval(run);
    }
    var run = setInterval(function() { animate(); },60);
});

If I turn the whole animation around, begin with a width of 150 for the clipping rectangle, and increase it with recW++ up to the test-value of 200, suddenly the animation does no longer work. The gradual increase of the variable works without problems, but the visible clipping area does not grow.

I suspect that I am perhaps just overlooking the obvious here, but I simply cannot seem to find the error and I'd be very thankful if somebody could point me into the right direction ;)
Thanks a lot
Tricon

A: Your problem is a tricky one to debug unless you have a lot of experience (which I didn't either).
The reason you can animate the shape getting smaller and not it getting larger is because, I suspect, you are ANDing the clips together. Therefore, as they get smaller, everything looks fine since you are expecting the smallest clip area. When the clip is getting larger, however, you are ANDing with the original small clip area, so it appears like there is no animation.
To fix this you need to place a restore() call at the end of your clip. However, for this to work, you also need a save() call at the beginning of your clip. Finally, I added a bordering box to indicate where the clip is exactly, and since this is a fill and a stroke, I placed another beginPath statement to not stroke the circle outside of the clip area (which we just restored from).
Here is the full jsFiddle code
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.fillStyle = "#a00";
var recW = 150;

function animate2() {
    ctx.clearRect(50,50,canvas.width,recW - 1);

    ctx.save();

    ctx.beginPath();
    ctx.rect(50, 50, recW, recW);
    ctx.clip();

    ctx.beginPath();
    ctx.arc(250,100,90,0,Math.PI*2,true);
    ctx.fill();

    ctx.restore();
    ctx.beginPath();
    ctx.rect(50 - 1, 50 - 1, recW + 2, recW + 2);
    ctx.lineWidth = 10;
    ctx.stroke();
    console.log(recW);
    recW++;

    if (recW == 300) clearInterval(run);
}
var run = setInterval(function() { animate2(); },5);

A: Here is a nice guide on how to animate a clipping path. Your problem is that once the clip is made, you have to take it away in order to grow it, so you use save states and canvas wipes to make this effect.
Here is some example code.
<canvas  id="slide29Canvas2" width="970px" height="600px"></canvas>

<script>
    // Grabs the canvas element we made above
var ca1=document.getElementById("slide29Canvas1");

// Defines the 2d thing, standard for making a canvas
var c1=ca1.getContext("2d");

// Creates an image variable to hold and preload our image (can't do animations on an image unless its fully loaded)
var img1 = document.createElement('IMG');

// Loads image link into the img element we created above
img1.src = "http://tajvirani.com/wp-content/uploads/2012/03/slide29-bg_1.png";

// Creates the first save event, this gives us a base to clear our clipping / mask to since you can't just delete elements.
c1.save();

// Our function for when the image loads
img1.onload = function () {

    // First call to our canvas drawing function, the thing that is going to do all the work for us.
        // You can just call the function but I did it through a timer
    setTimeout(function() { drawc1r(0); },5);

        // The function that is doing all the heavy lifting. The reason we are doing a function is because
        // to make an animation we have to draw the circle (or element) frame by frame, to do this manually would be to time
        // intensive so we are just going to create a loop to do it. 'i' stands for the radius of our border
        // so over time our radius is going to get bigger and bigger.
    function drawc1r(i) {

        // Creates a save state. Imagine a save state like an array, when you clear one it pops last element in the array off the stack
        // When you save, it creates an element at the top of the stack. So if we cleared without making new ones, we would end up with nothing on our stage.
    c1.save();

        // This clears everything off the stage, I do this because our image has transparency, and restore() (the thing that pops one off the stack)
        // Doesn't clear off images, and so if we stick an image on the stage over and over, the transparency will stack on top of each other and
        // That isn't quite what we want.
    c1.clearRect(0, 0, ca1.width, ca1.height);

        // Adds one to the radius making the circle a little bigger with every step
    i++;

        // Tells canvas we are going to start creating an item on the stage - it can be a line, a rectangle or any shape you draw, but whatever
        // after this path will be added to the clip when its called. I can have 3 rectangles drawn and that would make a clip.
    c1.beginPath();

        // Can't make a true circle, so we make an arced line that happens to trace a circle - 'i' is used to define our radius.
    c1.arc(853, 320, i, 0, 2 * Math.PI, false);

        // After everything is defined, we make a clip area out of it.
    c1.clip();

        // Now that we have the clip added to it, we are going to add the image to the clip area.
    c1.drawImage(img1, 0, 0);

        // This pops one off the stack which gets rid of the clip so we can enlarge it and make it again on the next pass
    c1.restore();

        // Here is the final size of the circle, I want it to grow the circle until it hits 800 so we set a timeout to run this function again
        // until we get the size we want. The time in milliseconds pretty much defines your framerate for growing the circle. There are other
        // methods for doing this that give you better frame rates, but I didn't have much luck with them so I'm not going to include them.
    if(i < 800) {
        setTimeout(function() { drawc1r(i); },5);
    }

}


text:
Q: How to use OptaPlanner ValueRange based on a planning entity's value? Hey pretty new to optaplanner. What I have is a process planning entity that has an "availability zone" and set of computers that also have an assigned availability zone. Since a process can only be put on a computer with the same availability zone I wanted to use the ValueRangeProvider to narrow down the possible selections to include only those computers (similar to how the example in the documentation narrows down rooms based on the teachers department). But there is no direct connection from availability zones to the lower level entities (i.e. computers) the object I am working with currently only points up.
I was thinking that I could just pass in the list of computers to every process and just create a valuerange list based on that similar to what I did below, but I was hoping for a more elegant solution. I was looking at filters but I could not figure out how to create a filter to restricted a possible move based on the planning entity and that entity's planning variable.
@PlanningVariable(strengthComparatorClass = ComputerStrengthComparator.class)
public Computer getComputer() {
    return computer;
}
@ValueRangeProvider(id="computerRange")
public List<Computer> getPossibleComputers(){
    return computers.stream().filter(computer -> computer.getAvalibilityZone().equals(this.getAvalibilityZone())).collect(Collectors.toList());
}

If anyone knows of something I missed or has any ideas I would much appreciate the help.

A: That code actually works as far as I can tell. See docs "Value Range Provider from entity" (as opposed to "from solution").
That being said, it does have limitations: some features do not support it and will fail fast if combined with value ranges "from entity" - most do these days so I wouldn't worry about it. Furthermore, it prevents the Local Search from breaking that hard constraints to escape a local optima, but that's usually not a problem.


text:
Q: Looking For Ideas of Vectorization I'm looking to create a calculated column based value from another column with few conditions.

*

*Evaluate only when ['EVENT'] is 'Injecting'

*Find the first ['EVENT_TIME'] where the ['EVENT'] is 'Flowing'

*group result based on unique id ['CMPL_RC_UID']

here's my code
def next_event(row,table):
    if row['EVENT'] == 'Injecting':
        return table[(table['EVENT'] == 'Flowing') & (table['EVENT_TIME'] >
           row['EVENT_TIME'])].groupby('CMPL_RC_UID')['EVENT_TIME'].min().values[0]
    else:
        pass

ev_table.apply(lambda row: next_event(row, ev_table), axis=1)

I'm currently using .apply and it gives me result that I'm looking for but my df have a lot of data and it's taking a really long time to process. So I'm wondering if there's a way to vectorize the code .

CMPL_RC_UID
EVENT
EVENT_TIME

10074
Flowing
1/20/2011

10074
Injecting
12/22/2010

10074
Flowing
1/6/2010

10074
Injecting
12/10/2009


text:
Q: Atribuir um valor à minha td dentro de uma table com jQuery Não consigo atribuir um valor à minha td dentro de uma tabela, ela contém id dinâmico como no exemplo abaixo:

Lista de Dependentes

            CPF
            Tipo Dependente

            2323
            teste

            09298618417
            teste

           jose2
            teste

            123
            teste

Porém o código JS não funciona:
$("#depedente-cpf-31").html('teste');

A:
Minha resposta ficou mais como uma "demonstração" das outras funções
  que podem ser utilizadas, o erro realmente deve ser a falta da
  referência ao jQuery ou é tentado acessar o elemento antes do mesmo
  ser criado, como foi citado na resposta do @Randrade

*

*Usa o jQuery.append para adicionar conteúdo no fim do elemento

*E o jQuery.prepend para adicionar conteúdo no começo do elemento.

*O jQuery.html substitui todo o conteúdo do elemento pelo novo.

$("#div1").append(" Adicionado usando append()");
$("#div2").prepend("Adicionado usando prepend() ");
$("#div3").html(" Adiciondo usando html() ");

Texto original

Texto original

Texto original

A: A forma que está fazendo está correta. Verifique se você está referenciando o jQuery corretamente.
Outro possível problema é você está chamando a função antes da tabela estar formada. Se for isso, basta alterar o seu script de posição, ou adicionar o $(document).read() à sua função.

$("#depedente-cpf-31").html('Olha, funcionou');

Lista de Dependentes

      CPF
      Tipo Dependente

      2323
      teste

      09298618417
      teste

      jose2
      teste

      123
      teste

Por fim, caso não funcione, abra o console do browser (F12) e poste o erro que está aparecendo.


text:
Q: Python program stuck in infinite loop This piece of code has given me a serious headache. It's supposed to be a generator that takes a string as an input, and replaces all '{}'s with all possible letter combinations, essentially working in a similiar manner to itertools.permutations() but with the addition of constant values.
I've checked each individual element, and it appears that my increment function turns into an infinite loop. It seems to work if I reduce the number of strings being produced, however. Can someone explain to me why the program fails when trying to return all possible values? Assume you had to do the same without using itertools, how would you accomplish the task?
def string_char_combinations(string, chars=False):
    if not chars:
        chars = [chr(i) for i in range(ord('a'), ord('z')+1)]
    varcount = string.count('{}')
    a = [0 for i in range(varcount)]

    def increment(lst, n):
        if n == 0:
            return lst ##ERROR: Infinite loop?
        print(n)
        lst[n] += 1
        print(lst)
        if lst[n] > len(chars)-1:
            lst[n] = 0
            lst = increment(lst, n-1)
        return lst

    while a[0] < len(chars)-1:
        a = increment(a, len(a)-1)
        yield string.format(*[chars[i] for i in a])

if __name__ == "__main__":
    print(list(string_char_combinations("a{}{}a")))

A: You don't incremente the n here
    def increment(lst, n):
            if n == 0:
                return lst ##ERROR: Infinite loop?
So the value of n is always 0


text:
Q: undefined method user_path' form_for I have a UsersController and it has below code
def sign_up
@user = User.new
end

And my view page has
<div class="col-md-6 col-md-offset-3">
    <%= form_for @user do |f| %>
      <%= f.label :first_name%>
      <%= f.text_field :first_name %>
      <%= f.label :last_name %>
      <%= f.text_field :last_name %>
      <%= f.submit "Register", class: 'btn btn-primary'%>
    <% end %>
  </div>

My routes.rb file contains the following entry
 get 'signup' => 'users#sign_up'

But When I submit the form, it says
ActionView::Template::Error (undefined method `users_path' for #<#<Class:0x00000004d91490>:0x00000004d90220>)

Why does this throw an error and do I need to explicity point to url in the form_for?? Why is it so??

A: Change your routes to:
resources :users, only: [:new, :create], path_names: {new: 'sign_up'}

and rename your sign_up action back to new. The reason you are getting the error is rails trying to guess the correct url for given resource. Since you have passed @user, which is an instance of User class, it will try to call "#{@user.class.model_name.route_key}_path key, which results in the error you got.
To solve the issue you need either make your routes to define users_path or you need to specify the url directly using url option. users_path can be defined by either index or create action, so the above solution will work (and will not create remaining CRUD routes, yey!)

A: Try changing this line:
<%= form_for @user do |f| %>

to this:
<%= form_for(@user, url: 'signup') do |f| %>


text:
Q: Redmine Rest API - file attachment, upload token is not complete I'm trying to add an issue with a file attachment but the response token is not complete.
It is the same error as http://www.redmine.org/boards/2/topics/42425 (5 years old question) but there is no response there.
The redmine used is a 3.2.1.stable.
I'm using https://www.redmine.org/projects/redmine/wiki/Rest_api#Attaching-files to know how to upload files, but when I do a POST to /uploads.json?filename=myFileName, the response is something like {"upload":{"token":"6898."}}  The response code is still a 201, so it doesn't seem like there is an error.
The response to the API call should be something like {"upload":{"token":"7167.ed1ccdb093229ca1bd0b043618d88743"}}.
I tried using the partial token returned, to no avail.
Anyone have an idea as to why the token is not okay / how to correct the problem?

A: For some reason Redmine can't copy uploaded file to persistent (final) location. Maybe there's a lack of disk space, maybe there are some issues with file name. Check your environment.log for
"Saving attachment '#{self.diskfile}' (#{@temp_file.size} bytes)"

when the file is being uploaded. Maybe this will indicate the reason.

A: In fact, the problem was that the file sent was empty.
This answer may well be of help to someone.


text:
Q: Can a 4D spacecraft, with just a single rigid thruster, achieve any rotational velocity? It seems preposterous at first glance. I just want to be sure. Even in 3D the behaviour of rotating objects can be surprising (see the Dzhanibekov effect); in 4D it could be more surprising.
A 2D or 3D spacecraft (with no reaction wheels etc.) needs at least two thrusters to control its spin. See my answer on space.SE.

For any two $4\times4$ matrices $X$ and $Y$, define the commutator $[X,Y]=XY-YX$, the anticommutator $\{X,Y\}=XY+YX$, and the Frobenius inner product $\langle X,Y\rangle=\text{tr}(X^\top Y)$, where $\text{tr}$ is the trace and $\top$ is the transpose.
Let $M$ be a symmetric positive-definite $4\times4$ matrix, and $T=\mathbf f\,\mathbf r^\top-\mathbf r\,\mathbf f^\top$ an antisymmetric $4\times4$ matrix. ($M$ describes the distribution of mass in the spacecraft, $\mathbf r$ is a vector locating the thruster relative to the centre of mass, $\mathbf f$ is the force produced by the thruster, and $T$ is the torque produced by the thruster. More details here. Everything is described in the rotating reference frame.)
The angular velocity $\Omega(t)$, an antisymmetric $4\times4$ matrix, changes with time $t$ according to Euler's equation
$$\{M,\Omega'(t)\}+[\Omega(t),\{M,\Omega(t)\}]=f(t)T$$
where $f(t)\geq0$ is a function (continuous, piecewise-constant, or just integrable) describing when and how strongly the thruster is used.
Question: Can $M$ and $T$ be chosen such that, for any two antisymmetric $4\times4$ matrices $\Omega_0$ and $\Omega_1$, there exist $\Omega$ and $t_1>0$ and $f$ such that $\Omega(0)=\Omega_0$ and $\Omega(t_1)=\Omega_1$?
To simplify things, we may take $f$ to be a combination of Dirac deltas instead of an ordinary function. Then the angular velocity satisfies $\{M,\Omega'(t)\}+[\Omega(t),\{M,\Omega(t)\}]=0$ except at a finite set of times when $\{M,\Omega(t)\}$ changes by a positive multiple of $T$.

Here is Euler's equation in terms of the components $\omega_{ij}$ of the angular velocity. Assume that $M$ is diagonal, with components $m_i>0$.
$$(m_1+m_2)\,\omega_{12}'(t)+(m_2-m_1)\big(\omega_{13}(t)\,\omega_{32}(t)+\omega_{14}(t)\,\omega_{42}(t)\big)=f(t)\,\tau_{12}$$
(And permute the indices to get 6 equations like this.)
If $m_1=m_2$, then $\omega_{12}'$ has constant sign; $\omega_{12}$ is either always non-increasing, or always non-decreasing. So, if the difference between initial and final values of $\omega_{12}$ has the wrong sign compared to $\tau_{12}$, then there is no solution. Thus, we must take $m_1\neq m_2$, and similarly $m_i\neq m_j$ for $i\neq j$.

The Frobenius inner product of two antisymmetric matrices has every term duplicated: $\sum_{i,j}x_{ij}y_{ij}=2\sum_{i<j}x_{ij}y_{ij}$ (since $x_{ji}=-x_{ij}$ and $y_{ji}=-y_{ij}$). So it's natural to take half of this.
The angular momentum is $L(t)=\{M,\Omega(t)\}$. Its squared magnitude is $\tfrac12\langle L(t),L(t)\rangle$; the derivative of this is $\langle L(t),f(t)T\rangle$. So the angular momentum has constant magnitude whenever $f(t)=0$. (The angular momentum itself would be constant in an inertial reference frame, but here we're using a rotating reference frame.)
The rotational energy is $\tfrac14\langle\Omega(t),L(t)\rangle$; the derivative of this is $\tfrac12\langle\Omega(t),f(t)T\rangle$. So the energy is constant whenever $f(t)=0$.
All of that applies in any dimension. But in 4D there's another constant, the angular momentum bivector's exterior square, or equivalently its inner product with its Hodge dual.
Here are those constants in component form. Squared magnitude of angular momentum:
$$(m_1+m_2)^2\omega_{12}^2+(m_1+m_3)^2\omega_{13}^2+(m_2+m_3)^2\omega_{23}^2\\+(m_1+m_4)^2\omega_{14}^2+(m_2+m_4)^2\omega_{24}^2+(m_3+m_4)^2\omega_{34}^2$$
Doubled energy:
$$(m_1+m_2)\omega_{12}^2+(m_1+m_3)\omega_{13}^2+(m_2+m_3)\omega_{23}^2\\+(m_1+m_4)\omega_{14}^2+(m_2+m_4)\omega_{24}^2+(m_3+m_4)\omega_{34}^2$$
Halved exterior square of angular momentum:
$$(m_1+m_2)(m_3+m_4)\omega_{12}\omega_{34}-(m_1+m_3)(m_2+m_4)\omega_{13}\omega_{24}+(m_2+m_3)(m_1+m_4)\omega_{23}\omega_{14}$$
(Its derivative is the exterior product of angular momentum and torque: $(m_1+m_2)\omega_{12}\,f\,\tau_{34}+\cdots$ .)
These three constants define two ellipsoids and another quadratic surface (with signature $+^3-^3$) in the 6D space of antisymmetric matrices. When $f=0$, $\Omega$ must remain on the intersection of these three quadratic surfaces. When $f>0$, the above expressions are just quadratic forms, not necessarily constant.
It seems more convenient here to work with $L$ instead of $\Omega$. Of course $l_{ij}=(m_i+m_j)\omega_{ij}$. Let's write a quadratic form as $q(L)=q(L,L)$, using the same symbol for the corresponding bilinear form. All three of the above forms have derivative $2q(L,L')=2q(L,f\,T)$; in other words $q(L,[\Omega,L])=0$.
If we can find some combination of those forms such that $q(L,T)\geq0$ for all relevant $L$, then $q(L)$ would be always non-decreasing in time; there would be no solution when the initial and final values have $q(L_1)<q(L_0)$. But I'm not sure what "relevant" means here; I haven't thought this through.

Notice that Euler's equation has a time symmetry: Given a solution $\Omega(t)$, we can construct another solution $\tilde\Omega(t)=-\Omega(t_1-t)$, so that $\{M,\tilde\Omega'(t)\}+[\tilde\Omega(t),\{M,\tilde\Omega(t)\}]=f(t_1-t)\,T$, and the initial and final values are swapped (and negated): $\tilde\Omega(0)=-\Omega_1$ and $\tilde\Omega(t_1)=-\Omega_0$. Therefore, any angular velocity can be reached from any other, if and only if any angular velocity can be reached from $0$. (We can reverse a path from $0$ to $-\Omega_0$ to get a path from $\Omega_0$ to $0$, and concatenate that with a path from $0$ to $\Omega_1$, to get a path from $\Omega_0$ to $\Omega_1$.)
Also, Euler's equation has a scale symmetry: Given a solution $\Omega(t)$, for any $k>0$ we can construct another solution $\tilde\Omega(t)=k\,\Omega(kt)$, so that $\{M,\tilde\Omega'(t)\}+[\tilde\Omega(t),\{M,\tilde\Omega(t)\}]=k^2f(kt)\,T$, and the final value is $\tilde\Omega(t_1/k)=k\,\Omega(t_1)=k\,\Omega_1$. Therefore, any angular velocity can be reached from $0$, if and only if any angular velocity in a small neighbourhood of $0$ can be reached from $0$.
(It looks like these two symmetries are related by $k=-1$, but we should keep a distinction between positive time and negative time.)


text:
Q: Normal parametrization of a line for the Hough Transform. How is $\theta$ defined for a line through the origin For a straighline in 2D space $y=mx+b$, the normal parametrization of the line gives an alternate representation of the line as $R=x\cos\theta  +y\sin\theta$, where $R$ is the algebraic distance from the origin to the line and  $\theta$ is the angle $R$ makes with the line.
In the paper Use of the Hough Transform to Detect Lines and Curves, the author states that restricting  $\theta$ to $[0,\pi)$ gives a unique representation of all possible lines.
My question is how would $\theta$ be defined for lines passing through the origin such that they are also uniquely identified by $R$ and $\theta$ ?
PS: Also I am pretty sure that $R$ is allowed to be negative in this definition but would be nice if anyone could confirm this ?


text:
Q: Auto submit form before going to next page of form I have a multi-page form that was created for me. All of the pages on the form have submit button that saves the data to a database, a previous button that goes to the previous page and a next button. The problem is that the data does not save if I click the previous or next links.
How can I set it up so that that submit button is automatically pressed before going to the previous or next page of the form?
<a class="form-buttons" href="<?php echo $prev_url;?>">Prev

<input type="submit" name="status" value="Save" />

<a class="form-buttons" href="<?php echo $next_url;?>">Next

I'm new to programming so any help would be greatly appreciated.
Thanks!

A: You can use three submit buttons and depending on which one was clicked you can run a certain code block..
I.e.
<input type="submit" name="status" value="Prev" />
<input type="submit" name="status" value="Save" />
<input type="submit" name="status" value="Next" />

<?php

 if(!empty($_REQUEST['status']) && $_REQUEST['status'] == 'Prev'){
      //save data and redirect to previous page using header();
 }

 if(!empty($_REQUEST['status']) && $_REQUEST['status'] == 'Next'){
      //save data and redirect to next page using header();
 }

 if(!empty($_REQUEST['status']) && $_REQUEST['status'] == 'Save'){
      //save data and do whatever you want
 }

?>


text:
Q: Integrate BitBucket Private Repository with Gitbook Private Book I want to integrate my private bitbucket repository with gitbook private book.
Anyone could suggest a way to do so?
Thanks in advance.

A: Step 1:
You can first create a repository in Bitbucket. Once you have that done you need to check the "Get started with command line",  if you have to initialize a new project or you would like to use your existing project. Keep the commands from that handy because for the next step you would be using it.
Step 2 :
Now you have to go to the gitbook directory. In Linux it is normally at
/home/<username>/GitBook/Library/Import. In this directory go into the book which you would like to push to bitbucket. (Please check for Windows)
Run the commands from Step 1. Your Bitbucket repo should be populated.