VMWare + JavaFX + Mac "hello world" app fails to install/execute

Question: I'm posting here after much study of all the previous postings (on this site and elsewhere) regarding problems in running a JavaFX application (developed using JWrapper as the launcher) in a VMWare encapsulated instance of Mac OSX 10.10. [NOTE: edited the preceding sentence and the title of this posting on 2015-02-25 to add reference to VMWare.]
After experiencing failure of my much larger Java 1.8.0_25 application to install and launch in Mac OSX v10.10.1, I replicated the problem using a 3-line "Hello World" JavaFX application.
In both cases, I am using what seem to be the standard Mac-oriented parameter settings in the JWrapper build-parm XML:
<JvmOption>-Djavafx.macosx.embedded=true</JvmOption>
<MustFork>true</MustFork>

In both cases, when attempting installation on the Mac, the JWrapper splash screen appears as expected, but then it goes away, and the application itself fails to launch.
Here are the links to (1) zip file with all logs from an attempted "HelloWorldFX" installation on Mac OSX v10.10.1, and (2) zip file with the log and "build" folder from the application's JWrapper build process. Note that this application installs and runs fine in Windows and Ubuntu.
Logs:
https://googledrive.com/host/0B0skoeyva4KiUDZBS1FSUXo4RUU/mac_logs.zip
Build folder (300MB):
https://googledrive.com/host/0B0skoeyva4KiUDZBS1FSUXo4RUU/helloWorldFX_build_folder.zip
Here are the highlights:
The HelloWorldFX code (pretty much the entirety of the application):
public void start(Stage stage) {
    stage.setTitle("Hello World FX");
    stage.setScene
        (new Scene(new StackPane(new Button("Hello World FX")), 600, 250));
    stage.show();
}

My complete JWrapper build parms:
<JWrapper>

    <BundleName>HelloWorldFX3</BundleName>

    <App>
      <Name>HelloWorldFX3</Name>
      <LogoPNG>images/logo.png</LogoPNG>
      <MainClass>helloworldfx.HelloWorldFX</MainClass>
    </App>

    <SupportedLanguages>en</SupportedLanguages>

    <InstallType>CurrentUser</InstallType>

    <SplashPNG>images/splash.png</SplashPNG>
    <BundleLogoPNG>images/logo.png</BundleLogoPNG>

    <JvmOptions>
     <JvmOption>-Xmx256m</JvmOption>

     <JvmOption>-Djavafx.macosx.embedded=true</JvmOption>

    </JvmOptions>

    <Windows32JRE>jrepack18/win32/jre1.8.0_25</Windows32JRE>
    <Windows64JRE>jrepack18/win32/jre1.8.0_25</Windows64JRE>
    <Linux32JRE>jrepack18/linux/jre1.8.0_25</Linux32JRE>
    <Linux64JRE>jrepack18/linuxx64/jre1.8.0_25</Linux64JRE>
    <Mac64JRE>jrepack18/macos64/jre1.8.0_25.jre</Mac64JRE>

    <File classpath='yes'>helloWorldApp/HelloWorldFX.jar</File>

    <NoStripJREs>true</NoStripJREs>

    <MustFork>true</MustFork>

 </JWrapper>

An ominous message from the "Wrapper" log file on the Mac:
+1 [BundleLoader] Could not load JRE bundle!

One curious line from the "Generic Updater" log file on the Mac, in which a file name is apparently truncated by JWrapper, resulting in a file not found exception:
8574158 (+0) java.io.FileNotFoundException: /Users/admin/Library/Application Support/JWrapper-HelloWorldFX3/JWrapper-JWrapper-00033253833-complete/JWAppSpec- (No such file or directory)

The entirety of the "HelloWorldFX" log file on the Mac (just craps out after or while attempting to disable App Nap):
8574542 (+0) STDOUT test
8574542 (+0) STDERR test
8574543 (+1) [LogFolderCleaner] Keeping Wrapper-2015-02-18-23-56-04-443.log
8574543 (+0) [LogFolderCleaner] Keeping HelloWorldFX3-HelloWorldFX3-2015-02-18-23-56-14-525.log
8574544 (+1) [LogFolderCleaner] Keeping GenericUpdater-2015-02-18-23-56-13-488.log
8574545 (+1) [EDT Exception Printer] Catching all EDT and uncaught exceptions and printing
8574548 (+3) [JWrapperNative] Detected 64-bit architecture
8574548 (+0) [JWrapperNative] Detected Mac OS
8574551 (+3) [JWrapper] sun.java2d.dpiaware: null
8574558 (+7) [JWDetectedProxy] No proxy configuration found to load.
8574559 (+1) JVM Option: -Xmx256m
8574559 (+0) JVM Option: -Djavafx.macosx.embedded=true
8574559 (+0) [JWrapper] JVM Home: /Users/admin/Library/Application Support/JWrapper-HelloWorldFX3/JWrapper-Mac64JRE-00034082796-complete
8574573 (+14) [JWrapper] Wrote JVM Options OK
8574574 (+1) [JWrapper] Set app name to HelloWorldFX3
8574577 (+3) [JWrapper] Loading virtual app
8574577 (+0) [JWrapper] Got virtual app HelloWorldFX3
8574577 (+0) [JWrapper] Setting OS dock info
8574786 (+209) [JWrapper] Image: BufferedImage@5ef04b5: type = 6 ColorModel: #pixelBits = 32 numComponents = 4 color space = java.awt.color.ICC_ColorSpace@5f4da5c3 transparency = 3 has alpha = true isAlphaPre = false ByteInterleavedRaster: width = 256 height = 245 #numDataElements 4 dataOff[0] = 3
8574887 (+101) [JWrapper] Disabling App Nap

Any assistance with getting this problem resolved would be GREATLY appreciated!!
Answer: All this launch looks OK, the fact that the HelloWorldFX3 log was produced at all would indicate that the app did launch.
The message 'Disabling App Nap' is just the last message that JWrapper prints before it hands over control so that doesn't indicate that it failed to launch.
Do you get any hs_err_pid files generated anywhere?
What is the main method for your app like, are you able to put in a printout and check if it reaches that point in the logs?
My best guess at this point would be that although you have NoStripJRE specified maybe you haven't deleted the pre-built JRE archives from your build folder?  If not then JWrapper will continue to use those and won't rebuild them and you won't have the JavaFX components to allow your app to run.  I would suggest removing those and rebuilding and giving that another whirl.  Beyond that if there is a hs_err_pid file it may have more info.
Comment: Now that you mention it, yes there IS a file prefixed "hs_err_pid". Here is a link to a copy of it:
https://googledrive.com/host/0B0skoeyva4KiUDZBS1FSUXo4RUU/hs_err_pid5748.log

The contents of the hs_err_pid file make no sense to me, going much further down the rabbit-hole than I've ever been.

By the way, forgive me for neglecting to mention: When I attempt to execute the application on the Mac, a standard Mac window DOES come up saying "HelloWorldFX3 quit unexpectedly. Click Reopen to open the application again... [etc.]", so something IS definitely going wrong (in the eyes of OSX).
Comment: One additional question:
Do you folks at JWrapper have a simple (helloWorld-ish) JavaFX application as part of your testing routines? If so, what build of Java are you using with it? (If not, please set one up.) -- Thanks!!
Comment: BTW, repeated this entire build and installation process using Java 1.8.0_31 (the latest build from Oracle). Exact same result encountered -- no joy.
Comment: More: As you advised, I put a println statement into the main method. This printed out in the output, so the main method IS successfully invoked (before any JavaFX class/methods are invoked). My start method (see code snippet above) is never reached, so things are apparently crapping out during instantiation of the JavaFX environment.  (Looking at the hs_err_pid output suggests things possibly go bad when the JavaFX "QuantumRenderer" is making a call to a native OSX function.)
Comment: Multiple google searches led me to this bug report, issued in December, which has hs_err_pid output which looks (to my untrained eye) similar to mine: https://bugs.openjdk.java.net/browse/JDK-8067271
Comment: More on this (for what it's worth): installed the latest NetBeans (8.0.2) in my Mac OSX 10.10.1 environment, did a "clean and build", followed by "run" on the standard NetBeans JavaFX "helloworld" application, and got very similar abend to the one documented above. The hs_err_pid from this new NetBeans abend is here: https://googledrive.com/host/0B0skoeyva4KiUDZBS1FSUXo4RUU/hs_err_pid35710_netbeans.log
Comment: After digging considerably deeper, I crucially realized that the Mac machine provided to me remotely by the MacinCloud service is actually a VMWare-encapsulated instance running on a larger machine.

So this problem is apparently caused by VMWare getting between JavaFX and the native OSX graphics infrastructure that JavaFX needs to access.

Continued in next comment...
Comment: I followed the advice on this stackoverflow posting (http://stackoverflow.com/questions/18754803/how-to-disable-or-bypass-hardware-graphics-accelerationprism-in-javafx) to add the JVM runtime parm -Dprism.order=j2d. This option allowed for successful launch of the HelloWorld window, but not its button. This run then generated a CGLCreateContext error.

Bottom line: I apparently need to get direct access to a Mac that is not partitioned with VMWare, in order for any of my JavaFX applications to be runnable.


Verifying the existence of a variable in JavaScript

Question: While reading in a JSF book, the author implements a map that serves as a namespace in which he defines some JavaScript functions.
The map is implemented like this:
if (!com) var com = {}
if (!com.example) {
    com.example= {
       myFunction: function(data) {

      // some code here

    }
  }
}

I searched to understand that syntax but didn't succeed, could someone explain to me what does !com means ? how can we check a variable if it's not already declared?
Comment: It means 'If the variable `com` is a falsy value, return true'. Basically, the `!` is the `not` operator. If a value is '`falsy`' (`false`, `0`, `null`, `''`, `undefined`), it will turn into `true`. Otherwise, it is turned into `false`.
Comment: As a suggestion consider not reading that book.
Comment: In addition if com is undefined it will also be falsy!
So if you do var com, and not set its value it will also return true
Comment: the shown code is a terrible pattern that doesn't work well for anything useful.
Comment: @IsmaelMiguel thanks for the explanation, Vohuman at that point :) ?
Comment: thanks everyone, I understand :) @dandavis I am not the developer of that code :)
Answer: if (!com) checks to see if com is a falsey value.  if (com) checks to see if it's a truthy value so you can see that the ! reverses the test.
In your specific code example:
if (!com) var com = {};

the code is checking to see if the com variable is defined and initialized yet.  If it has not been initialized, it's value will be undefined which is a falsey value which will cause this code to then initialize it.
In Javascript, there are many falsey values and undefined is one such falsey value.  The falsey values are:
null
""
false
NaN
0
undefined

See this article for more info on falsey/truthy.

One thing you have to be careful of is that if (com) or if (!com) may cause a reference error in some situations.  The safest way to test if a variable has been defined and initialized is this:
if (typeof com === "undefined")

because this will not cause an error in any circumstances.
Or, a common design pattern for namespaces is this:
var com = com || {};

This will define and initialize com as a namespace object if it doesn't already exist with a truthy value.
Comment: @Tarik - yes  `var com = com || {};` makes sure that `com` either already exists and is initialized or it creates it and initializes it to an empty object.  This is a very common design pattern for declaring a namespace object that is used by many different pieces of code.  It does the same thing as `if (com) var com = {};`, but without confusion about hoisting and without putting `var` statements inside an `if()` which some people don't like to see.  Example: http://jsfiddle.net/jfriend00/3pb68zu8/
Comment: I saw that @dandavis said that the code is a RefError, what does that mean ?
Comment: see my answer, it's more subtle than just not falsey as my fiddle demonstrates, it involves hoisting and scope
Comment: @ToniLeigh - it depends upon the circumstance.  The OP didn't mention any sort of error related to that so they were probably using the code in a context that didn't cause a referenceError.  In any case, I've added more to my answer to address that issue.
Comment: @jfriend00 - I took 'how can we check a variable if it's not already declared?' to mean exactly that, as in, how does this actually work when we haven't actually done anything with that variable yet
Comment: @ToniLeigh - I took the question literally where they asked us to explain the particular syntax they illustrated in their question.  In any case, I've added better design patterns to my answer.
Comment: @jfriend00 it's somewhat ambiguous I think, so I hold that hoisting and scope has relevance to this question
Comment: @jfriend00 in what kind of situations we may get the RefError? and thanks for the the instructive discussion between you and Toni Leigh
Comment: @Tarik - when `com` is not yet defined at all, `if (com)` will generate a reference error so `if (com)` only works when it has been defined, but not yet initialized.  If there's a `var com` ANYWHERE in scope, then Javascript's hoisting will make the variable be defined in that scope so `if (com) var com = {};` will work.  Personally, I prefer `var com = com || {};` because it handles everything for you in one simple statement.
Comment: @jfriend00 Perfect, one last question: the `var com = com || {};` also do the same thing as that code? I mean it creates a  map that serves as a namespace ?
Comment: `var com = com || {};` works? and does something you want? i would think that would leave `com=={}` no matter what... unless you locally declared it above, but in that case, why check it later?
Answer: The answer here is subtler than just checking !truthy, as the OP has acknowledged by asking why we can check a value that is not assigned. Yes, the author of the example is checking whether com is falsey and if so then assigning an empty object to it, but also the fact this works depends on the use of javascript variable hoisting and the way it is scoped.
Javascript will look for all variables in it's current scope at the start of that scope and put memory aside for them, even if the value cannot be deduced. Because com is defined in the code it's initialisation is hoisted to the top of the scope it's in (global in this case) and it's already been assigned the falsey value undefined before the check is made.
In the fiddle here we can see that hoisting defines the com variable, but when execution gets to the next example where the var in the conditional is different from the tested variable - if (!comA) var comB = {} - an exception is thrown in the console.
Once assigned as an object, trying to access an undefined property on that object will also return a falsey undefined value and the next if block will also execute. Object properties are not treated like variables.
Answer: The first if will execute when com is a falsy value. That means undefined, false, 0, "" or maybe null.
Note that
null == false          // returns false

But
!null == !false       // returns true

Answer: If you haven't defined a variable, trying to access it will return undefined. Since undefined is falsy in JS, !undefined evaluates to true
Comment: yeah, in a world of hoisting it's a crucial distinction, otherwise i'd let it slide...
Comment: Whoops, slip of the finger. Meant to say defined, hence the undefined


Passar id recebida do banco de dados pela URL com javascript

Question: Comecei a aprender javascript tem pouco tempo e sou bem leigo ainda.
Então...
Estou querendo substituir as janelas de alert por modais personalizadas. Então ao clicar no botão de editar por exemplo, abre a minha janela de confirmação e se clico em OK ela me redireciona para a página de edição.
Gostaria que no redirecionamento da pagina fosse enviado o id do usuário pego no banco de dados, passando ele pela url com window.location=''; ou outro redirecionador. Nem sei se tem como fazer isso.
Se alguém puder ajudar ficarei grato.

        Confirm

    <?php foreach($usuario->findAll() as $key => $value): ?>
        <?php
            $id = $value->id;
            $nome = $value->nome;
            $nascimento = $value->nascimento;
            $sexo = $value->sexo;
            $uf = $value->uf;
        ?>

        Nome: <?php echo $nome; ?>

        Nascimento: <?php echo $nascimento; ?>

        Sexo: <?php echo $sexo; ?>

        UF: <?php echo $uf; ?>

        <?php echo "<button onclick='doAlert();'>Editar</button>"; ?>

    <?php endforeach; ?>

Comment: talvez um destes links ajude: https://jsfiddle.net/2pmn1ems/3/, https://pt.stackoverflow.com/questions/130803/passar-id-de-um-dado-de-uma-tabela-para-a-modal
Comment: Olá, Funcionou perfeitamente. Muito obrigado!
Comment: ainda bem que ajudou. De nada
Answer: Experimente usar o Sweet Alert 2
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/sweetalert2/6.6.0/sweetalert2.css">

    <?php foreach($usuario->findAll() as $key => $value): ?>
        <?php
            $id = $value->id;
            $nome = $value->nome;
            $nascimento = $value->nascimento;
            $sexo = $value->sexo;
            $uf = $value->uf;
        ?>

        Nome: <?php echo $nome; ?>

        Nascimento: <?php echo $nascimento; ?>

        Sexo: <?php echo $sexo; ?>

        UF: <?php echo $uf; ?>

        <?php echo "<button onclick='doAlert(".$id.");'>Editar</button>"; ?>

    <?php endforeach; ?>


Embedded Media Field Video: Output both Video Flash Object and Video Thumbnail in Node Display?

Question: I would like to be able to access both the Video Flash Object, as well as the Video Thumbnail filepath from the Node Display. Please let me know if I can provide more info, not sure anything else is relevant! Thanks!
Clarification: Basically I want to be able to be able to output both the video with a custom resolution, and the thumbnail through an imagecache preset, from either a custom module, or within template.php. Essentially I would hope to end up with both the final video HTML and image HTML as individual objects or php variables, so I can then output them wherever I like from within the relevant node.tpl.php. I'm assuming there's a simple theme() function I can use for both of the above. The embedded video at this time can come from either Youtube/Vimeo.
Comment: can you explain the context? how would you like to be able to video object and the thumbnail path? do you need it globally, on certain nodes? etc.
Answer: One way to do it is to set the video field display mode to full video under /content/types/CONTENT_TYPE/display then add the thumbnail via theme_emvideo_video_thumbnail() as a variable using themename_preprocess_node(&$vars) in your theme's template.php -OR- print it directly in your node.tpl
The trick to theme_emvideo_video_thumbnail(($field, $item, $formatter, $node, $no_link = FALSE, $options = array())) is to provide all the right parameters. Especially $options
e.g.
<?php
  // code adapted from emvideo.theme.inc
  // ignore the <?php tag

  $system_types = _content_type_info();
  $field_name = 'field_video'; // the machine name of your video field

  $field = $system_types['fields'][$field_name];
  $field['widget'] = $system_types['content types'][$node->type]['fields'][$field_name]['widget']; // get CCK widget data. includes all formatting settings

  $options['return_url'] = TRUE; //return URL
  $options['raw'] = TRUE; // return image path. Otherwise node path is returned

  print theme('emvideo_video_thumbnail', $field, $node->{$field_name}[0], 'video_thumbnail', $node, FALSE, $options);

In template.php
<?php
// change MYTHEME with the theme's machine name or use phptemplate
function MYTHEME_preprocess_node(&$vars) {
  if ($vars->type == "mynodetype") {
    // see code above
    $vars->video_thumbnail = theme('emvideo_video_thumbnail'...);
  }
}

Then <?php print $video_thumbnail; ?> where you need it in node.tpl.php (-OR- use the first code block directly in the node template)
Hope it helps.


Controlling for a third variable in chi-squared analysis

Question: I have $n$ individuals belonging to five different groups. I would like to know if those groups have a significant impact on a certain factor $Y$ (having three possible levels, A, B and C). So, I am basically in the case of a chi-squared analysis with "Group" and $Y$ as inputs.
The problem is the following. I know that the sex of an individual also impacts $Y$, and the sex-ratio in each group is not balanced: some groups have more men and other groups have more women. Thus, I would like to control for the factor Sex in this analysis.
I'm not interested in testing the independence of all factors ("are there more women in Group1 than in Group2?" is clearly not interesting for me), but really in testing the independance of Group and $Y$ when controlling for Sex.
Which kind of model or analysis should I use?
Comment: You have a 2 x 5 x 3 table with 2 x (5-1) x (3-1) degrees of freedom.
Comment: Indeed, but what am I supposed to do with this table? (Especially if all my variables do not play the same role, and one of them is not strictly a variable of interest but must control the link between the two other variables?)
Comment: If you would not have include this second variable, then you would have had a typic 5 X 3 table with (5-1) x (3-1) degrees of freedom. The effect of adding this new variable, adding another level to the table, is a reduction in the bias (due to possible correlation between groups and sex), making it actually more difficult to find an effect, but more accurate if you do. So you have a model P(level) =  significant function of 'sex' and 'group'. With chi-squere test you assume the opposite:  P(level)$\neq$  significant function of 'sex' and 'group', and test whether your observations match this.
Comment: The difference in roles occurs in the place where you let the sex variable not reduce the degrees of freedom. Your model is $P(level=i \vert sex, group) = P(level=i, \vert group)$. Thus you predict your cells in group,level,sex by: $N_{g,l,s} = N_s * P(g) * P(l)$ instead of $N_{g,l,s} = N * P(s) * P(g) * P(l)$
Comment: I mean $$N_{g,l,s}= N_s * P(g) * P(l \vert g)$$ instead of  $$N_{g,l,s}= N * P(s) * P(g \vert s) * P(l \vert s,g)$$ You have got 2x5x3 observed $N_{g,l,s}$ and fit 2 $N_s$, 2x4 independent  $P(g \vert s)$ and 2x3 independent  $P(l \vert s,g)$.
Answer: Your case, as you have described it, is exactly the situation the Cochran-Mantel-Haenszel test is designed for.  Many people are familiar with it only in the case where there are many $2\times 2$ tables, but there are generalizations that apply to tables with more than two rows and more than two columns.  Moreover, you can have just two strata.  Thus, in your case you have $3$ rows and $5$ columns that you want to test for independence (like a traditional chi-squared test), but controlling for sex (which amounts to $2$ strata).
One thing to note is that the CMH test assumes the effect of group on Y is the same in all levels of sex, i.e., there is no group x sex interaction.  If you believed there was, or wanted to test for such an interaction, you would need a different test.  However, you don't seem to be interested in that, and this is the simplest test to give you what you want since you are operating under that assumption.
Most statistical software should be able to do this for you.  Here is a quick example, coded in R:
dat = as.table(array(1:30, dim=c(3, 5, 2),
                     dimnames=list(    Y=c("A", "B", "C"),
                                   Group=c("g1", "g2", "g3", "g4", "g5"),
                                     Sex=c("Male", "Female"))))
dat
# , , Sex = Male
#
#    Group
# Y   g1 g2 g3 g4 g5
#   A  1  4  7 10 13
#   B  2  5  8 11 14
#   C  3  6  9 12 15
#
# , , Sex = Female
#
#    Group
# Y   g1 g2 g3 g4 g5
#   A 16 19 22 25 28
#   B 17 20 23 26 29
#   C 18 21 24 27 30
mantelhaen.test(dat)
#   Cochran-Mantel-Haenszel test
#
# data:  dat
# Cochran-Mantel-Haenszel M^2 = 0.19448, df = 8, p-value = 1

Comment: Thank you **very much**, I didn't know this test. Very interesting!
Answer: I suggest using multinomial logistic regression with Y as the dependent variable and sex and group as independent variables.


How to Update CPanel Via SSH

Question: I am on a server running CentOS 5 with WHM WHM 11.36.2 (build 0). Is there a way to update Cpanel using SSH or should I use the package manager of WHM?
Comment: This question appears to be off-topic because it is about [`working with a service provider's management interface, such as cPanel`](http://serverfault.com/help/on-topic).
Answer: You can find script that update cpanel at <code>/usr/local/cpanel/scripts/upcp</code>.
It runs each package's update script as you selected options among Automatic Manual Updates Only Never Update.
Comment: Okay, and then I can just update the package using `/scripts/upcp --force`?
Answer: Use this procedure for cpanel update...
login to your server via SSH and run the following command as root or sudo: [root#~]/scripts/upcp

How to Update CPanel Via SSH


view is distorted after using activeadmin, says translation missing

Question: I have used twitter-bootstrap gem to make a store application. It was working fine until I added the activeadmin gem.
The view of the admin home page has a line:
Store Title
and the
"translation_missing"

is almost every where and the view is distorted.
These are the things I did:
add this line to my gem file:
gem 'activeadmin'

and then run this:
rails generate active_admin:install
rake db:migrate
rails s

Answer: Try this, go to /config/locales/en.yml, and add the latest en.yml from the active_admin repo to the end (or replace the same block for en: active_admin block if it already exists in your local en.yml file)
This worked for me. ActiveAdmin was missing some translations (probably due to a Gem conflict) and this fixes that.
Comment: Confirmed to work for me, although it was working fine and all of a sudden stopped.  Also the link has changed to [here](https://raw.github.com/gregbell/active_admin/master/config/locales/en.yml)


How not to lose messages from Kafka when database is offline

Question: I am developing microservice which consumes messages from Kaffka then processes this messages and stores output to MongoDB
I am new to kafka and I encounter some problem with losing messages.
Scenario is pretty easy:
In case of mongoDB being offline microservice recieves a message then trying to save output to Mongo then I get error that says mongo is offline and message is lost.
My question is there is any mechanism in kafka that stops sending messages in that case. Should manually commit offset in Kafka ? What are best practices to handle error in Kafka consumers?
Answer: For such kind of scenario you should manually commit the offset. Commit offset only if your message processing successful. You commit it like below.  However you should note that messages have ttl hence messages get automatically deleted from kafka broker after ttl elapse.
consumer.commitSync();

Answer: I think rather than making commit manually, you should use Kafka Streams and Kafka Connect. Managing transaction between two systems: Apache Kafka and MongoDB might be not so easy, so better use already developed and tested tools (You can read more about Kafka Connect:  https://kafka.apache.org/documentation/#connect, https://docs.confluent.io/current/connect/index.html)
Your scenario might be something like this:

Process your message using Kafka Streams and send result to new
topic (Kafka Streams support exactly-once semantics)
Use Kafka Connect (Sink connector) to save data in MongoDB https://www.confluent.io/connector/kafka-connect-mongodb-sink/
Answer: One way you can do this by using pause and resume methods on MessageListenerContainer (But you have to use spring kafka > 2.1.x) spring-kafka-docs
@KafkaListener Lifecycle Management

The listener containers created for @KafkaListener annotations are not beans in the application context. Instead, they are registered with an infrastructure bean of type KafkaListenerEndpointRegistry. This bean is automatically declared by the framework and manages the containers' lifecycles; it will auto-start any containers that have autoStartup set to true.

So Autowire KafkaListenerEndpointRegistry registry endpoint in the application
@Autowired
private KafkaListenerEndpointRegistry registry;

Get the MessageListenerContainer from registry spring-kafka-docs
public MessageListenerContainer getListenerContainer(java.lang.String id)

Return the MessageListenerContainer with the specified id or null if no such container exists.

Parameters:

id - the id of the container

On MessageListenerContainer you can use pause or resume methods spring-kafka-docs
default void pause()

Pause this container before the next poll().

default void resume()

Resume this container, if paused, after the next poll().


Delphi creating thread safe writing functions

Question: I'm using Delphi XE in order to create a multi thread application.
I want to create a thread to handle all the writing into a firebird/sqlite database log.
And i want to create several threads that do some jobs and these other threads need to use the writing log thread when they need.
Thread1 = writing log thread
Thread2 = do some math and from time to time use Thread1 to write log.
Thread3 = do some other stuff and from time to time use Thread1 to write log.

and so on
for simplicity I have created a method in thread1 named WriteCollectionLog that all the other thread need to use to write the log into thread1 memory (a collection) and thread1 "onexecute" will handle the real log write into the database. This method is intended to be used like a "fire and forget" method.
now how do i make this thread safe? or can I make it thread safe? (by using TCriticalSection?)
thread2.WriteCollectionLog ...
thread3.WriteCollectionLog ...

procedure Thread1.WriteCollectionLog(aIDWORKFLOW : Integer);
var workItem : TLogFIREBIRD_Item;
begin
  try
    readWriteCriticalSection.Acquire;  <--- this will suspend the calling thread .. like thread2, thread3 and not the thread1?
    do stuff;
  finally
    readWriteCriticalSection.Release;
  end;
end;

Regards
Razvan
Comment: Store the log items into a queue (thread safe one) and let the thread pool handle its content.
Answer: Just implement what you wrote: only write to the DB from Thread1.
Please don't expect to "call" one thread from another, as you may using "Synchronize" to run some code in the main thread. It would be blocking, which is not what you expect, I guess.
The idea is to have a small in-memory structure, shared between the threads, protected by a critical section. One goal is to keep any critical section as small as possible.
For instance, you may use a TObjectQueue, then Thread2 and Thread3 will push some data to the queue, and Thread1 will wait for some pending data in the Queue, then unqueue it and write it - and if you define a transaction, it will be faster than a naive blocking process. If you just want to write some log content, use a TArray<string>, with an associated lock.


Error Assigning Availability Set To Virtual Machine In Different Regions

Question: Am I allowed to assign an availability set in East US 2 to a Azure VM in Central US.  I am getting this error below but the Availability set does exist in East US 2.
<code>{
  "error": {
    "code": "NotFound",
    "message": "The Availability Set /subscriptions/resourceId/resourceGroups/Exposure/providers/Microsoft.Compute/availabilitySets/ExposureAvailabilitySet cannot be found."
  }
}
</code>
Answer: In order to be in an same availability set the VMs need to be in the same region.


Showing that $(1-u)z^2\leq P(uz\leq |X|)$ when $0<u<1, E(X^2)=1, $ and $0<z<E(|X|)$.

Question: I am trying to show that

$$(1-u)z^2\leq P(uz\leq |X|)$$ where $0<u<1, E(X^2)=1, $
   and $0<z<E(|X|)$.

I've been given a hint to consider Cauchy-Schwarz, however, I don't see where this could apply.  I have been thinking maybe I could combine it with Markov's or Chebyshev's inequalities, to turn the condition on $E(X^2)$ into a condition on the probability $P(uz\leq |X|)$, but I don't see how to do it.
Could I get a further hint, please?
Answer: Dedimensionalizing all this to get rid of the constraints on $E(X^2)$ and $z$ is cumbersome but it can be done and it shows that the inequality to prove is equivalent to the following statement:

For every nonnegative integrable random variable $X$ and every $t$ in $(0,1)$, $$P(X\geqslant tE(X))\geqslant\frac{(1-t)(E(X))^2}{E(X^2)}.\tag{$\ast$}$$

For every nonnegative integrable random variable $X$ and every $t$ in $(0,1)$, Paley-Zygmund inequality (based on the so-called second-moment method) yields the weaker statement:

$$P(X\geqslant tE(X))\geqslant\frac{(1-t)^2(E(X))^2}{E(X^2)}.$$

Using the "sharp" inequality mentioned in the link, one can probably show that the inequality stated in the question and reformulated as $(\ast)$ above (that is, with the factor $1-t$ instead of $(1-t)^2$ in the RHS) does not hold in general.


Sending email with ssmtp From value issue

Question: I am trying to send an email from my cron script using ssmtp, the email is working fine but the "From" value is always showing Ubuntu <firstname.lastname@example.com> which I don't want to use because I need to use something like From="Cron Report <firstname.lastname@example.com>",
ssmtp.conf
#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=postmaster

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=####################

# Where will the mail seem to come from?
#rewriteDomain=

# The full hostname
hostname=example.com
AuthUser=####################
AuthPass==####################
FromLineOverride=NO
UseSTARTTLS=YES
#From="Cron Report <firstname.lastname@example.com>"

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
#FromLineOverride=YES

revaliases
root:firstname.lastname@example.com

Answer: Not sure how to change the settings in the config, but the below worked for me.
1). Uncomment ssmtp.conf:
FromLineOverride=YES

and in the crontab itself, specify 'from' address (not the below will send an email every 5 minutes ;):
MAILTO=<firstname.lastname@example.com>
MAILFROM=<firstname.lastname@example.com>
*/5 * * * * echo 'Test email from crontab. Skynet takes over the world!'


addViolation() is deprecated: how to replace it?

Question: How to adapt the following code to avoid the deprecation of addViolation() according to https://www.drupal.org/node/3238432 ?
class MyValidator extends ConstraintValidator {

  public function validate($items, Constraint $constraint) {
    if (!$this->isValid($items)) {
      $this->context->addViolation($constraint->message); // How to adapt this line?
    }
  }
}

Comment: I think the deprecation message is a false alarm. In contrast to the methods mentioned in the change record addViolation() is not marked as internal in Symfony 6 and if Drupal removes this method they will replace it with Symfony code.
Comment: thank you. Is this means that the deprecation code has been falsely added to the addViolation() method... Some kind of Core bug I would say?
Comment: It's not falsely added, it's clear they want to remove this implementation of the method. This doesn't change the usage of the method, though, it is used the same way in Symfony.
Answer: The code shown in the question doesn't need to be changed: Once Start using the class Symfony\Component\Validator\ValidatorBuilder instead of copied classes is fixed, $this->context won't contain anymore an instance of \Drupal\Core\TypedData\Validation\ExecutionContext but \Symfony\Component\Validator\Context\ExecutionContext.
As the documentation says, classes that extend ConstraintValidator should just assume that $this->context is an object implementing ExecutionContextInterface, not which class is actually used. With that assumption, the changes introduced by that issue won't influence contrain validator classes (except for the fact the deprecation message won't be anymore triggered).


Scroll horizontally instead of vertically in certain div with images?

Question: I tried many solutions I found on the web. None worked. I'm trying to make a website scroll horizontally when I'm scrolling vertically. I tried to accomplish this via js - nothing. Then I read that I should be able to do this simply using css. Again - nothing. Here's the code as it is right now:

What is wrong? / What can I do?
Comment: can you provide a JSFiddle ?
Comment: What do you mean? You may just copy the above?
Comment: seems duplicate: http://stackoverflow.com/questions/2346958/how-to-do-a-horizontal-scroll-on-mouse-wheel-scroll
Comment: Tip: If you use proper indentation, we might actually read the code in your question. :)
Comment: so, did you make it work ? which solution work for you ?
Answer: The selected answer doesn't work in my browser (FireFox).
Here is a solution I've gotten to work pretty nicely.
HTML:

When you scroll, you are essentially moving .img_holder left and right within #b.  This method requires that .img_holder is as wide (or wider) than the sum of the images you'll be placing in it, as well as all the padding and margins.  #b is the desired width to be viewed on the page.
CSS:
#b {
    width: 400px;
    border: 1px solid #111;
    padding: 0px;
    margin: 0px;
    overflow-x: scroll;
    overflow-y: hidden;
}
.img_holder {
    padding: 0px;
    margin: 0px;
    height: 100px;
    width: 910px;
}
img {
    height: 90px;
    width: 100px;
    padding: 5px;
    background: #123;
    display: inline-block;
}

JavaScript:
var scroller = {};
scroller.e = document.getElementById("b");

if (scroller.e.addEventListener) {
    scroller.e.addEventListener("mousewheel", MouseWheelHandler, false);
    scroller.e.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
} else scroller.e.attachEvent("onmousewheel", MouseWheelHandler);

function MouseWheelHandler(e) {

    // cross-browser wheel delta
    var e = window.event || e;
    var delta = - 20 * (Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))));

    var pst = $('#b').scrollLeft() + delta;

    if (pst < 0) {
        pst = 0;
    } else if (pst > $('.img_holder').width()) {
        pst = $('.img_holder').width();
    }

    $('#b').scrollLeft(pst);

    return false;
}

Make sure that you use conditions to stop from scrolling below zero and above the max width of the container (if conditions near bottom of code).  Also, the delta value when scrolling is very small, and so to prevent the user from having to scroll a bunch I've multiplied it by 20.  You can choose any value you'd like to adjust scrolling speed.
Also works nicely if you want to hide the horizontal Scroll Bar:
#b {
    overflow-x:hidden:
}

As shown here
Comment: And it doesn't require any external JS files to be included, other than JQuery.
Comment: Great!, can you please: put it a slider ?, and you make the content bigger?
Comment: [This](http://jsfiddle.net/ye259/4/) fiddle has a slider, [this](http://jsfiddle.net/ye259/5/) one doesn't.  [Here](http://jsfiddle.net/ye259/6/) is one with larger images within.  Make sure to increase the size of all the divs, especially the width of `.img_holder`
Answer: Here is what you need:
Example: http://css-tricks.com/examples/HorzScrolling/
Code: http://css-tricks.com/snippets/jquery/horz-scroll-with-mouse-wheel/
$(function() {

   $("body").mousewheel(function(event, delta) {

      this.scrollLeft -= (delta * 30);

      event.preventDefault();

   });

})

Comment: I'm puzzled. The example doesn't work for me?! (Using iceweasel/firefox.)
Comment: This basically worked! But instead of jquery.mousewheel.min.js I used jquery.mousewheel.js
Comment: This method doesn't work on my system.  The solution shouldn't be browser-dependent. "Try Chrome" is not a solution - you can't ask all the viewers of your site to download a new browser just so the site works properly.  Refer to my answer for a complete solution that is browser-independent.
Comment: This wasn't browser-independent. However, using jquery.mousewheel.js instead made it.
Answer: Try something like this one:
.scrolls {
    overflow-x: scroll;
    overflow-y: hidden;
    height: 80px;
    white-space:nowrap
}
.imageDiv img {
    box-shadow: 1px 1px 10px #999;
    margin: 2px;
    max-height: 50px;
    cursor: pointer;
    display:inline-block;
    *display:inline;/* For IE7*/
    *zoom:1;/* For IE7*/
    vertical-align:top;
 }


Devise RegistrationsController create action in API

Question: I'm trying to create a Rails 3 app with an API. I use Devise as my authentication system. I would like to make it possible to sign up and later sign in through the API. And i'm not quite sure how I should do this. I have created separated controllers to manage the API, i.e. api/v1/account/1/projects.json. I'm currently trying to create a custom Devise::RegistrationsController for the API, but I'm not quite sure how to do this.
My create action currently looks like this:
class API::V1::RegistrationsController < Devise::RegistrationsController
  redpond_to :json, :xml

  def create
    build_resource
    if resource.save
      if resource.active_for_authentication?
        # Account is a nested resource for User, I want to
        # create an associated account when the User signs up through the client,
        # how should I do this?
        account = resource.accounts.build
        # How can I get the sign_in to work?
        sign_in(resource_name, resource)
        # Probably wrong
        respond_with resource, :location => after_sign_up_path_for(resource)
      else
        # probably wrong
        expire_session_data_after_sign_in!
        respond_with resource, :location => after_inactive_sign_up_path_for(resource)
      end
    else
      # probably wrong, or?
      clean_up_passwords resource
    end
  end

Which probably is very incorrect as mentioned in my comments, so I wonder if anyone could give me any guidance on how to make it work. Should also mention that account is a nested resource for the user.
I also wonder how I should set up the login and logout functionality in the API with Devise.
Thanks!
Answer: This other SO question may help you. It looks very similar. Pay special attention to the gist that's linked in the answer.
Comment: I got the signing part working by following the links, with some modifications. The signup part will therefore probably also work. Thanks!


How can a function have a finite area but infinite volume when revolved around an axis?

Question: I have a function $f(x) = \frac{1}{\sqrt{x}}$ on $[0, \pi]$ and want to find the area of the function, then the volume of the function were it revolved around the x-axis.
For the area:
$$\begin{align}
A &= \int_0^\pi \frac{1}{\sqrt{x}} \, dx \\
&= \int_0^\pi \frac{1}{x^{\frac{1}{2}}} \, dx \\
&= \int_0^\pi x^{\frac{-1}{2}} \, dx \\
&= \left[ \frac{x^{\left(\frac{-1}{2}+1\right)}}{\left(\frac{-1}{2}+1\right)} \right]_0^\pi \\
&= \left[\frac{x^{\frac{1}{2}}}{\left( \frac{1}{2}\right)}\right]_0^\pi \\
&= \left[2x^{\frac{1}{2}}\right]_0^\pi \\
&= \left[2\sqrt{x}\right]_0^\pi \\
&= 2\sqrt{\pi} - 2\sqrt{0} \\
&= 2\sqrt{\pi}
\end{align}$$
The area $A$ of $f(x)$ on $[0, \pi]$ is finite. Now revolving around the x-axis:
$$\begin{align}
V &= \int_0^\pi \pi\left(\frac{1}{\sqrt{x}}\right)^2 \, dx \\
&= \int_0^\pi \pi\left(\frac{1^2}{\left(\sqrt{x}\right)^2}\right) \, dx \\
&= \int_0^\pi \pi\left(\frac{1}{x}\right) \, dx \\
&= \int_0^\pi \frac{\pi}{x} \, dx \\
&= \left[\pi \ln{x}\right]_0^\pi \\
&= \pi \left[\ln{x}\right]_0^\pi \\
&= \pi (\ln{\pi} - \ln{0})
\end{align}$$
Note $\ln{x}$ is undefined for $x = 0$ and complex for $x \lt 0$, thus the volume $V$ of $f(x)$ over $[0, \pi]$ is not finite.
How can an area of a function be finite, yet the volume of the same function rotated around an axis be infinite/undefined? Is this a quirk of the mathematics or I haven't yet learned how to find the volume of shapes like this? I don't know if the mathematics here is definitive or it's undefined as a consequence of my (lack of) knowledge.
Comment: It's called a "paradox", which means something which is *seemingly* contradictory but may in fact be true, or that is contrary to perceived opinions or expectations. The infinite is often paradoxical. Note that physical intuition here is useless, since you run into quantum mechanical and Planck length issues.
Comment: You showed how, quite in some detail.
Comment: The same way a 2D shape can have infinite circumference but finite area. (E.g., Koch's snowflake.)
Answer: When you integrate to compute the volume of the solid of revolution, you are integrating the square of the function. It turns out that $\frac 1{\sqrt x}$ is not square integrable, and the integral diverges to $+\infty$. Any function that is integrable but not square integrable will give finite area but infinite volume.


Notation of portamento

Question: I have two measures (in treble clef) of a soprano voice, the first starting on the higher c and the second ending on the c an octave lower.
I would like to notate a portamento that starts on the beginning of measure 1 and ends on the end of measure 2.
This is my current notation:

Is my notation correct?
Answer: What you have at present is vague about whether the gliss starts early or late, but is pretty clear that it ends on the FIRST beat of bar 2.
For clarity of exactly where the gliss starts and ends, I think you want something like this.  Rests to show the beats?  Or no rests because - well, there ISN'T silence!   Maybe even my third example, though I can see it being a rehearsal-stopper.
Answer: IMO your example is clear and conveys that the glissando should start at the beginning of m1 and ends at the end of m2.
If you would want something different, then it would be notated differently, I think.
E.g. you want the glissando to start at the last beat of m1 until the end of m2:

Or you want the glissando to start at the beginning of m1 until the first beat of m2:
Comment: But TBH I wouldn't interpret Laurence's notations correctly either. I'd be very confused by all of them.
Comment: The OP wants the gliss to end on the final beat of measure 2.  I don't think you can indicate this without putting rests or "empties" in the first 3 beats of that measure.
Comment: Nope, my interpretation of the example agrees with Laurence Payne's: the glissando ends at the *beginning* of Bar 2.
Comment: Ok, fair enough @Dekkadeci

Notation of portamento


Jquery function on Dynamically created List not working

Question: Please Help me out, I can get the dynamic list on the second Page and all is Ok. But when i click any "li" to get alert of the "id" (which works fine for hard coded list) i dont get any thing. I have tried listview('refresh') and (trigger) too but no effect. Most of the other questions were solved with the help of listview("refresh") but not in my case. Please see if you can point me in the right direction.
$(document).on('pagebeforeshow','#page1',function(){
        $("#bar .type").click(function(){
            localStorage['ppl']=$(this).attr('id');
            $.mobile.changePage("#second",{
                transition: "slide",
                reverse: true
            });
        });
    });
    $(document).on('pagebeforeshow','#second',function(){
        var ty =  localStorage['ppl'];
        getOther(ty);// THIS POPULATE THE LIST
        /*THESE ONES DONT WORK FOR ME */
        //$(document).trigger('create');
        //$('[data-role="listview"]').listview("refresh");
        //$('#foo).listview('refresh');
        $("#foo li").click(function(){
            alert($(this).attr('id'));// NO ALERT FROM THIS NEW LIST
            $.mobile.changePage('#third',{
                transition: "slide",
                reverse:true
            });
        });
    });

this the HTML Code.

First Page

A

B

Second Page

    Back

AB

AC

Third Page
Back

Comment: Use event delegation: $("#foo").on("click", "li", function(){...  http://learn.jquery.com/events/event-delegation/
Comment: @ezanker thanks for reply but still unsuccessful
Comment: post jsfiddle if possible
Comment: Don't use `pagebeforeshow` to bind events, you'll end up multiplying them.
Answer: After doing lots of research, and scratchings of head i did some changes to code and got the result. Thanks for you help.
Firstly for my function"getOther(ty);" i added it into the body,
    $(document).on('pagebeforeshow','#page1',function(){
 AND IN IT I PUT THIS LINE
$("#foo").append($("

")).listview("refresh");

and it did the trick for adding the dynamic list into the DOM.
And the for attaching click function to "li" I was using
$("#foo li").click(function(){

alert($(this).attr('id'));// NO ALERT FROM THIS NEW LIST

I changed it to
$("#foo").on('click','li',function(){

and It worked. Thank you for your help. Much appreciate it.
Answer: use jquery "on" method instead of 'click'.
$("#foo").find('li').on(function(){
     localStorage['ppl']=$(this).attr('id');
     $.mobile.changePage("#second",{
        transition: "slide",
        reverse: true
     });
});

Answer: Try refactoring your code so that the click handlers are created on pagecreate. So when page1 is created, add the event handler for clicking the #bar.type items. Then when second page is created use event delegation to add a handler to the LI's within foo. Because these LI's are dynamic and not available when the handler is added, you actually need to add the handler to the UL and delegate it to its LI's.
$(document).on('pagecreate','#page1',function(){
    $("#bar .type").click(function(){
        localStorage['ppl']=$(this).attr('id');
        $.mobile.changePage("#second",{
            transition: "slide",
            reverse: true
        });
    });
});
$(document).on('pagecreate','#second',function(){
    $("#foo").on("click", "li", function(){
        alert($(this).attr('id'));// NO ALERT FROM THIS NEW LIST
        $.mobile.changePage('#third',{
            transition: "slide",
            reverse:true
        });
    });
});

$(document).on('pagebeforeshow','#second',function(){
    var ty =  localStorage['ppl'];
    getOther(ty);// THIS POPULATE THE LIST
});

Here is a DEMO


MLB - process of signing guy off of streets

Question: This is a theoretical question, but I am curious of the process. Let's say the owner of a major league ball club is driving around somewhere and sees a baseball game happening on the streets where a pitcher is throwing 250mph (yes I know not possible, but this is to exaggerate his skills). So obviously the owner is very intrigued and finds out the guy is just a regular guy who never played any organized baseball. Could that owner just sign him right there if he wanted to? Does he have to get drafted?
Answer: While there are some rules about age and college attendance, if the player is not in any of those groups, any team can sign him (or her) as an undrafted free agent. It actually happens from time to time. The examples I found are players who were in the drafts, but never got picked. In fact, this is a very common entrance method; as those rules above show, players from outside an "extended area" of the US do not enter the MLB draft, but can be signed directly.


how to config jax-ws Handler in Spring?

Question: I  according jax-ws API integration jax-ws with Spring ,but I get an exception at my webservice project,here is API site :http://jax-ws-commons.java.net/spring/ ,I have same config xml in my project,but i get an exception is below:
<code>    Caused by: org.xml.sax.SAXParseException: cvc-complex-type.3.2.2: Attribute 'handlers'                   is not allowed to appear in element 'ws:service'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
</code>
who can give me solution?
Answer: The example given is wrong and not valid with regard to the schema. handlers is not an attribute, but a nested element. Use it like this:
<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:wss="http://jax-ws.dev.java.net/spring/servlet"
    xmlns:ws="http://jax-ws.dev.java.net/spring/core"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://jax-ws.dev.java.net/spring/servlet http://jax-ws.dev.java.net/spring/servlet.xsd http://jax-ws.dev.java.net/spring/core http://jax-ws.dev.java.net/spring/core.xsd">

 <wss:binding url="/services/demo">
     <wss:service>
         <ws:service bean="#demoEndpoint">
             <ws:handlers>
                 <ref bean="demoHandler"/>
             </ws:handlers>
         </ws:service>
     </wss:service>
 </wss:binding>
</bean>
</code>

how to config jax-ws Handler in Spring?


Subnet Masking in IPv6

Question: I know within IPv4 subnet masking, the network is determined by either the 1st, 2nd or 3rd set of octets. Being there are so many more characters in IPv6, how do you determine the subnet mask?
Answer: The network is not related to the octets.  Octets were substantive many, many years ago - now they're just for readability for us humans.  IP addresses are just numbers; representing them as we do is just easier.  Try ping 134744072 (which is 22.214.171.124, Google's public DNS server), for instance.
The length of the subnet mask is simply a number of bits - a mask of 8, 16, or 24 bits will align with octets, but a mask of any length, any number of bits, is valid.  Review the answers to this question for all that you need to know and more.
In IPv6, the same is true; a valid mask is of any length, and does not need to align to one of the 16-bit colon-separated fields (which are, again, only for our human readability).
Comment: Worth noting that I haven't yet seen an IPv6 implementation that actually asks for a subnet mask (e.g. `ff:ff:ff:ff:ff:ff::`), they all use CIDR notation, so `/48`, `/64`, `/128` etc which makes it *really* easy to determine the network/host part of the address
Comment: And an IPv6 network is (almost) always a /64. Technically you could use other sizes, but not everything will work. If you don't have a good reason to do otherwise: use a /64 per network.
Comment: Thank you for the clarification as well as the link, it will definitely be helpful for future reference.

Subnet Masking in IPv6


IIS 7 and Windows 2008: only one ip address showing for IIS binding when multiple aliases exist?

Question: In Windows 2003 I have multiple IP aliases setup on a single network card all bound to IIS 6.
In Windows 2008 I have multiple IP aliases setup but only one shows up in IIS 7.
What do I need to do to have the other IPs show up?  It gives choices of all unassigned or the main IP address.  I have obviously tried restarting the machine.
I tried both using host headers and no headers.  I also double checked the firewall and DNS settings.
Any ideas?
Comment: Is there anything interesting installed on the machine? Fresh install? What else is configured on it so far? does 'Netsh http sh ipl' show you anything interesting?
Answer: This is a bug with IIS UI. You can manually add the required IP in the IP Address section.


VHD with 3 partitions and 3 operating systems. How to split?

Question: Got a guy on the other side of Earth who needs a sole partition off of a vhd so he can do his job.  The entire vhd is over 490gb.  The 1 partition is about 80.  So I want to split the the vhd up into its 3 partitions.  A vhd file for every partition.  How can I do this?
Answer: I have had to mess with this a while back. What I had to do was mount the drive, and it should mount the partitions as well as long as the partition table is in tact.
Once the VHD and it's partitions mount it will look just like a regular HDD/SSD.
Use something similar to disk2vhd to copy each to it's own individual drive.
From there you should be set.
Answer: I'm thinking something very basic to do that is risk free and you don't to mess with the partition tables or anything.

Copy the VHD 3 times
Mount each VHD alone
For each VHD, delete the partitions you don't want and only keep the one you need.


A calculus conjecture about sum and derivative

Question: Let $f(x) , g_1(x) , g_2(x) , \ldots$ be analytic on $[-1,1].$
If for almost Every $x $e $[-1,1] $we have :
Property A :
If
$$f(x) = g_1(x) + g_2(x) + \cdots \tag{property I }$$
And
If
$$f ' (x) = g_1 ' (x) + g_2 ' (x) + \cdots \tag{property II}$$
Then
$$f '' (x) = g_1 '' (x) + g_2 '' (x) + \cdots$$
And by induction the $n $th derivative satisfies ( $n$ is a positive integer )
$$f^{(n)} (x) = g_1^{(n)} (x) + g_2^{(n)} (x) + \cdots$$

notice property I does not always imply property II ;
example
The Fourier series for $f(x) = x.$

How to prove or disprove this ?
What are nice (counter-)examples ?

I got this question from the tetration forum where my mentor ( Tommy1729 ) posted it :
http://math.eretrandre.org/tetrationforum/showthread.php?tid=1088
I think i have seen it on sci.math as well ( also posted by him)
I assume he knows the answer , but wants to see how people handle it.

I was reading complex analysis before I read his post.
That inspired me to conjecture a variant :
( that I believe is easier )
Let $f(z),g_1(z),g_2(z),...$ be analytic on the closed unit circle.
The rest is equivalent.

I think replacing analytic with $C^\infty$ in Tommy's statement is interesting.
Afterall there are functions that are $C^\infty$ almost everywhere but analytic almost nowhere.

This problem seemed simple when i first saw it , but is appears deceptively complicated to me.
Or Maybe I am weak.
I considered fourier series , Riemann's series theorem and contour integrals to find a counterexample , but I failed.
I think it is possible to show the hypothesis correct if all the $f,g_i$ are monotone.
What bothers me most is - unlike most statements - that I am not even sure if it likely true or likely false !?
A further complication is summability methods, but for now Lets assume we consider ordinary sums that converge.
Is this a hard question ? Is this a new question ?
Comment: Should i post on MO too ?
Comment: I would use $g_1(x)$ rather than $g1(x)$, which is given by \$g_1(x)\$
Answer: Consider this example:
$$\cos x = (\cos x - \cos (2x)/2^2) + (\cos (2x)/2^2 - \cos (3x)/3^2)+(\cos (3x)/3^2 - \cos (4x)/4^2) + \cdots.$$
Differentiating, we wonder if
$$-\sin x = (\cos x - \cos (2x)/2^2)'+ (\cos (2x)/2^2 - \cos (3x)/3^2)' + \cdots$$ $$ = (-\sin x + \sin (2x)/2) + (-\sin (2x)/2 + \sin (3x)/3) + \cdots.$$
Yes, this is fine: The $n$th partial sum is $-\sin x + [\sin(n+1)x]/(n+1) \to -\sin x.$ But we run into trouble with the next derivative, because the series of second derivatives is
$$(-\cos x + \cos (2x)) + (-\cos (2x)+ \cos (3x)) + \cdots,$$
which diverges for every $x\in [-1,1]\setminus \{0\}.$


Como crio um slide automático com JavaScript, HTML e CSS?

Question: Sou iniciante e meu primeiro projeto é dividido por etapas, é um projeto até que um tanto bobo, mas me mantém animada em continuar estudando e tudo o mais. Basicamente, é como se fosse uma coleção de skins que quero comprar do Lol, bem simples e tudo.
Eu criei um slide que mostrava as skins que eu mais queria, ele funciona e tudo o mais. Eu pesquisei bastante mas não entendi como posso fazer para deixar ele automático, como um slide que passa a imagem depois de alguns segundos, mas que eu poderia ainda assim continuar clicando nos botões de navegação dele para ver alguma que eu quero.
Eu vi alguns vídeos usando somente o CSS, mas não soube como aplicar porque a estrutura parece ser muito diferente, então estou buscando algum meio de usar o JavaScript para isso. Sou bem iniciante, mas estou aprendendo, e se for muito complexo eu vou procurar aprender e entender o que tenho que fazer!
É isto, vou deixar o HTML e CSS aqui embaixo caso seja necessário.

                <input type="radio" name="slide" id="slide1" checked>
                <input type="radio" name="slide" id="slide2">
                <input type="radio" name="slide" id="slide3">
                <input type="radio" name="slide" id="slide4">

CSS:

/* Estilo do Slide */

main{
    position: absolute;
    top: 30%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.content{
    height: 500px;
    width: 900px;
    border-radius: 20px;
    overflow: hidden;
}

.navigation{
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translate(-50%);
    display: flex;
}

.bar{
    width: 70px;
    height: 17px;
    border: 3px solid white;
    margin: 6px;
    border-radius: 5px;
    cursor: pointer;
}

.bar:hover{
    background-color: white;
    transition: 0.5s;
}

.slides input{
    display: none;
}

.slides{
    display: flex;
    width: 500%;
    height: 100%;
}

.slide{
    width: 20%;
    transition: .6s;
}

.slide img{
    width: 100%;
    height: 100%;
}

#slide1:checked ~ .s1{
    margin-left: 0%;
}

#slide2:checked ~ .s1{
    margin-left: -20%;
}

#slide3:checked ~ .s1{
    margin-left: -40%;
}

#slide4:checked ~ .s1{
    margin-left: -60%;
}

Answer: Tomei a liberdade de rescrever todo o projeto. Espero que nao se importe e que meu codigo te ajude. <3

let count =1;
document.getElementById("radio1").checked = true;

setInterval( function(){
    nextImage();
}, 2000)

function nextImage(){
    count++;
    if(count>4){
        count = 1;
    }

    document.getElementById("radio"+count).checked = true;
}
body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.slider {
    margin: 0 auto;
    width: 800px;
    height: 400px;
    overflow: hidden;
}
.slides{
    width: 400%;
    height: 400px;
    display: flex;
}
.slides input{
    display: none;
}
.slide{
    width: 25%;
    position: relative;
}
.slide img{
    width: 800px;
}
.manual-navigation{
    position: absolute;
    width: 800px;
    margin-top: -40px;
    display: flex;
    justify-content: center;
}
.manual-btn{
    border: 2px solid white;
    padding: 5px;
    border-radius: 10px;
    cursor: pointer;
    transition: 1s;
}
.manual-btn:not(:last-child){
    margin-right: 40px;
}
.manual-btn:hover{
    background-color: white;
}
#radio1:checked ~ .first {
    margin-left: 0;
}
#radio2:checked ~ .first {
    margin-left: -25%;
}
#radio3:checked ~ .first {
    margin-left: -50%;
}
.navigation-auto div{
    border: 2px solid #20a6ff;
    padding: 5px;
    border-radius: 10px;
    cursor: pointer;
    transition: 1s;
}
.navigation-auto {
    position: absolute;
    width: 800px;
    margin-top: 360px;
    display: flex;
    justify-content: center;
}
.navigation-auto div:not(:last-child) {
    margin-right: 40px;
}
#radio1:checked ~ .navigation-auto .auto-btn1 {
    background-color: white;
}
#radio2:checked ~ .navigation-auto .auto-btn2 {
    background-color: white;
}
#radio3:checked ~ .navigation-auto .auto-btn3 {
    background-color: white;
}
#radio4:checked ~ .navigation-auto .auto-btn4 {
    background-color: white;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/estilo.css">
    <title>TESTE</title>

            <input type="radio" name="radio-btn" id="radio1">
            <input type="radio" name="radio-btn" id="radio2">
            <input type="radio" name="radio-btn" id="radio3">
            <input type="radio" name="radio-btn" id="radio4">


Post variable not being caught in php sent from dynamically generated html

Question: Im having a really simple issue but iv looked around and cant debug it for some reason, can someone point me in the right direction??
I have a php script which dynamically generates a link
 <?php
  $id = 1;

  echo "click link"

 ?>

On example.php I have...

 $userId = $_POST['id'];

 then I insert $userId query...
 ?>

For some reason the Post vairable is not being cause by the example.php script I can see it in the URL at the top of the page but they wont make sweet passionate php love. Any thoughts? I will mention I am doing this from within an IFRAME however I tried it simply and got the same result :(
Comment: Is it `example.php` or `page.php`?
Comment: sorry my bad http://www.example.com/page.php and yes it has an opening <?php tag lol
Answer: I think you mean, on page.php you have...
If that is the case, you are sending the id parameter in a GET, not a POST.  To access it in your other page you need to use:
$userId = $_GET['id'];

Comment: that's not the only problem: just try to run his code and see what echoes
Answer: your variable is in $userId = $_GET['id'];.
another problem is a mess with ' symbols: should be
echo "click link"

Answer: Sorry, but you ar sending data via GET NOT POST
access it via $_GET['id'];


Expectation of transition in a Markov process

Question: I have the following transition matrix for a Discrete Markov process with 3 states, say states A, B and C:
\begin{bmatrix}0.985992 &  0.0134092 & 0.000599272\\
               0.0265225 &  0.949748 & 0.0237297 \\
               0.00196398 & 0.0895138 & 0.908522
\end{bmatrix}
As I was doing some calculations I noticed that if I simulated data the number of transitions from any two states is roughly the same going both ways (e.g. the number of states going from A to B, A->B, is roughly the same as from B to A, B->A), for example for 100000 iterations:

A->B: 8164 and B->A: 8340
B->C: 7602 and C->B: 7779
A->C: 365 and C->A: 188

In an intuitive way, Why is this? I understand it if I calculate the expectations, for example:
$\mathbb{E}(A \rightarrow B)=\pi_A P(B | A)$
and this is actually very close to $\mathbb{E}(B \rightarrow A)=\pi_B P(A | B)$, where $\pi_X$ is the stationary distribution for state $X$.
I just don't quite grasp why this happens. Any insights? Any reference or leads appreciated.
Answer: This is a peculiar property of your transition matrix, but it doesn't have to be that way.
If your system satisfies $\pi_A P(B|A) = \pi_B P(A|B)$ for all states $A$ and $B$, your system is said to satisfy the property of detailed balance. Transition matrices that satisfy this property, are called reversible.
But there are Markov chains with stationary distributions that don't satisfy this property. E.g., you could try to find a chain that has as stationary distribution the uniform distribution but a transition matrix that is not symmetric. That means, find a transition matrix where all rows and all columns sum to one, but that is not symmetric. A simple example would be:
$$
T = \left[\begin{matrix}
              0.1 & 0.1 & 0.8 \\
              0.2 & 0.8 &   0 \\
              0.7 & 0.1 & 0.2 \\
          \end{matrix}\right].
$$
Clearly, the stationary distribution is the uniform distribution $\pi_U = (1/3, 1/3, 1/3)$, and this Markov chain is not reversible.
A good, short introduction to Markov chains can be found e.g. in

Bishop, Christopher M., and Nasser M. Nasrabadi. Pattern recognition and machine learning. Vol. 4. No. 4. New York: springer, 2006.


How do you evaluate $\int \frac{y^2}{y^2+d^2}dy$?

Question: $\color{green}{question}$:
How do you evaluate this integral?

$$\int \frac{y^2}{y^2+d^2}dy=y-d\,{\tan}^{-1}\left ( \frac{y}{d} \right )+\mathrm{constant}$$

$\color{green}{I~know}$ I should use the change of variables, But I do not know how to do.
Thank you for any hint.
Comment: Start by adding $d^2-d^2$ to the numerator.
Comment: @L.F. thanks for edit.your edit was really helpful :)
Comment: @Software: $\ddot\smile +1$
Comment: @BabakS. thank you :) your comment give me incentive for more activities.
Comment: As a general rule, if you want to integrate the quotient of two polynomials where the degree of the numerator is at least as large as the degree of the denominator, then you want to divide first.
Comment: @user84413 yes,is true.thank you so much.
Comment: @amWhy thank you my friend
Answer: $$\frac{y^2}{y^2+d^2} = \frac{y^2 + d^2}{y^2+d^2} - \frac{d^2}{y^2+d^2}$$
The latter is an arctangent integral.
Comment: thank you, Excellent. $\Large\color{blue}{+}$
Answer: Hint

$$\frac{y^2}{y^2+d^2}=\frac{y^2+d^2-d^2}{y^2+d^2}=1-\frac{d^2}{y^2+d^2}$$
$$\frac{d^2}{y^2+d^2}=\frac{1}{(y/d)^2+1}=\frac{1}{t^2+1}$$
$$\int\frac{dt}{t^2+1}=\arctan t+C$$
Comment: I think this is the best answer so $\huge\color{green}{✓}$ for you :) thank you again.
Comment: thanks for your hint $\Large\color{red}{+}$
Comment: You're welcome.
Answer: Maple code with(Student[Calculus1]):IntTutor$(y^2/(y^2 +d^2),y$); produced the output which can be seen here. It coincides with the excellent answer by Eric Auld.
Comment: It would be preferred to insert the document linked as a image in your answer itself.
Comment: thank you, This code is useful for me so +1 for you. :)


How to remove HTML tags from rendered text

Question: I am needing to remove the opening and closing
 tags from some rendered comment text. I pass the content to a component as a prop and i think that in doing so, it doesn't allow for the v-html directive to work correctly.
I need the content to render without the html tags
Here is where I am trying to render normally with v-html
 <textarea class="form-control comment-inline-edit" v-html="content" name="comment-inline-edit" cols="45" rows="3"></textarea>

And here is where I am passing the rendered content from the parent component
<CommentEdit v-show="isEditting" :content="comment.content.rendered" v-on:cancel="cancelEdit" />

Is there a VueJS way to do this other than using v-html?
Answer: I would recommend you strip HTML from rendered text in VueJS using a filter, that way you can repeatedly use the filter around the application, rather than a specific singular computation.
I wrote the following, which utilizes the browser's parsing (most reliable method) as regex can be thwarted by user silliness:
Vue.filter('stripHTML', function (value) {
  const div = document.createElement('div')
  div.innerHTML = value
  return text = div.textContent || div.innerText || '';
});

Once you include this in your app.js you can then render it anywhere as follows:
{{ pdf.description | stripHTML }}

Comment: Good answer but just note for other users... this is exactly usable for what it says is `striphtml` - so it is not XSS safe. It is vulnerable for e.g. input string containing ``.
Comment: Thanks @Grant .This worked well but what if i want to keep image tags, How would i go
Answer:
 @{{data.description | strippedContent}}

filters: {
    strippedContent: function(string) {
           return string.replace(/<\/?[^>]+>/ig, " ");
    }
}

Working for me
Answer: The question of how to remove HTML tags from text in javascript already has an answer.
The Vue way to do this would be to create a computed property that runs code to remove HTML tags from the rendered content and pass that to your CommentEdit component instead:
computed: {
  strippedContent() {
    let regex = /(<([^>]+)>)/ig;
    return this.comment.content.rendered.replace(regex, "");
  }
}

<CommentEdit v-show="isEditting" :content="strippedContent" />

Comment: https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454
Comment: @JonathonHibbard yeah, I don't know the very best way to strip out html tags. My example code came from googling "strip html tags javascript". I'm sure the asker can find something that will work for him. I'm telling him how to use a feature of Vue to run the stripping method and pass that data to his component.
Answer: I was alarmed by @mikep's comment to @Grant's answer about XSS vulnerability. This would be a show stopper for me.
A quick test confirms it to be true:
        {{foo| stripHTML}}
...

  data:function(){return {
    foo: "
some text
",
  }},

This shows the alert, proving the Javascript was injected and executed.
I found a technique to parse the HTML without attaching it to the DOM in this answer which is not vulnerable to the image attack.
I came up with this version of Grant's filter which simply renders the same test to "some text" with no alert shown.
Vue.filter('stripHTML', function (value) {
    let text = ''
    const parser = new DOMParser();
    const dom = parser.parseFromString(value, "text/html");
    let div = dom.querySelector('body>*');
    if(div){
        text = div.textContent || div.innerText || ''
    }
    return text
});

Note this assumes there's a single top-level node in the content, like
some stuff
, but you could extend the query selector to handle other cases.
Answer: const re = /<[^<>]+>/g

:content="comment.content.replace(re, '')"

Hi, you could try this out!


Does opencv have a function similar to size and bwperim in matlab?

Question: I am new to opencv and good at matlab
i want to write equalent of below to opencv
[mm,nn]=size(binaryimage);
bwperim(binaryimage);
Please can any one help
Answer: There is a library for these things: http://opencv.willowgarage.com/wiki/cvBlobsLib
Comment: ya i have reference manual of Opencv But is cvsize same as size in matlab

and for perimeter i didnt find similar function
Comment: it is too bad though that it uses IplImage :((
Answer: For emulating bwperim you can do
Mat m;
Mat dilated = m.clone(); dilate(dilated,one_pixel_wide_element);
Mat output = dilated - m;

where the one_pixel_wide_element can be constructed using instructions from opencv:
  dilation_type = MORPH_RECT;
  dilation_size = 1;
  Mat element = getStructuringElement( dilation_type,
                  Size( 2*dilation_size + 1, 2*dilation_size+1 ),
                  Point( dilation_size, dilation_size ) );

This gives an outer boundary. For inner boundaries do erode (and m-eroded).


How to create a large sample database?

Question: I have few sample databases but they are quite small in size. I want to create a database with records upto 50GB. I want to learn many aspects of the database and also want to test our application's performance against it.
How to gather random data?
Answer: Just script a lot of appropriate inserts with randomised data.
I can't be any more specific as you tell us nothing about your database.
Comment: What else you want to know?
Comment: How about the database you're using!
Answer: You can use some "Faker" APIs like this one :
http://faker.rubyforge.org/
Or if you want real data, you can gather it from internet, some months ago I needed real data for tests, I've made a IRC bot that log all the messages on the Top 10 channels on Freenode and let it run 24h24 for many weeks, that gave me lot of data (~1 million rows) :)
Answer: A number of sources on the internet allow you to download their content, and it often reaches into the 10's or 100's of GB. Two that I can think of off the top of my head are:

Wikipedia (http://en.wikipedia.org/wiki/Wikipedia:Database_download)
StackOverflow (http://blog.stackoverflow.com/category/cc-wiki-dump/)

Though these dumps are in XML, it's easily imported into an empty database by any modern RDBMS. A number of other sites have dumps as well, especially wiki-ish sites (like both of these examples).

How to create a large sample database?


Why is so much extra space being added to my UILabel when I try to change height to fit text?

Question: I have no idea why the height of my UILabel is expanding to such a great height. It leaves the text of my UILabel in the centre. I don't want all of this extra space...
Unwanted extra space

Here is my code (I set the text before this point):
self.infoDescription.numberOfLines = 0;
[self.infoDescription sizeToFit];
self.infoDescription.frame = CGRectMake(20, self.infoAdultSize.frame.size.height+self.infoAdultSize.frame.origin.y+10, self.infoView.frame.size.width-40, self.infoDescription.frame.size.height);

Please help :( I just want the height of the UILabel to fit the text exactly.
Comment: just try to interchange the code of label, first set the frame and then make size to fit of label.
Comment: That worked! Thank you.
Comment: please upvote my answer if helpful
Comment: Possible duplicate of [How to get the size of a NSString](http://stackoverflow.com/questions/2669063/how-to-get-the-size-of-a-nsstring)
Answer: First set the frame and then make size to fit of label.
  **self.infoDescription.frame = CGRectMake(20, self.infoAdultSize.frame.size.height+self.infoAdultSize.frame.origin.y+10, self.infoView.frame.size.width-40, self.infoDescription.frame.size.height);
    [self.infoDescription sizeToFit];**

Comment: Wow, It's Working fluently.
Answer: Try this:
CGSize maximumSize = CGSizeMake(300, 9999);
NSString *myString = @"This is a long string which wraps";
UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:14];
CGSize myStringSize = [myString sizeWithFont:myFont
                           constrainedToSize:maximumSize
                               lineBreakMode:self.myLabel.lineBreakMode];

(original source)
Answer: Please check this answer it works for me and it is exactly what you are looking for.
//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];

//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;


Passing taxonomy term through drupal_html_class() and use it as row class name

Question: In a view I would like to use a excluded term reference field as source for the the row classname. But the values need to be sanitized by putting the term names through drupal_html_class(), otherwise the resulting classnames are not valid in every case.
How can I sanitize the values using a preprocess function?
Answer: I got it working by using this preprocess function:
function mytheme_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];
  if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if ($field->field == 'field_category') {
      $tid = $variables['row']->_entity->field_category->target_id;
      $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
      $name = $term->getName();
      $variables['output'] = \Drupal\Component\Utility\Html::cleanCssIdentifier($name);
    }
  }
}

An alternative would be using mytheme_views_pre_render.
Comment: I would be very interested, which hook (hook_preprocess_views_view_field or hook_views_pre_render) is best regarding performance and caching.


JavaScript function runs for 1 second then clears?

Question: So I've written a web page with a few JavaScript functions.
The page runs perfectly in Dreamweaver but when I tried it out in a browser (Google Chrome and Firefox) the JavaScript flashes for a split second then clears. I have no idea at all why this is.

   <form name="myForm">

 TILE CALCULATOR

            Wall height (cm)
            <input type="text"  id="wall_height" />

            Wall Width (cm)

            <input type="text"  id="wall_width" />

            Tile Height (cm)
            <input type="text"  id="tile_height" />

            Tile Width (cm)
            <input type="text"   id="tile_width" />

        <button onclick="javascript:validate();"> Calculate </button>

    </form>

<canvas id="myCanvas">

Your browser does not support this feature</canvas>

I would really appreciate it if someone could have a quick look for me! Thanks,
Comment: what is the planned behaviour of your javascript?
Comment: it prints out a wall of tiles in a canvas and gives the result of the area. It prints the wall and gives the result in dreamweaver then stays there , in a browser its prints and gives the correct result but only flashes it on screen for a split second
Answer: Try using onclick="javascript:validate();" on the form tag instead of on the button tag and try using 'onsubmit' instead of 'onclick'
Answer: Just replace your onclick attribute by onclick='validate(); return false'.
OR (better then previous)
Just add a type="button" attribute to your button tag, once the HTML5 button's default behavior is to submit forms.
Useful tip
Bind your handler programatically, this way (with no jQuery):
        <button type="button" id="calculate"> Calculate </button>

...

        window.addEventListener("load", function(){
          document.getElementById("calculate").addEventListener("click", validate);
        });

Answer: there is no problem with kepping the button in the form you you need to return false everytime to avoid the form submit using the return false like this
    onclick="javascript:validate();return false;"


If two vectors are normal to the same plane in $\mathbb{R}^3$, must they then be parallel to each other?

Question: Following this article on MathWorld define the plane passing through a point $x_0$ perpendicular to a vector $n$ as the set of all points $x$ satisfying
$$n \cdot (x - x_0) = 0.$$
Define a normal vector to a plane to be a nonzero vector $N$ that satisfies
$$N \cdot (x_1 - x_2) = 0$$
for all points $x_1$ and $x_2$ on the plane.
Question: Let $\alpha$ be a plane. If $N_1$ and $N_2$ are both normal vectors to $\alpha$, must they be parallel to each other (i.e., does there exist a nonzero number $c$ such that $N_1 = cN_2$)?
I've tried to resolve the question using the cross product and some linear algebra as follows: Let $x_1$ and $x_2$ be two distinct points on $\alpha$ and set $v = (x_1 - x_2) \times N_1$. Then $v$ is orthogonal to both $(x_1 - x_2)$ and $N_1$; so the set $\{v, N_1, x_1 - x_2\}$ is an orthogonal basis of $\mathbb{R}^3$. It follows that there exist numbers $c_1$, $c_2$ and $c_3$ such that
$$N_2 = c_1v + c_2N_1 + c_3(x_1 - x_2).$$
The dot product $N_2 \cdot (x_1 - x_2)$ is zero since $N_2$ is a normal vector to $\alpha$; hence
$$0 = N_2 \cdot (x_1 - x_2) = c_3\lVert x_1 - x_2 \rVert^2,$$
where $\lVert v \rVert = \sqrt{v \cdot v}$ for all vectors $v$. Since $x_1 \neq x_2$, this forces $c_3 = 0$. It remains to prove that $c_1 = 0$. I'm stuck on this point; all ideas are welcome.
Comment: Yes ${}{}{}{}{}{}$
Answer: Look at dimensions.
First, let
$$ W = \{ x_1-x_2 \mid x_1,x_2\text{ are in the plane}\} $$
It is an easy matter of algebra to see that this is the same as
$$ W = \{ x_1-x_0 \mid (x_1-x_0)\cdot n = 0 \} $$
which is a linear subspace of $\mathbb R^3$, namely the solution space of
$$ n_x x + n_y y + n_z z = 0 $$
which has dimension $2$ because it is the null space of the $1\times 3$ matrix $[n_x\;n_y\;n_z]$, and by the rank-nullity theorem the dimension must be either 2 or 3 and can be 3 only if $n=0$.
Thus, $W$ has some basis $\{w,u\}$. It should be easy to see that $N$ is a normal vector exactly if $N\cdot w=0$ and $N\cdot u=0$ -- one doesn't need to check for all members of $W$, only the two basis vectors.
This means that the set of all normal vectors is the solutions to
$$ w_x x + w_y y + w_z z = 0 \\ u_x x + u_y y + u_z z = 0 $$
which is two linear equations of three unknowns. By the rank-nullity-theorem again this solution space has dimension 1, because the matrix $$\begin{bmatrix} w_x & w_y & w_z \\ u_x & u_y & u_z \end{bmatrix}$$ has rank 2 (if the rank were any lower, $\{w,u\}$ would not be linearly independent, contradicting their being a basis for $W$).
This means the set of normal vectors is an $1$-dimensional linear subspace.
Finally, if you have two normal vectors $N_1$ and $N_2$, they must be linearly dependent, because a linear subspace cannot contain a linearly independent subset with more elements than its dimension. And if you have two linearly dependent vectors, one is always a multiple of the other.
Comment: Thanks a lot for your thorough answer to the question. It had not occurred to me to look at it that way; I was stuck on the idea of using the cross product.


Relation between uniform convergence of curves in a manifold and homotopy

Question: I was working through some things in riemannian geometry and I had this doubt:
Let $M$ be a closed riemannian manifold, $H$ an embedded submanifold and $V$ be its $\varepsilon$-tubular neighborhood. Consider a sequence of continuous curves $\sigma_{l}:[0,1] \rightarrow M\setminus V$. Suppose that the sequence converges uniformly to a continuous curve  $\sigma:[0,1]\rightarrow M\setminus V$.  Can I assume that $\sigma$ is homotopic to some $\sigma_l$ for $l$ large enough?
Answer: I assume you either want 1. a fixed endpoint homotopy of curves all having the same start point and the same end point or 2. a free or based homotopy of loops. Otherwise, it would be good to specify what kind of curves you have and what type of homotopy you want.
In either of these situations, the answer is yes. In fact, it holds in a much more general setting.
In a metric space $X$ which has a universal cover (locally path connected, semi-locally simply connected), if $\sigma_l\to\sigma$ uniformly, then there is a $N$ such that $\sigma_l$ is homotopic (in any of the above senses) to $\sigma$ for each $l\geq N$.
Really, you don't even need the metric. If $X$ is path connected, locally path connected, and semi-locally simply connected (the usual ingredients for a universal covering), and you use the compact-open topology on the space of paths (this agrees with the uniform metric when $X$ is metric), then if $\sigma_l\to \sigma$ in this path space, then there is a $N$ such that $\sigma_l$ is homotopic (in any of the above senses) to $\sigma$ for each $l\geq N$.
The general idea is, for large $l$, to connect $\sigma$ and $\sigma_l$ with "small" paths so that you get a sequence of "small" loops between the two. Since small loops in a space with a universal cover are trivial (homotopically), you can piece together all these homotopies to get a homotopy of $\sigma$ and $\sigma_l$.
There is a nice detailed proof of the general statement in
Discreteness and Homogeneity of the Topological Fundamental Group
Answer: I was thinking a differently than Jeremy.  My argument is not nearly as general, since it relies explicitly on the metric.
Let $\sigma_l\to\sigma$ uniformly in $M$, where $M$ is some Riemannian manifold (not necessarily complete) without boundary.  Since the convergence is uniform, for every $\epsilon>0$ there is some $N$ so that $l>N$ implies $\sup_t d(\sigma_l(t),\sigma(t)) < \epsilon$.
Since $\sigma$ is compact, it admits a tubular neighborhood $\nu$ of radius $\epsilon_0 > 0$.  (Compactness lets us avoids pathologies such as an infinite spiral toward the "edge" of an incomplete manifold.)  Associated to $\epsilon_0$ is an $N_0$ so that for all $l>N_0$, $\sigma_l$ lies entirely within $\nu$.
The tubular neighborhood is diffeomorphic to the normal bundle of $\sigma$ in $M$, so we may regard $\sigma_l$ as a section of the normal bundle.  All sections of a vector bundle are homotopic to its zero section  Pulling this homotopy back by the diffeomorphism between the normal bundle and $\nu$, we have a homotopy between $\sigma_l$ and $\sigma$.  The minimal $N_0$ so that all $l > N_0$ have $\sigma_l$ homotopic to $\sigma$ is that given by the radius of the cut locus of $\sigma$.
The intuition here is that since $\sigma$ is compact, some small $\epsilon$-neighborhood of $\sigma$ must retract onto it (this is the tubular neighborhood).  Since the $\sigma_l\to\sigma$ uniformly, for large enough $l$ we can "suck" the $\sigma_l$ onto $\sigma$ via that retraction.
Comment: Although above solution is more general I chose this as the accepted answer because I thought it was more direct and it was easier to fill in the details.


Find the domain and range of $f(x)=\sin^{-1}(\sqrt{x^2+x+1})$

Question: Find the domain and range of $f(x)=\sin^{-1}(\sqrt{x^2+x+1})$
Finding the domain:
$$x^2+x+1>=0 \text { it is always true }$$
$$-1<=\sqrt{x^2+x+1}<=1$$
$$\sqrt{x^2+x+1}>=-1 \text { and } \sqrt{x^2+x+1}<=1$$
$$\sqrt{x^2+x+1}<=1$$
$$x^2+x+1<=1$$
$$x(x+1)<=0$$
$$x\in[-1,0]$$
Finding the range
$$f(x)=\sin^{-1}\left(\sqrt{\left(x+\frac{1}{2}\right)^2+\frac{3}{4}}\right)$$
$$f(x)=\sin^{-1}\left(\sqrt{\left([-1,0]+\frac{1}{2}\right)^2+\frac{3}
{4}}\right)$$
$$f(x)=\sin^{-1}\left(\sqrt{\left[\frac{-1}{2},\frac{1}{2}\right]^2+\frac{3}
{4}}\right)$$
$$f(x)=\sin^{-1}\left(\sqrt{\left[0,\frac{1}{4}\right]+\frac{3}
{4}}\right)$$
$$f(x)=\sin^{-1}\left(\sqrt{\left[\frac{3}{4},1\right]}\right)$$
$$f(x)=\sin^{-1}\left({\left[\frac{\sqrt{3}}{2},1\right]}\right)$$
$$f(x)\in \left[2m\pi+\dfrac{\pi}{3},2m\pi+\dfrac{2\pi}{3}\right] \text { where m is integer }$$
but actual answer is $\left[\dfrac{\pi}{3},\dfrac{\pi}{2}\right]$
Answer:
$$f(x)\in \left[2m\pi+\dfrac{\pi}{3},2m\pi+\dfrac{2\pi}{3}\right] \text { where m is integer }$$

This isn't true because the range of the inverse sine function is from $\left[-\frac{\pi}{2},\frac{\pi}{2}\right]$. Let $$\theta=\sin^{-1}\left(\frac{\sqrt{3}}{2}\right)$$
then
$$\sin{\theta}=\frac{\sqrt{3}}{2}$$
with the restriction that $\theta\in\left[-\frac{\pi}{2},\frac{\pi}{2}\right]$. The possible triangles with this ratio of $y$ to hypotenuse (i.e. $\sin$) are shown below

where only $\pi/ 3$ falls within the restricted range for the inverse sine function. Similarly, letting
$$\theta=\sin^{-1}\left(1\right)$$
means
$$\sin{\theta}=1$$
where only $ \pi/ 2$ falls within the restricted range for the inverse sine function.
Answer: The range of $f(x)=sin^{-1} x$ is $[-\pi/2,\pi/2]$ over the domain $[-1,1]$.
So here  range the range of the the given function  is $[\pi/3,\pi/2].$
Comment: but see if $y=\sin^{-1}x$, then $\sin y=x$, so in this question $\sin(f(x))=\left[\dfrac{\sqrt{3}}{2},1\right]$, so you can see that $y\in[2m\pi+\dfrac{\pi}{3},2m\pi+\dfrac{2\pi}{3}]$ where $m\in Z$, what am I missing here
Answer: The range of the function $\sin^{-1}$ is only $[-\frac{\pi}{2}, \frac{\pi}{2}]$. Hence with $f(x) = \sin^{-1} \left( \left[ \frac{\sqrt{3}}{2}, 1\right] \right)$, the $\sin^{-1}$ functions maps these points to the range $\left[ \frac{\pi}{3}, \frac{\pi}{2}\right]$.
Comment: but see if $y=\sin^{-1}x$, then $\sin y=x$, so in this question $\sin(f(x))=\left[\dfrac{\sqrt{3}}{2},1\right]$, so you can see that $y\in[2m\pi+\dfrac{\pi}{3},2m\pi+\dfrac{2\pi}{3}]$ where $m\in Z$, what am I missing here
Comment: You are correct in saying that all of these y values give a sine value in the expected range. However, the $\sin ^ {-1}$ function has a range only in $[-\pi/2, \pi/2]$, by definition. The reason for this is that otherwise, it will become a multi-valued function, which is not allowed. A function cannot be multi-valued.
Comment: good point, thanks
Answer: The domain of $$f(x)=\sin^{-1}(\sqrt{x^2+x+1})$$ is where you get $$0\le x^2+x+1\le 1$$ which is the interval $[-1,0]$
Note that $f(-1/2)=\pi/3$ is the minimum value and $f(-1)=f(0)= \pi/2$ is the maximum.
Thus the range is the interval  $[\pi/3, \pi/2]$


How to check if network traffic on a specific port is secured/encrypted

Question: We are running Elasticsearch 5.5.1 on Windows 2008 R2. We have installed Searchguard SSL plugin to enable SSL on Elasticsearch's transport port(9300) and are using jks certificate provided by our admin. How do I verify that the communication on this port is using SSL? Are there any inbuilt tools or other freeware tools that can be used to determine/monitor this?
Thanks!
Answer: You can use the below command to examine if the port is secured:
openssl s_client -showcerts -connect hostname:port
Alternatively:
you can use "Keystore Explorer" tool and select Examine> ExamineSSL, and put in your host and port and click OK,  if this port on that server is encrypted then it will show the certificate details that the port is using to encrypt data.
If the port is not secured, then it will show a message "Could not examine SSL certificates for (hostname:port) mentioned"


Como colocar online um programa?

Question: Existe uma planilha (do google) compartilhada no qual vários usuários editam e a observam simultaneamente. Pra quem já usou a planilha compartilhada do google sabe que quando alguém começa a escrever todos enxergam em tempo real. Enfim eu construir um programa com algumas funcionalidades a mais para substituir essa planilha compartilhada (usei python 3.x e tkinter) o problema é que eu não faço ideia de como colocar esse programa online para vários usuários (no máximo 120) usarem simultaneamente. P.ex: alguém começou a digitar alguma coisa e todos verem (igual a planilha do google). Se alguém que entendeu o problema e puder pelo menos me orientar o que eu devo pesquisar/estudar serei eternamente grato !
ABAIXO UM PRINT DO PROGRAMA
Comment: O problema é colocar online para que todos possam acessar ou que apareça em tempo real as modificações de cada usuário? Aliás, já aproveite para [edit] a pergunta e adicionar códigos relevantes para facilitar o entendimento do problema.
Answer: Colocar online implica ligações de rede de cada utilizador. Cada ligação de rede vai ter uma latência. O processo de edição em tempo real por vários clientes numa rede é um grande desafio. Uma técnica utilizada é o uso de websockets.
O flow dos dados segue da seguinte forma genérica:

Utilizador A pede a página da planilla ao servidor
Utilizador B pede igualmente
Utilizador A envia um comando de edição para o servidor
O servidor faz um broadcast para todos os clientes ligados
Cada software cliente executa o comando recebido pelo broadcast.
O utilizador B observa em tempo real o comando de edição do utilizador A.

Como colocar online um programa?


No default value for '#type' => 'date'?

Question: is there a way to configure a date form so it has no default value?
Setting the default value to NULL sets the default value automatically to the current date.
<code>  /**
   * @return array
   */
  public function getFormFieldSampDate() {
    return [
      '#type' => 'date',
      '#title' => t('Date of Sampling '),
      '#default_value' => self::dateStringToArray($this->sampling_date),
    ];
  }
</code>
Thanks
Comment: Pretty simple, don't provide a `#default_value` key.
Comment: That does not work for me. The API says:  "The #default_value will be today's date if no value is supplied." Thats sounds like there can't be no default date?
Answer: Step 1) Install Date module.
Step 2) Enable the Date Popup module (comes with the Date module).
Step 3) Add code like the following:
<code>  $form['date'] = [
    '#date_label' => 'above',
    '#type' => 'date_popup',
    '#date_format' => 'm/d/Y',
    '#datepicker_options' => [
      // limits date picker so no future date can be picked.
      // remove this section if you want to allow future dates.
      'maxDate' => "+0D",
    ],
    '#required' => TRUE,
    '#attributes' => [
      'autocomplete' => 'off',
    ],
  ];
</code>
Result:
Comment: @Xyarvius see [Change the title of date_popup filed in custom form](https://drupal.stackexchange.com/questions/153677/change-the-title-of-date-popup-filed-in-custom-form/153678)
Comment: Thanks, worked very well. Is there a simple solution to disable or change the description to the fields?
Comment: Thanks. Worked very well.

No default value for '#type' => 'date'?


mongoose findByIdAndDelete / findOneAndRemove not deleting

Question: Im using a basic forms to create/delete info from mongodb.
I can create the records fine enough when i submit the form but when i try to remove a record i keep getting this error:
     Cast to ObjectId failed for value " 596f5d7770f6f0d0c2767d3f" at
path "_id" for model "dwb_notes"

I've looked around and most of the answers i see here on SO speak to multiple instances of the app running or multiple programs running on the same port etc, and other varied solutions that aren't directly related to my problem(i think) but i've tried them anyways to no avail.
I only have one record in the db right now for testing. Here is my model:
function todoNotesModel(){
    const mongoose = require("mongoose");
    const Schema = mongoose.Schema;

    const NotesSchema = new Schema({
        todoCompany : String,
        todoIsFor : String,
        todoPostedBy : String,
        todoCompleted : Boolean,
        todoPriority : String,
        todoMessages : Array,
        todoTitle : String,
        todoDate : String
    });

    const NotesModel = mongoose.model("dwb_notes", NotesSchema);

    return NotesModel;
}

module.exports = todoNotesModel();

Using another html form, on load, the delete button is assigned the document id (in this case its 596f5d7770f6f0d0c2767d3f ), and appends it to the delete button.
on submit, this id is passed to the delete route via:
app.delete("/notesapi/:tabID", (request, response) => {
    NotesModel.findByIdAndRemove(request.params.tabID, (error, data)=>{
        if(error){
            console.log("error in deleting yo!");
            throw error;
        } else {
            console.log("data all gone and deleted yo");
            response.status(204);

        }
    });
});

when i run a : db.dwb_notes.find().pretty()
i get back :
"_id" : ObjectId("596f5d7770f6f0d0c2767d3f"),
"todoCompany" : "",
"todoIsFor" : "",
"todoPostedBy" : "LOGGED IN USER HERE",
"todoCompleted" : false,
"todoPriority" : "green",
"todoTitle" : "",
"todoDate" : "Wed Jul 19 2017 09:23:56 GMT-0400 (Eastern Daylight Time)",
"todoMessages" : [
        ""
],
"__v" : 0

which shows its there so i don't understand why i'm getting this error.
Any ideas?
Comment: Have you tried to truncate the ObjectID string? In your error looks like there's a space in your ObjectID string.
Comment: Sorry I meant, stip: http://php.net/manual/en/function.trim.php
Comment: OMG IT WORKED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! you did it THANK YOU. man i been on this for TOO long. You were right. i removed all the code and simply directly added the id number to a dummy var, and it worked. I then took your thory and applied replace(" ", "") and it worked!!! THANK YOU. And yep, just used .trim. Put in full response so i can accept
Comment: Howdy Zander, what do you mean "truncate"?
Comment: ahh ok, im on JS but i get it. Let me try it
Comment: oh sorry haha, I was answering PHP questions, got a little caught up. I believe JS has: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/trim .. `String.trim()`
Comment: haha no problem :)
Answer: it looks like your error is printing out an additional space in your MongoID String. Creating an invalid MongoID String.
You can use: string.trim() Documentation
To remove any spaces before or after the string.
Comment: Thanks this was really helpful. Something so small. Zander, maybe you can help me out with this other issue ive been having that i cant figure out located here: https://stackoverflow.com/questions/45130054/ajax-network-error-even-though-it-passes-the-information


If $p(x+y)^2=5$ and $q (x-y)^2=3$, then the simplified value of $p^2(x+y)^2+4pqxy-q^2(x-y)^2$ is?

Question:
If $p(x+y)^2=5$ and $q (x-y)^2=3$, then the simplified value of $p^2(x+y)^2+4pqxy-q^2(x-y)^2$ is?
Answer: $2(p+q)$
Comment: We already have $$(x+y)^2,(x-y)^2$$  Can't you find $xy$ from there?
Answer: $$(x+y)^2 = 5/p$$
$$(x-y)^2 = 3/q$$
$$\implies 4xy = 5/p - 3/q$$
Answer: we have $$5p-3q+pq(\frac{5}{p}-\frac{3}{q})=2p+2q=2(p+q)$$