React js big in filesize? Correct way to setup gulpfile.js?

Question: I have created a gulpfile.js and a package.json (inclusing all my npm packages), but once building (even without all the additional npm packages), I have a very big final javascript file. It's around 1,5 mb, with React.js, ES2015 and a few other things..
Can anyone tell me why my final build is so big, and how a gulpfile should look like with all the latest versions of the frameworks as of today?
gulpfile:
var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');

gulp.task('default', function(){
    return browserify('./source/app.js')
        .transform(babelify, {presets: ["es2015", "react"]})
        .bundle()
        .pipe(source('build.js'))
        .pipe(gulp.dest('./build/'));
});

and my packages.json
"devDependencies": {
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "babelify": "^7.3.0",
    "browserify": "^13.0.1",
    "gulp": "^3.9.1",
    "vinyl-source-stream": "^1.1.0"
},
"dependencies": {
    "react": "^15.0.2",
    "react-addons-update": "^15.0.2",
    "react-bootstrap": "^0.29.4",
    "react-dom": "^15.0.2"
}

Thank you (a lot)!
Answer: There are couple of important steps you're missing if you want to create minified production builds.
Environment
The unminified version of React contains a certain amount of code that can be safely omitted for production. You'll find it in conditional statements like this:
if(process.env.NODE_ENV !== 'production') {
  // ...
}

The first is to include envify as part of your pipeline, then set up the appropriate environment variable from gulp.
gulp.task('default', function(){
  process.env.NODE_ENV = 'production';
  return browserify('./source/app.js')
    ...
});

When this runs, it will substitute the process.env.* references for their literal values.
// with process.env.NODE_ENV = 'production'
if(process.env.NODE_ENV !== 'production') { }
// becomes
if('production' !== 'production') { }

Minification
Smart minifiers, like UglifyJS2 will spot this in their static analysis pass and recognize that the statement contains dead code (code that will never run) and can safely remove it before further minification.
The minifier will also remove comments, rename most of your variables and delete lots of whitespace to shrink the filesize.
Once you've eliminated the dead code and minified the rest, you should find that the gzipped size of the resulting bundle is much more reasonable. Otherwise, you might be interested in checking out Preact (which is only 3kb) and some of the other alternatives to React.
Comment: Hi Dan, thnx for your extensive answer. I have added envify and uglify, but still, the minimal file size I get is over 700kb (minified..). The original file was a liite over 2 mb. btw. envify only reduced the file size by a few kb.. I think something is not correct, since I also read about people posting on their filesizes around 80-150 kb for their whole project.. What can I expect? My project is fairly small.. is it because I use ES?
Comment: Envify won't actually remove that much code, but it will prevent some expensive things from happening at runtime. The bulk of your minified bundle comes from React and the other libraries you've included, the ES syntax polyfills provided by Babel won't be huge.
Comment: If you're really keen on cutting the bundle down further then you can look into using [Rollup](http://rollupjs.org/) instead of Browserify (to eliminate dead code) and [Buble](https://buble.surge.sh/) instead of Babel (a lightweight alternative). Also remember that people often quote their filesize after gzip and minification.


How can I leave Subject as blank when fill nothing in the subject field of a comment?

Question: When we fill nothing in the subject field of comment, drupal will use the comment body as the value of subject. See the code in CommentForm::buildEntity
// Validate the comment's subject. If not specified, extract from comment
// body.
if (trim($comment->getSubject()) == '') {
  if ($comment->hasField('comment_body')) {
    // The body may be in any format, so:
    // 1) Filter it into HTML
    // 2) Strip out all HTML tags
    // 3) Convert entities back to plain-text.
    $comment_text = $comment->comment_body->processed;
    $comment->setSubject(Unicode::truncate(trim(Html::decodeEntities(strip_tags($comment_text))), 29, TRUE, TRUE));
  }
  // Edge cases where the comment body is populated only by HTML tags will
  // require a default subject.
  if ($comment->getSubject() == '') {
    $comment->setSubject($this->t('(No subject)'));
  }
}

I still need to show Subject if it's been filled, while leave the Subject as blank when the user fill nothing in. To programmatically change the default behavior, we may need to override the function after buildEntity take place, otherwise buildEntity will override it again to the comment body. Is it possible to do that?
Answer: You can use hook_ENTITY_TYPE_presave to do this, just call
 if (!$entity->getSubject()) {
   $entity->setSubject('');
 }

if it isn't filled.
Hope it makes sense.
Comment: This method set the subject field to be blank no matter it is filled or not. I still need Subject to be shown when it is filled with something.
Comment: I'm sorry if it was unclear try to look at update where I use getSubject to check if it has value
Comment: Thanks a lot, it works. I'm still curious about the calling precedure. If the hook_ENTITY_TYPE_presave calls first,  buildEnity will then set the value from comment_body again; if not, hook_ENTITY_TYPE_presave will always set subject to be blank. It seems conflict ... Where did I misunderstand?
Comment: hook_ENTITY_TYPE_presave is called just before the entity is saved. And it will only set the subject to be blank if has no value, instead of taking the value from body.
Comment: Let me guess there's a callback from the save procedure, both hook_ENTITY_TYPE_presave and buildEntity will be called at the same time and the hook_ENTITY_TYPE_presave has a higher priority to set the Subject?
Comment: Yes I think so.
Answer: After codes pile up, the issue comes back again. Maybe some other function definition causes the above code of @Jdrupal lose its effect. I now use a reverse process of buildEntity in hook_ENTITY_TYPE_presave to achieve my purpose. Though not neat, it works:
$subject = strip_tags($entity->get('comment_body')->value);
if(strpos($entity->getSubject(),$subject) !== false)
  $entity->setSubject('');


Accessing this.props from React Component functions

Question: I'm new to React.js and is confused by how the following 2 functions displayGender and toggleGender access this.props differently.
import React, { Component } from 'react';

export default class User extends Component {

    displayGender() {
        console.log('displayGender: ', this.props)
    }

    toggleGender() {
        console.log('toggleGender: ', this.props)
    }

    render() {
        return (
            <Button onClick={ this.toggleGender.bind(this) } >
                { this.displayGender.bind(this) }
            </Button>
        );
    }
}

Why is this.toggleGender.bind(this) able to access this.props that was passed to this React Component User, but this.displayGender.bind(this) sees this.props as undefined?
So far I am only able to access this.props from within this.displayGender if I pass it to the function. Is this the usual practice?
export default class User extends Component {

    displayGender(props) {
        console.log(props.user)
    }

    render() {
        return (
            <Button onClick={ this.toggleGender.bind(this) } >
                { this.displayGender(this.props) }
            </Button>
        );
    }
}

Comment: It is rather odd to pass a *function* as a child to a React component. Do you maybe mean to *call* the function (and in the future pass the return value as child)? *"Is this the usual practice?"* If you call the function directly  (i.e. `{this.displayGender()}`) it should be no problem to access `this.props`.
Comment: `.bind` returns a function. Hence `{this.displayGender.bind(this)}` passes a function as child to ``.
Comment: @FelixKling Can you explain how I am passing a function as a child? Sorry kinda confused here.
Comment: When is displayGender actually called?
Answer: That's because your this.toggleGender.bind(this) function is added as a click event in your component and this.displayGender.bind(this) is added as a child  node inside the <button>
What bind usually refers is put the given function inside some other anonymous enclosed function (and preserve the context ie, this if supplied)
So: toggleGender.bind(this) usually refers to function(){toggleGender()}
When the above is placed in click function it makes sense as we're attaching a function to click event. But it wouldn't make sense to add it as a child node
Comment: *"`toggleGender.bind(this)` usually refers to `function(){toggleGender()}`"* I think this is a bit confusing. While `.bind` returns a new function, the fact that `this` is bound to a specific value is important. So rather: `toggleGender.bind(foo)` refers to `function(){toggleGender.call(foo)}`.
Comment: @FelixKling thanks for your comment..can you go through my edit and confirm if my assumption is correct?
Answer:
Why is this.toggleGender.bind(this) able to access this.props that was
  passed to this React Component User, but this.displayGender.bind(this)
  sees this.props as undefined?

I'm not certain it's necessary to bind "this" to displayGender because unlike toggleGender it should already be bound to the correct object by default. I believe you should be able to access this.props from displayGender just by invoking the method.
The Handling Events section in the React docs might be helpful.


Connection String Encryption , whats the idea?

Question: If I am encrypting the connection string section, anyone who has the web.config can reDecrypt the information.
There is no password key which is known only to me or something similar....
What's the idea here?? Anyone who will have that web.config with VS, will be able to decipher the info...
I dont get the idea...
Comment: you can only unencrypt the value if you have access to the machine where the web.config is, or know the machine key. You'd have to be totally compromised already for someone to have that.
Comment: thanks hatchet : That helped me to understand.
Comment: My advice would be to read the documentation: http://msdn.microsoft.com/en-us/library/53tyfkaw(v=VS.100).aspx and then ask a more targetted question. Your question is so vague as to be unanswerable.
Answer: You wrongly assume that anyone can decrypt the web.config. Once the config file section is encrypted, it can only be decrypted on the same machine (or the machine that has got the same key - this is for web farming).
Usually, it is fairly easy to download the actual web.config remotely (through vulnerabilities). But the malicious user will not have your key and will not be able to decrypt the file (or sections with sensitive data).
The point here is you have got to trust your site hoster, that is the sensitive key will not be distributed.
Answer: You can specify the encryption provider, but the default is the RSA provider. There is a key used, but it is 'secret'. So someone would need a privileges to run applications on your server, or unrestricted access to the file system in order to unencrypt your web.config.
This (especially step 2) talks about it:
http://msdn2.microsoft.com/en-us/library/ms998283.aspx
Answer: I don't know whether aspnet_regiis.exe tool uses keys to encrypt or decrypt web.config. But
If it stores in the web.config then It would be decrypted by anyone who has aspnet_regiis utlility installed but If it is stored in machine.config or in .Net Framework folder of the computer than It would not be decrypted by anyone.
Comment: It is usually placed in machine.config or secure windows storage. It is **never** stored in web.config itself


Run time determination of compilation options

Question: I need to be able to determine at run time what compilation options were use to build the executable. Is there a way to do this?
EDIT: I'm particularly interested in detecting optimization settings. The reason is that I'm writing commercial software that must run as fast as possible. While I am just modifying and testing the system I don't do all the optimizations because it takes too long. But I am worried that I may accidentally go and release an unoptimized version of the program. What I'd like to do is have the program give me a visual warning at start up saying something like "This is the slow version - do not release".
EDIT: Maybe I could write some little utility to run as a pre-build step? Is the command line stored in some file somewhere? If it is then I could extract it, then write it to some include file as a string and hey presto!
EDIT: My choice is not between debug and release. Debug is way too slow - I reserve that strictly for debugging. My day to day choice is between optimized and super-optimized (including the slow-to-compile link time compilation, or even profile guided optimization).
EDIT: I often make changes to the complex compilation process, different libraries, different pre-defined macros, different source files etc. It seems clumsy to have to maintain multiple, almost-identical project files differing only in a couple of optimization flags. I would much prefer to just, as-and-when-required switch a couple of flags in a single project and re-compile. I just want the executable to self test how it was created.
EDIT: IIRC there is some way to ask the visual studio to create a makefile. Can I ask visual studio to create this makefile for me as a pre-build step?
Comment: All of them or specific ones?
Comment: I am particularly interested in optimization flags.
Comment: This is standard in the VS build system.  You've got a Debug and a Release configuration.  You use the former, ship the latter.  The DEBUG macro is automatically #defined for the former.
Comment: Check this question which looks similar to your request. http://stackoverflow.com/questions/654450/programatically-detecting-release-debug-mode-net
Answer: The best way I know of to pass information from the build system to a running program is via the preprocessor. You can pass preprocessor definitions on the command line, and inside use them to set the value of variables, select code, or whatever with #ifdefs.
So setup your build system to use something like DEBUG_SET for debug its debug builds, etc.

Addressing the second "EDIT", yes the command line for your prebuild and postbuild tools are put in the project's vcproj file. It is an XML file, and you should find it under  at tag Configurations->Tool with a name attribute something like "VCPreBuildEventTool". Try adding one with the GUI and then opening the file in a text editor, and you should see.
It is fairly common around here to create tools to process vcproj files. I'm wondering if we couldn't use some of those property sheets mentioned in the comments instead though...
Comment: To expand on T.E.D.'s answer, you can also use property sheets ( http://msdn.microsoft.com/en-us/library/a4xbdz1e%28VS.80%29.aspx ) to make management of various compiler flags much less painful.  I have a "Release.settings" file that I attach to all the `Release` configurations and a "Debug.settings" that I attach to the `Debug` as well as tons of other property sheets for various things (a "Server" sheet detailing all the flags for server, such as not bothering to run any of the GUI things).
Comment: Its not that bad (unless 2008 is way different than the 2005 we use). Right click on your project file and select properties. Then on the property page select Configuration Properties->C/C++0->Preprocessor. Then select Processor Definitions, and add your definition. Put the correct definition in each configuration you use, and you're there. This is the exact scheme we use here to tell our programs which configuration they were compiled under.
Comment: If I was using a make file, that would be the perfect answer, but with a GUI, its a but clumsy.
Comment: Property sheets are definitely the way forward for any non-trivial set of projects. It's made our configuration much easier (we have debug and release versions of 32-bit and 64-bit targets across around 100 projects, all of these share most of their settings).
Answer: I think you might be going about this the wrong way...
See, while Visual Studio starts off giving you just Debug and Release configurations, there's nothing stopping you from adding as many as you like, with whatever compilation settings you like.
Certainly, for day-to-day use, you shouldn't be fiddling with compiler settings and so on. Just set them up once and switch configurations as needed.
To add more configurations, use the Build->Configuration Manager page. There you'll the default Debug and Release, and you can create your own "Super Release" or whatever you want to call it.
Answer: Create multiple configurations for your project, for example Debug, Release & Production.  Change the names of the output binaries for each configuration to match across configurations.  For example MyApp_d.exe, MyDll_d.dll for debug, MyApp_r.exe, MyDll_r.dll for Release, and MyApp.exe & MyDll.dll for Production.  This will help to keep all the different flavors straight without having to try to add code (which will be slow and brittle) that will detect at runtime which flavor is running and perform some magic then.
Comment: I wonder why this doesn't get more upvotes. Clearly looks to me like this answer addresses the real issue while the question goes into the wrong direction.
Comment: @mxp: I dont get it either.  In my experience, this is clearly the way to go.
Answer: Would it be possible to store the compile options (or, the full command line, if there is such) in a text file while invoking the build, and making sure to ship that file along with the executable?
[This is certainly not elegant, but just wanted to check.]
Comment: I have nothing in principle against such a trick - but I don't know how to do it. It would be great to be able to do some "pre-build step" where somehow the full command line gets copied to a file which then gets #included and made in to a string... or something...
Comment: @Mick: Thanks. But, I don't know VisualStudio, so I cannot tell you exactly "how" to do it. Sorry, it was just an idea. However, if available, my intention was to fopen the file and read the contents, possibly into a string.
Answer: Attempting to answer my own question...
If I search the visual studio help system for "predefined macros" I will get a page listing a variety of macros which are defined according to assorted compilation options. Its far from a complete answer, but it may be the best I'm going to get.
Answer: Several compilers set different defines when compiling. These you can then use in your program. (its not really detecting at runtime, its just something that is 'baked' into your program during compilation).
For GCC they are shown here. These also contain the optimization level.
Here is the list for Visual Studio. However I do not think it contains the optimization level, perhaps it has other info you can use.
Since this is the most common way to pass information from the compiler to the executable. I don't think this is possible for visual studio.
Answer: To do this right you will need to create an additional configuration called, say "SuperOptimised". You now have the standard configurations ("Debug" and "Release") and a third "SuperOptimised". The problem with this is that it makes the configuration management of the project much harder, to change a common setting between the three configurations, you need to make that change in three places.
The solution to that is to use "Property Sheets" (".vsprops" files) and the "Property Manager" tab. You can create a property sheet that is common across all three configurations, and specific sheets for Release, Debug and SuperOptimised. Combine the common settings with the specific settings (using property inheritance) to manage the configurations - the "Property Manager" tab allows you to do this. You can change the ".vsprops" files to change common settings across configurations without changing the configurations themselves.
More info on Property Sheets here:
http://msdn.microsoft.com/en-us/library/a4xbdz1e(VS.80).aspx
Finally if you want to check which configuration was build at runtime, use the preprocessor to define a macro value in the "SuperOptimised" .vsprops file, say "SUPEROPTIMISED". You can then check whether you have the right build with:
#ifndef SUPEROPTIMISED
    // Warn the user that this is not a shipping build
#endif

This may all seem like a lot of work, but managing non-trivial projects (and especially multi-project workspaces) through property sheets greatly reduces the chance of error when making configuration changes.
Comment: The property sheets do look nasty but they are not so bad. You create new property sheets in the "Property Manager" tab, you can save them as ".vsprops" files. Once they are saved you can add them to existing configurations as a hierarchy. To edit a property sheet, just double-click it in the "Property Manager" and you get the normal VS properties window (you don't need to edit them as text). You can set the macro in C/C++ -> Preprocessor - just type "SUPEROPTIMISED" in this box. Macros are separated with a ";".
Comment: I am tempted to mark this as the correct answer, it feels like it's problem solved... My only problem being that Microsoft documentation is so incredibly unhelpful that I don't know how I will ever get property sheets up and running. It shows an example line in the sheet stating " "... I have no idea what that means and I have no idea how to find out what that means. I was hoping to see things that looked more like "link-time-compilation=ON".. or whatever.
Answer: It sounds like you already have multiple configurations set up, and you just want to know for sure which one the current .exe was built with, rather than know exactly which compiler options were picked?
If so then the following are some options:

Build the .exe a different name for each configuration e.g App_d, App_super_optimized, etc
Add a different symbol definition in each config that can be checked as #defined at startup
Perhaps in conjunction with 2. make all but your release build require some file to be present, which you don't distribute. That way, your users CAN'T run a slow version even if you do release it by accident.
Comment: Well then I think that's precisely the problem. MSVC++ makes it very easy to create a new build configuration by cloning your existing release config. Many libraries do exactly this - static Vs DLL builds, etc.
Comment: @john: I already have debug and release. But I currently don't have separate optimized vs super-optimized configurations. I simply use release and manually flip a couple of flags to turn on link time code generation and sometimes even profile guided optimization.
Comment: I am not very expert on visual studio... I have just discovered the "configuration manager" and see that I can make a new project with "copy settings from:"... I'm confused about whether or not to tick the "Create new solution configurations" checkbox or not.
Comment: I think not, but I would have to check. I suggest you start a new question "how to create new build configurations" or something and explain you want to create optimized & super-optimized versions of your release build.
Comment: Or, ask Codeka to elaborate on his answer.
Answer: Visual Studio 2008 has already set this up for you. When you create a new project, it sets up two build configurations for you: Debug and Release. You can switch between these configurations with a toolbar control.
Debug has settings tailored for debugging, in particular optimization turned off.
Release has settings tailored for release, in particular optimization turned on.
The preprocessor macro DEBUG is only defined in the Debug configuration, so you can easily do someting like:
#ifdef DEBUG
::MessageBox("You are using the debug version", "Warning - Slow", MB_OK);
#endif

Note also, that these configurations put their output in different folders, so it's easy to tell them apart.
Answer: I have a trick for checking that I do not release Debug versions of my programs. I compare the size of the executables and DLLs to the sizes of the same binaries of the last release. They must be of similar, usually slightly increased size. If I have the Debug version of a file, the size is x3 or x4 thi size of the Release version.


Notes tied to rests?

Question: This is the end of Leo Brouwer's study 4 from the "Estudios Sencillos":

Some notes here are tied to rests, or so it seems. What did Brouwer want the performer to do?
Comment: A related scenario is discussed in [Understanding the ending of Debussy's La fille aux cheveux de lin](https://music.stackexchange.com/q/58698/70803).
Comment: These notes aren't tied to rests, they're tied to nothing. You can just as well employ a "laissez vibrer" at the end of a piece, with *nothing* following. In all cases the meaning is "let strings ring as long as they will, regardless of tempo".
Answer: It means to let the chords ring, rather than cutting them off at the moment of the rest. Brouwer doesn't want the chords cut off; rather he wants them to fade naturally. This is a fairly common way to notate that. Sometimes such "ties to rests" will be accompanied by "l.v." or "Laissez Vibrer" ("let vibrate").
Here is an example from Debussy's Prelude for Piano (Preludes, Book 2, Number 1), the final two measures. The half-note chords are allowed to ring, via the damper pedal, and decay naturally (i.e., with the dampers lifted), while the two final chords are played.
Comment: @Tim Not sure about that. How is two letters intuitive if you have no idea what they stand for (and even in which language the phrase might be)? I'd say both notations are something you either know or don't know, not something you can easily guess. "Laissez vibrer" can be comprehensible if you know just a little French, but "L. v." is opaque.
Comment: Unless one actually knows the meaning, tying to rests isn't intuitive. L.v is.
Comment: This doesn't really make sense to me as a piano player so I'm trying to understand. Usually, the damper stops the sound from the piano as soon as I lift my finger from the key. If I want the let the note ring, I press the sustain pedal to keep the damper off the string as long as I hold the pedal (though this does all the dampers at once). There's no way I know of to just "let a chord ring out naturally" on the piano. The only thing that comes to mind that **might** do this is the [Sostenudo Pedal](https://en.wikipedia.org/wiki/Piano_pedals#Sostenuto_pedal). Is that perhaps what this is for?
Comment: @Tim  With all due respect please don't state personal preference as an absolute.   The meaning of  a tie to a rest is obvious to a number of musicians I know.
Comment: @CarlWitthoft - hadn't realised I did state anything as a personal preference. Sorry.
Comment: @Chipster That's a good point. The Debussy (and the general case) employ the sustain pedal. What I meant by "decay" naturally, is that the strings are allowed to vibrate, damperless, until the sound fades out, rather than cutting off the sound (by releasing the pedal) at a specific time. I'll clarify the post to make that explicit.
Comment: @Tim: An L.V. notation might for some instruments be preferred if no notes should be damped, but using ties would allow for the possibility that some notes should be damped while others are allowed to ring.  The difference in notation might also be relevant if a piece might be performed by different kinds of instruments.  It may be that if one is playing a piece on an instrument where notes would naturally decay over a period of four bars, letting the notes ring for that whole time may be preferable to damping them sooner, but if one is playing on a sustaining instrument, ...
Comment: ...having the note stop after one bar would be preferable to having it stop at some other time or having it sustain for the whole four bars.
Comment: @supercat - in a lot of cases, the notes would (should) have been written out with whatever duration the composer wanted. The main case I find for l.v., which more often than not, isn't even notated, is with classical guitar pieces, where cutting notes off as writ. makes it all sound wrong. I inherited a student from a teacher who had taught just that, and the (exam) pieces sounded just awful, and I'm certain would have got him a fail.
Comment: @Tim: In many cases, the "best" duration for a note will depend upon the combination of instruments used to perform a piece and, in some cases, the acoustics of the space in which it is being performed.  Depending upon the nature of the piece, I'd interpret ties connected to rests as an invitation for a performer to exercise judgment as to what duration would be most appropriate given the instruments and venue.
Comment: Thanks, that makes more sense to me now. +1 :)
Answer: Depending upon the style of music, I would be inclined to interpret notes tied to rest as an invitation to hold notes beyond the indicated duration if, in a performer's judgment, such treatment would make the piece sound better on the particular instruments being used, and in the particular venue where the piece is being performed, than playing them precisely as marked.
In many cases, it may be desirable to have a slight "echo" of notes that are played in one measure persist into the next measure, but for the sound of such notes to be much quieter than the sound of notes played in the later measure.  If a piece is being performed in a very resonant space, or on a piano whose dampers quench string vibrations relatively slowly, this may naturally happen even if notes are cut off precisely at the end of a measure.  If the piece is played on a piano with very fast-acting dampers in an acoustically dry space, however, the start of the next measure may sound very "empty" if notes were cut off as written.  Unless a piece is written for a very specific purpose, there's no way a compiler will be able to anticipate the acoustics of the places it will be performed, or the characteristics of the instruments of the instruments that will be used, but a performer who is using the actual instruments in the space would be far better able (perhaps in conjunction with other people sitting in the audience area) to judge such things.

Notes tied to rests?


Open neighborhood in Lie group

Question: The following is from "An Introduction to Lie Groups and Lie Algebras" by Kirillov.
Let $G$ be a connected Lie group and $U$ be a neighborhood of $1$.  Then if $H$ is the subgroup generated by $U$, $H$ is open because $h\cdot U$ is a neighborhood of $h$ in $G$.
I am not seeing why the last part is true.  If the product in $G$ were an open map it would be clear that $h\cdot U$ is a neighborhood of $h$, but why is it true anyways?
Comment: The map $x \mapsto hx$ is a homeomorphism $G \rightarrow G$ (continuous with continuous inverse).  The image of $U$ under this homeomorphism is $hU$.
Comment: Ah, the product **is** an open map from $G\times G$ to $G$ !
Answer: Multiplication by $h$ on the left is a homeomorphism from $G$ to itself.
In particular, $U$ open implies $hU$ open.
Comment: See the comment by D_S. One only needs that $G$ is a topological group.
Comment: I'm confused why it's a homeomorphism.  Doesn't the definition only say that multiplication $G\times G\rightarrow G$ is a smooth map?
Comment: Ah I see; that's what I was missing.  Thanks!
Answer: Let $h\in H$, and $L_h(x)=hx$. Since $L_h$ is a diffeomorphism, it is an open map. We deduce that $L_h(U) =\{hu, u\in U\} \subset H$ is open. Since
 $h=h. 1\in L_h(U) $, we deduce that $H$ contains an open neighbourhood of $h$ and henceforth is open.

Open neighborhood in Lie group


How do I order a search query by best match?

Question: I am using the following code.
<code>$query = \Drupal::entityQuery('node');
  $query->condition('status', 1);
  $query->condition('type', 'article');
  for ($i = 0; $i < count($split_keys); $i++){
  $group = $query->orConditionGroup()
  ->condition('title', '%'.$keys.'%' ,'LIKE')
  ->condition('body', '%'.$keys.'%' ,'LIKE')
  ->condition('title', '%'.$split_keys[$i].'%' ,'LIKE')
  ->condition('body', '%'.$split_keys[$i].'%' ,'LIKE');
  }
  $query->range(10,20);
  $query->addExpression('CASE WHEN title like %'.$key.'% THEN 0
       WHEN title like %'.$split_keys[$i].'% THEN 1
       WHEN body like %'.$keys.'% THEN 2
       WHEN body like %'.$split_keys[$i].'% THEN 3
       ELSE 4 END', 'order_col');
  $query->sort('order_col', 'ASC');
  $entity_search = $query->condition($group)->execute();
</code>
I am trying to sort by best match, but I get the following error.

Call to undefined method Drupal\Core\Entity\Query\Sql\Query::addExpression()

How can I fix the code?
Answer: An entity query can't have arbitrary expressions added to it. To proceed with your current approach you'll need to execute a raw query against the database.
But to address your actual question, How to create search query in Drupal 8 order by best match, the answer is to use the Search API module:

This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine. For site administrators, it is a great alternative to other search solutions, since it already incorporates facetting support and the ability to use the Views module for displaying search results, filters, etc. Also, with the Apache Solr integration, a high-performance search engine is available for this module.

In my experience the Solr integration is excellent, but if you don't have a Solr server handy, you can always fall back on the included database backend module. I would imagine that the results you get using search API will be better than any query you can put together yourself in any short amount of time.
Comment: Thank you for your suggestion @Clive, is there any solution besides using Search API, or any suggest if using another query to get that result? I'm very noob to integrate Search API module with my custom theme
Comment: I don't have another suggestion, sorry. If you're happy that your SQL logic with the cases etc is correct, then converting it to use a raw query instead of entity query is the best I can advise


Rest reading a long using @QueryParam always returns 0 when using @POST

Question: I send the following ajax call to my JBoss server (using jQuery):
$.ajax({
  type: "POST",
  url: "http://localhost/services/v1/online/123/abc",
  data: {
    "status": 100
  },
  contentType: "text/xml; charset=\"UTF-8\"",
  success: function(data, textStatus, jqXHR) { },
  error: function( jqXHR, textStatus, errorThrown ) { },
  dataType: "xml"
});

My Java code looks like this (@ApplicationPath and class- @Path is setup correctly so the following is triggered):
@POST
@Path("/{docId}/{secId}")
@Produces(MediaType.TEXT_XML)
public String getSectionAccess(@PathParam("docId") String docId,
                               @PathParam("secId") String secId,
                               @QueryParam("status") long timeInMS) {
  System.out.println(timeInMS);
}

My problem is that the timeInMS always returns the value 0. If I use @GET instead of @POST then timeInMS equals 100 as expected.
What am I doing wrong?
The following code:
ResteasyProviderFactory.getContextData(HttpServletRequest.class).getParameter("status");

shows me that the result of status is "100" (a string but can be converted to a long)... Why is the value not inserted in the timeInMS when using @POST (or @PUT for that matter)?
Answer: Change the annotation @QueryParam("status") to @FormParam("status"). Then change the contentType to application/x-www-form-urlencoded.
Or change the url to http://localhost/services/v1/online/123/abc?status=100
Comment: Thank you very much. For some reason it is a QueryParam when using GET in jQuery and FormParam when using POST or PUT


Expected response to be a , but was <200>

Question: Hi guys i have a controller code with the following :
class FeedbacksController < ApplicationController

  def create
    @feedback = Feedback.create(feedback_params)

    if @feedback.errors.any?
      flash[:error] = @feedback.errors
      render 'new'
    else
      redirect_to :back
    end

  end

test spec
require "rails_helper"

RSpec.describe FeedbacksController do

  describe "POST create" do

    context 'when param[:name] is present' do
        it 'should redirect to homepage' do
          @feedback = Feedback.create(:name => "Hah")
          @feedback.save
          is_expected.to redirect_to new_feedback_path
          debugger
        end
      end
  end
end

However when i run localhost, the output is exactly what i want but as of the unit test, it's not passing but returning me
"Expected response to be a m was was <200> ."
May i know why is it so and how should i pass my test case ?
Comment: I don't understand how you are even getting a 200 response. I don't see any call to your controller at all in your test.
Comment: What's your subject? `describe "PUT create"` - PUT is for update.
Comment: @AlexKojin I've re-edit them. Haha thx for telling me that.
Comment: @David wouldn't the Feedback.create call the controller ?
Comment: no ... thats creating an instance of the Feedback model.
Answer: You are missing the actual post request to your controller.
Please read this: rspec documentation
So this:
      @feedback = Feedback.create(:name => "Hah")
      @feedback.save

Should not be there. The second line is superfluous anyway, create already saves the object.
You are looking for code like this:
   it 'should redirect to homepage' do
      post feedback_path, params: { name: 'hah' }
      expect(response).to redirect_to(new_feedback_path)
    end


Difference in amount of samples, does that affect my chi squared test?

Question: So I have the following pandas crosstab table

a = np.array([[1844,  119],
       [4139,  367]])

As you can see the amount of user who are in the "não repescado" category. Surpass, considerably the amount of users in the "repescado" category. In this case, should I aim to make the amount of samples of each side equivalent since the test is frequency based I ought to believe to follow this line of thought? Or I can make the test without a care? If so how come I can do it without a care? Asking this question because when I learned all sample seen to have the same amount on each row and column sum
Comment: As a partial answer, the chi-square test of association will work fine when the column sums or row sums are far from equal.  In any case, you ***don't*** want to try to adjust the counts in the table to make e.g. the column sums equal. ...  For your table, what may be more informative than the chi-square test is to look at the proportions within each column or row (whichever makes sense).  For example, the proportions in column 1 are 0.31 and 0.69. And the proportions in  column 2 are 0.24 and 0.76.  Whether the difference in these proportions across columns is meaningful, is up to you.
Answer: It will affect the Chi-square test of independence, and in short, you should probably not do what you suggest.
You can test it for yourself, by making the number of observations repescado  similar to não repescado, while retaining the original distribution of repescado (something like 24.5% for finalizou, and 75.5% for não finalizou).
Your original table returns a Chi-square value of $\approx 8.238$. But here's what happens if you increase repescado  up to 5983 observations ($1465+4518$ if we retain the "24.5% & 75.5%" distribution):
import numpy as np
from scipy.stats import chi2_contingency
import pandas as pd
a = pd.DataFrame(
       data=np.array([[1844,  1465],
                      [4139,  4518]]),
       columns=["não repescado", "repescado"],
       index=["finalizou", "não finalizou"])

print("chi2 value =", chi2_contingency(a)[0])

chi2 value = 59.685441879817624

This will affect the p-value and the conclusion you can draw from your dataset. It is almost certainly not a good idea, depending on what you want to know.
If you increase your sample size by oversampling people in the repescado category, you won't be able to make valid inferences on the population anymore -assuming your original sample is a random sample from your population of interest. (In other words, your sample will be biased and won't be "representative" of your population anymore - even if strictly speaking, "representative" is an abuse of language).
So if you're interested in drawing conclusions about the population from which your sample comes from, don't oversample the repescado category, and use the chi-square test (or even the Fisher exact test for $2 \times 2$ tables like this one).
If you're interested in comparing the repescado and não repescado categories, oversampling might be a reasonable idea, but then you probably shouldn't use a chi-square test for that (for example, look into analyzing odds ratio instead). In this case, it's probably worth asking another question, where you'd explain more in detail what you want to learn from your dataset exactly.
Comment: In this case odds ratios is actually very interesting. I guess it will give me the odd of a certain group that is exposed to that new flux, and a group that is not. And tell me which group will be more susceptible to the wanted closure
Comment: @INGl0R1AM0R1 You might want asking another question about it, to know which analysis method is best given the way you collect your data (as there are others measures than odds ratios, like the risk ratio, see https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4640017/ for example).


Android: Issues in animating edittext?

Question: I tried to animate the edittext when user starts editing it.
I have tried the following code,
 EditText txtPassword = (EditText) findViewById(R.id.editText1);
 Animation  anim = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.anim);
 anim.setInterpolator((new AccelerateDecelerateInterpolator()));
 anim.setFillAfter(true);
txtPassword.startAnimation(anim);

anim.xml
````````
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="0" android:toYDelta="-50%p" android:duration="100"/>
</set>

The animation works fine.
but the edittext stopped userinteraction after animation.
If the user touches the previous position of the edittext of the screen, the keyboard appears.
but the edittext actually in the new position should respond. What I have to do?

I hope that someone can edit my question in correct english format.
Answer: (USEFUL HINT: There is a Android library for using the Honeycomb (Android 3.0) animation API on all versions of the platform back to 1.0!. It is called NineOldAndroid.)
(USEFUL HINT (Android Developers, View): Starting with Android 3.0, the preferred way of animating views is to use the android.animation package APIs. These Animator-based classes change actual properties of the View object, such as alpha and translationX. This behavior is contrasted to that of the pre-3.0 Animation-based classes, which instead animate only how the view is drawn on the display. In particular, the ViewPropertyAnimator class makes animating these View properties particularly easy and efficient. )
(NOTE THAT: BELOW SOLUTION IS FOR PRE-HONEYCOMB.)
Animations with android is a bit tricky to understand, in contrast to iOS. You need to know that;

only the ghost of the Android View subclass is animated.
and the grave is still at the ancestor coordinate

So the solution might be;

Block touch events to view
animatingView.setEnabled(FALSE);
animate view
Remove animatingView
animatingView.setVisibility(GONE);
(animatingView.getParent()).removeView(animatingView);
Add the exact duplicate of view to the new coordinates.
Comment: Thank for your reply but what about gingerbird(android 2.3)? need soln.
Comment: below part is the solution i provided. Which part you don't understand?
Comment: you said its works android 3.0 but needed for below android 3.0 version
Comment: no, i said my solution works for PRE-HONEYCOMB, which means versions released previously than honeycomb.
Comment: Also, there is a perfect animation wrapper called NineOldAndroid ( http://nineoldandroids.com/ ) written by Jake Wharton. It would be easier to implement than my solution. Good Luck!

Android: Issues in animating edittext?


How to best define a "contrast" in a Principal Component Analysis (PCA)?

Question: I have been studying how to interpret principal components.
I recently came across an example of a particular eigenvector:
$$e_j^T = \left[ \frac{\sqrt{2} }{2}, \frac{-\sqrt{2} }{2}, 0, \dots,0 \right]$$
I am under the impression that, often in social sciences, "this is called a contrast."
From what I can see, we have the difference between $X_1$ and $X_2$ (variables in our original dataset) playing a role in the $j$th eigenvector.
What can this say about the relationship between $X_1$ and $X_2$, with respect to this eigenvector?  There is clearly something going on with the equal, yet opposite, contribution of these independent variables, to our (possibly first) principal component.  I guess the answer to this is the answer to the question, "what is a contrast?"
Strangely enough, googling hasn't coming up with much of anything aside from dense discussion such as found on the Wikipedia page.
Comment: Some corrections are needed to stave of possible confusion: first, $e_j^\prime$ is an eigenvector, not an eigenvalue. Second, it does not assert any relationship at all between $X_1$ and $X_2$: it is literally just a linear combination of the two. FWIW, googling "linear regression test contrast" turns up [the Wikipedia article on the subject](http://en.wikipedia.org/wiki/Contrast_%28statistics%29) right away.
Comment: argh, thanks, I've fixed my typos and generally cleaned up the question.
Comment: I'm confused...I was taught it's dangerous to interpret PCA components because they are not identifiable, only the subspace they span is identifiable.
Comment: @aabeshou On the contrary, one *can* interpret individual PCA components (and this is often done). Nevertheless, I agree with your question and answer.
Comment: @user43228 That's right. I think it's understood that $e_j^T$ is being considered only up to a nonzero multiple. The usual way to express it as a contrast would be as the vector $(1,-1,0,\ldots,0)$ or $(-1,1,0,\ldots,0)$. That is why Matt (the OP) is using terms like "equal, yet opposite contribution" without focusing on the magnitudes of the components.
Comment: @whuber I learned that they were not even identifiable modulo scalar multiple, because you get the same subspace by rotating your principal components.
Comment: @aabeshou A "rotation" is in that sense is not part of a PCA. A PCA finds eigenspaces and eigenvalues. The only rotation it can apply, without changing its results, would be an orthogonal transformation of orthonormalized basis elements of any subspace of dimension greater than one (which only rarely occurs). I suspect what you mean by "rotation" involves a *factor analysis* rather than a PCA.
Comment: @whuber I think this is probably going off into a different discussion about the interpretation of principal components, but what I mean is that PCA finds a low-dimensional (D) linear subspace that minimizes expected projection distance, and one choice of basis for that subspace is the first D eigenvectors, but it could be dangerous to interpret those vectors as anything but one possible basis for the _subspace_, which is what is identifiable and relevant.

That being said, I see that the eigenvectors are not totally arbitrary in that they point in directions of maximum variance.
Comment: @aabeshou Thank you for the clarification. That subspace is naturally graded into a flag, ordered by decreasing eigenvalue. This is what justifies referring to a first, second, third, *etc*, principal component. If the purpose is only to identify a subspace then indeed there are many more choices of basis. It's at that point, I believe, that other procedures such as factor analysis depart from PCA (and therefore ought to be distinguished from PCA as such).
Comment: @whuber Now we get back to the reason I brought this up: having agreed (if I understand you correctly) that we can't assign meaning to the components that come out of PCA, and that if we seek meaningful components we must turn to other methods, is it still reasonable to ask the question above about whether the component implies a negative relationship between X1 and X2? To answer my own question, I suppose it does still make sense because the component is still meaningful at least in the sense that it points in a direction of high variance in the set.
Answer: Remembering that interpreting PCA results can be an art-form, let's use a relatively simple data set. The link here shows a PCA and interpretation of Fisher's iris data, which you can easily obtain for yourself and analyse in the software of your choice.
The bottom of p.9 shows the eigenvalues for the four principal components and p.11 provides an interpretation of the first two principal components.
As you can see, PC2 has been called a contrast between sepal length/width and petal length/width. The reason for that is that the eigenvector values corresponding to the sepal measurements are all negative and those corresponding to the petal measurements are all positive. However, and this is where the PCA "art" interpretation comes into it, you could argue that petal width has little effect on PC2, as it is only 0.08 and therefore not a very large value.
Looking at PC3, and ignoring the fact it accounts for such little variance (as that is not the point of this discussion), it appears to be a contrast between sepal and petal width, on the one hand, and sepal length on the other.
Having a subject matter expert on hand to help interpret PCA results can be very useful.
Comment: +1 and I took the liberty of correcting what seemed a mistake/typo in one sentence, confusing eigenvalues and eigenvectors. Please check that this is indeed what you had in mind.


SPF softfail for forwarded emails to Gmail account

Question: I've been able to make SPF pass on all the sent emails from my Postfix server. But for forwarded domains which simply redirect email to my gmail id I see softfail in the SPF.
For example if I send email from a hotmail account to firstname.lastname@example.com then it is forwarded to test email id firstname.lastname@example.com.
I've added SPF header "spf1 a mx -all" for my hostname(host.tariffplans.com) as well for all domains. The A record of all domains/subdomains is correctly pointing to my server IP : 184.108.40.206
But in the forwarded email header .. Google shows it as softfail.  What could be the problem?:
Delivered-To: email@example.com
Received: by 10.114.96.70 with SMTP id dq6csp51447ldb;
        Sat, 19 Jul 2014 23:05:03 -0700 (PDT)
X-Received: by 10.182.65.66 with SMTP id v2mr22896624obs.74.1405836302184;
        Sat, 19 Jul 2014 23:05:02 -0700 (PDT)
Return-Path:
Received: from host.tariffplans.com (tariffplans.com. [126.96.36.199])
        by mx.google.com with ESMTPS id js4si25593503obc.98.2014.07.19.23.05.01
        for
        (version=TLSv1.1 cipher=ECDHE-RSA-RC4-SHA bits=128/128);
        Sat, 19 Jul 2014 23:05:02 -0700 (PDT)
Received-SPF: softfail (google.com: domain of transitioning email@example.com does not designate 188.8.131.52 as permitted sender) client-ip=184.108.40.206;
Authentication-Results: mx.google.com;
       spf=softfail (google.com: domain of transitioning email@example.com does not designate 188.8.131.52 as permitted sender) firstname.lastname@example.com
Received: from BLU004-OMC4S20.hotmail.com (blu004-omc4s20.hotmail.com [184.108.40.206])
    (using TLSv1.2 with cipher AES128-SHA256 (128/128 bits))
    (No client certificate requested)
    by host.tariffplans.com (Postfix) with ESMTPS id 668E01E1619
    for ; Sun, 20 Jul 2014 11:35:01 +0530 (IST)
Received: from BLU181-W79 ([18.104.22.168]) by BLU004-OMC4S20.hotmail.com with Microsoft SMTPSVC(7.5.7601.22712);
     Sat, 19 Jul 2014 23:05:01 -0700
X-TMN: [mcaEHqstvkaYJBg7Y5zPleq+hEPF4BC7]
X-Originating-Email: [firstname.lastname@example.com]
Message-ID:
Content-Type: multipart/alternative;
    boundary="_dfcd1b0c-5d39-4204-a29c-16fb51556946_"
From: Bhasker Yamsani
To: "email@example.com"
Subject: testing
Date: Sun, 20 Jul 2014 02:05:00 -0400
Importance: Normal
MIME-Version: 1.0
X-OriginalArrivalTime: 20 Jul 2014 06:05:01.0018 (UTC) FILETIME=[8A96E3A0:01CFA3E0]
Comment: If I understand the headers correctly you receive mails on your server, but deliver them via hotmail? If you are using an external relay, you also have to include their IPs in your SPF-Record.
Comment: No I'm receiving email for a domain but forwarding it to my gmail account. The test sample email was sent from hotmail account to firstname.lastname@example.com which was forwarded to my Gmail account.
Answer: Your server host.tariffplansindia.com is receiving a mail from outside, in this case email@example.com. The receiver on your host is firstname.lastname@example.com. Now your server relays that mail (without changing the envelope From-address) to gmail. The gmail server now gets a mail from your server host.tariffplansindia.com with envelope-From firstname.lastname@example.com. Now the SPF-Record of hotmail.com forbids all senders except its own, and you can't do anything about that. SPF breaks this kind of mail-forwarding, that's a known issue, but it's also solved by Sender Rewriting Scheme (SRS) from Open SPF.
Using SRS, the relaying mailserver can rewrite the envelope-From so that it comes from a domain you control the SPF record for (host.tariffplansindia.com). Unfortunately, setting up SRS on a mailserver requires - in most cases - compiling and installing software by hand, there is only a very limited variety of available implementations listed on open-spf.org and also an existing question of how to perform SRS on postfix.
Comment: sebix, I hope you'll forgive me for editing your answer as I have.  Since the OP was kind enough to tell us all the real domains involved in this, I thought we could use the actual values in your answer (which I thought was otherwise very good, +1 from me) instead of example domains.  Anyone who's tempted to downvote this answer, please check and see if what you disagree with is something I wrote, not sebix's original.
Comment: @MadHatter I also wanted to edit my answer and change the domains, but due to connectivity issues, you were faster. But these were not the only changes you did. I can't see anything in your edit that could be wrong.
A good read about mail spoofing and the difference between envelope and message can be found on [security.stackexchange:  Why is it even possible to forge sender header in e-mail?](http://security.stackexchange.com/a/30741/52333)
Comment: sebix, yes, I also thought you might be a little confused about how SRS works, so I changed that a bit.  If you aren't OK with those edits, you're (of course!) welcome to revert them and do the domain changes yourself.
Comment: Thanks Sebix. I did not find this problem while using Cpanel. So I guess Cpanel must be using SRS.
Comment: Apologies for asking to confirm, but are you actually saying it's impossible to forward email from an external domain to an @gmail.com adres and have SPF pass? It kind of makes sense because why would Google allow any IP / domain to pass SPF, this seems like a security risk. I just need final confirmation. The infrastructure I use does not support SRS.
Comment: EDIT: It turns out I have Postfix and root access. I installed SRS and it's working perfectly! Only took me 3 years to solve this problem!
Answer: Found easy solution for me, I just add a TXT record in my domain name hosting with " v=spf1 ip4:xxx.xxx.xxx.xxx include:_spf.google.com ~all " where xxx.xxx.xxx.xxx is your server IP.
Comment: Someone downvoted this comment without specifying a reason so I upvoted it again. The reason why it should be considered is because of the `include:_spf.google.com ~all` line in there. Could that be a solution to stop Google from reporting forwarded emails as illegitimate? In the context of a reply, at least that should be considered.


Why does Array elements have to be of the same type

Question: Array DS requires all its members to have the same time. Java throws ArrayStoreException when an attempt has been made to store the wrong type of object into an array of objects. Don't remember what C++ does.
Is my understanding correct that it's important to have all objects of the same type in array because it guarantees constant time element access through the following two operations:
1) element size * element index = offset
2) array pointer address + offset

If objects are of different types and consequently different size, the above mentioned formula won't work.
Comment: you dropped your link :)
Comment: Your original `ArrayStoreException` Link did refer to `http://ArrayStoreException`
Comment: @SomeJavaGuy, what link?
Comment: @SomeJavaGuy, ah, I see, thanks
Answer: Because: we want it like this.
What I mean is: people using the Java language (probably the same for C++) are using a statically typed language for a purpose.
And when such people starting thinking in plurals; they typically think in plurals of "similar" things.
Caveat: in Java, everything is an Object, so you can always declare an Object[] and stuff anything into that. Strings, Numbers, whatever.
And that also leads to the other important aspect: in C++, your array represents an area in memory. And you better have same sized elements in that area; to avoid data corruption.
In Java on the other hand, an array is not pointing to raw memory.
Long story short: there are real differences between Java and C++ in this context (that one has to understand to make an informed decision); and then there is the "language" thing itself. In other words: this is not Ruby land, where you just put ducks, numbers, plants and quack sounds in the same "list" without further thinking.
Final thought, based on that joke in the last paragraph: in my eyes, an array is an implementation of the list concepts, thus it is about a collection of things of the same nature. If you want a collection of unrelated things, I would rather call that a tuple.
Comment: yeah, thanks, but since `JVM` is mostly implemented in `C++`, it still comes down to the underlying concepts. So my question is more why the array has to have the same type, rather than why it's so in `Java`. So I gather from your answer that it's not because of the constant time access, but rather because of constistency?
Comment: @Maximus [this accepted answer might be worth a reading](http://stackoverflow.com/questions/12369957/dealing-with-an-arraystoreexception)
Comment: @SomeJavaGuy, yeah, thanks, but it's too `Java` specific. I realize now that I shouldn't have added `Java` tag. And someone removed `c++` tag
Answer: Yes, you are right. All that is required for constant time random access.
Also, you can have an array of void pointers if you want to store different data types in a single array. For instance in c++, do
void * a[N]
a[i] = (void *)(&YourClass)
Similarly, use Object[] in java.
Comment: yes, index of ith element = base_address +  sum(element_sizes before the ith element). Not O(1) random access anymore. right!!
Comment: thanks, _if you want to store **different** data types in a single array_ -  so does then the formula in my question work?
Answer: The C++ language (and compiler) requires the type of the elements to be stored in an array for various reasons, like pointer arithmetics and array subscription (e.g. x[i]), default initialisation of the elements, dealing with alignment restrictions, ...).
int x[3] = { 1,2,3 };  // array of 3 int values, each being properly aligned concerning processor architecture;
myObjectType objs[10]; // array of 10 objects of type myObjectType, each being default initialised (probably the default constructor), each being properly aligned
myObjectType *objs[10]; // array of 10 pointers to objects of type myObjectType (including subclasses of myObjectType; allowing dynamic binding and polymorphism). Note: all pointers have the same size, the object to which they point may differ insize.

int *intptr = x;
bool isEqual= (intptr[2] == x[2]); // gives true
intptr += 2; // increases the pointer by "2*sizeof(int)" bytes.

So, yes, you are right: one reason is because of calculating offsets; But there are other reasons as well, and other issues like alignment, array to pointer decay, default initialisation logic are probably more subtle but essential, too.
Comment: thanks, I'll read bout _alignment, array to pointer decay, default initialisation logic_


Center dynamic div.card horizontally with Bootstrap 4

Question: I'm listing articles from a database on a website based on Bootstrap 4. I would like the blocks (div.card) to always be centered horizontally no matter how much there are with a maximum of 3 blocks per line. I'm pretty sure there's a simple way to do it but my tests where unsuccessful so far.
Here's the page : http://www.0000.yelofox.fr/nos-actualites
(You'll probably need to connect, I'm not sure as I'm logged in automatically. I can provide the password if needed)
The loop I use is made up that way :
echo '
';
echo '
Nos actualités
';
echo '
';
while ($data_news = mysqli_fetch_assoc($rq)){
    echo '
';
    echo '...';
    echo '
';
}
}
echo '
';
echo '
';

Let me know if you need further elements.
Thanks for you help
Comment: It can be done by css. PHP is giving the data , do the styling by css. And its lots easier with bootstrap.
Comment: I'm sure it is but no matter what I try, I can't get a proper alignment in Responsive
Answer: Seeing that the class="text-center" didn't work. You can try the following...
echo '
';
echo '
Nos actualités
';
echo '
';
while ($data_news = mysqli_fetch_assoc($rq)){
    echo '
';
    echo '...';
    echo '
';
}
}
echo '
';
echo '
';

Comment: Thanks for the suggestion. .text-align will just center the text inside the blocks. It's the blocks themselves that I'd like to center in the div.row.


Show $\phi: \mathbb F_3 \times \mathbb F_3 \rightarrow R$ given by $\phi(a,b) = a\epsilon_1 +b\epsilon_2$ is bijective, $a,b \in \mathbb F_3$

Question: Show $\phi: \mathbb F_3 \times\mathbb F_3 \rightarrow R$ given by $\phi(a,b) = a\epsilon_1 +b\epsilon_2$ is bijective, $a,b \in \mathbb F_3$.
$R = \mathbb F_3[X]/\langle X^2 -1\rangle$ and $\epsilon_1 = \alpha - 1, \epsilon_2 = -\alpha - 1$ for $\alpha = [X] \in R$.
I've already proved $\phi$ is surjective by: $[x] = [a^{'}X+b^{'}] \in R$ then $\phi(2a^{'}+b^{'}, a^{'}+b^{'})=[x]$.
However I'm having trouble showing that $\phi$ is injective. By the way I know $\epsilon_{1,2}$ and $\pm \alpha$ are zero divisors and units, respectively.
Thanks.
Comment: Since you've already shown your map to be surjective and both ${\mathbb F}_3 \times {\mathbb F}_3$ and $R$ contain 9 elements, you're already done.
Comment: May I ask why ? Is it because that without injective, then $\phi$ couldn't be surjective. Or how do I state this formally ?
Answer: Let's look this from an abstract point of view. So, let $F$ be a field, $R=F[X]/(X^2-1)$, $\alpha=[X]\in R$, $\varepsilon_1=\alpha-1$, $\varepsilon_2=-\alpha-1$.
The map $\varphi\colon F\times F\to R$ defined by
$$
f(a,b)=a\varepsilon_1+b\varepsilon_2
$$
is of course $F$-linear; $R$ is generated by $1$ and $\alpha$; so in order to show it's surjective, we need to find
$$
a(\alpha-1)+b(-\alpha-1)=1
$$
so $a-b=0$ and $a+b=-1$. The similar system for $\alpha$ gives $a-b=1$ and $a+b=0$. The systems are both solvable if and only if the characteristic of $F$ is different from $2$.
So the map $\varphi$ is surjective whenever $\operatorname{char}F\ne2$. Being a linear map between two-dimensional vector spaces, it is also injective.
Answer: Here is an alternative way of proving injectivity:
$\Phi$ is injective, if the only element that is mapped to $\bar 0 \in R$ is $(0,0) \in \Bbb F_3 \times \Bbb F_3$. So let's have a look at the elements that get mapped to $\bar 0$, ie. the kernel of $\Phi$:
\begin{align}
\ker \Phi & = \{(a,b) \in \Bbb F_3 \times \Bbb F_3 \mid \Phi(a,b) = \bar 0\} \\
& = \{a (\alpha -1) + b (-\alpha -1) = \bar 0 \mid (a,b) \in \Bbb F_3 \times \Bbb F_3 \}\\
& = \{a \alpha - a + b (-\alpha) - b = \bar 0 \mid (a,b) \in \Bbb F_3 \times \Bbb F_3 \}\\
& = \{\alpha(a-b) -(a+b) = \bar 0 \mid (a,b) \in \Bbb F_3 \times \Bbb F_3 \} \\
& = \{(a,b)= (0,0) \in \Bbb F_3 \times \Bbb F_3\}
\end{align}
which you can verify by taking all possible $(a,b) \in \Bbb F_3 \times \Bbb F_3$ and modding out $\alpha^2 -1$.
Comment: If I understand your argument correctly (pretty new in this field), you have shown $\ker \phi = \{(0,0) = e \in \mathbb F_3 \times \mathbb F_3 \}$ which implies $\phi$ is injective using group theory (homomorphism). Does this also apply to $\phi$ ? To be honest, I don't know if $\phi$ is a group or a ring homomorphism ? The problem only states "show that the function $\phi$ is bijective", nothing else.
Comment: The problem I have with this solution is the last step. All the preceding ones were ok, and relatively easy, but how did you justify this leap? Warning: if you replace $\Bbb{F}_3$ with $\Bbb{F}_2$ it is incorrect, so the argument has to reflect that somehow.
Comment: Maybe I was too quick, but actually you have the relations $a-b = \alpha$ and $a+b=1$ *or* $a-b = 0$ and $a+b = 0$. The first one isn't possible, since $a,b \in \Bbb F_3$ and the second one yields $a=b$, hence $2a = 0$, which is only possible for $a = b = 0$. If you take $\Bbb F_2$, you get the extra solution $a=b=1$ for this, hence no injectivity.


ndarray rust, change values of a slice

Question: In python's numpy given an array
a = np.zeros((10,10,2))

I could modify values of the array corresponding to a slice 4:6,: as such:
a[4:6,:] = [0,255]

In rust: given a ndarray from the ndarray package, i can slice
let mut img = Array3::<u8>::zeros((10,10,2));
let slice = img.slice_mut(s![4..6,..,..]);

But what is the idiomatic way of changing the values of that slice, by broadcasting the subarray corresponding to the last axis i.e. [0,255]?
Answer: through other means i found answer and im posting it here. One needs to combine slice_mut with method .assign(&stuff to broadcast)
 let mut img = Array3::<u8>::zeros((10,10,2));
 let arr = Array::ones(2);
 img.slice_mut(s![4..6usize,..,..]).assign(&arr);

ndarray rust, change values of a slice


Remove node_access check from content revisions view

Question: For the 'content' Views one can simply check tickbox 'Disable access checks' in UI under Advanced => Query, and the View returns all the records regardless of the node_access check.
However, in the 'content revisions' Views this tickbox is not available.
How can I make 'content revisions' Views to bypass the access_check?
Answer: In the hook_views_query_alter is possible to alter the query tags. Unfortunately, the method tag_remove is not present, but the $tags variable is public, which allows us to do:
function yourmodule_views_query_alter(&$view, &$query) {

    // Disable Node Access check for myview
    if ($view->name == 'myview') {
        $view->query->tags = [];
    }
}

I hope this will help somebody who needs unrestricted Views (e.g. for Services).


Powershell - how to run a script located on another computer?

Question: Could anyone please offer me some hints? I am stuck with this problem.
I have developed a PowerShell script located in:
<code>\\\ComputerNameA.xxx.xxx.local\d\xxx\script.ps1
</code>
This script requires 4 arguments to work. I need to run that script from another computer.
I have tried:
<code>Invoke-Command -ComputerName ComputerNameA
      -FilePath \\\ComputerNameA.xxx.xxx.local\d\xxx\script.ps1
      -ArgumentList {-arg0 string -arg1 string -arg2 string -arg3 string}
</code>
Any hints will be appreciated.
Update:
As to answer my original question, I think the answer is:
Invoke-Command -ComputerName ComputerNameA -Credential $cred
-FilePath \\ComputerNameA.xxx.xxx.local\d\xxx\script.ps1
-ArgumentList {-arg0 string -arg1 string -arg2 string -arg3 string}
Now, the new problem is I got the access denied error even the credential is exist (i.e. I setup a new user account - abcd and set the password as abcd)
Comment: What's the error when you ran the script from another system
Comment: Thank you Jawad. I fixed the previous problem. I need to use " " for a folder name which contains a space. The new error message is: connecting to remote server ComputerNameA failed with the following error message: access is denied.
Comment: Your invoke command needs credentials to access the other computer. You either need domain level access to run it, or use pssession to set credentials and then use them. or you can set them in the command with username parameter. https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/invoke-command?view=powershell-7
Comment: Thank you Robert. I setup a new user account in ComputerNameA, make the user be member of "Users" and "PS Job Users". And also use -credential in invoke-command, but still failed with: AccessDenied, PSSessionStateBroken
Answer: If you try to execute a PS1 script located on a remote computer as if you do it physically on the computer itself, then you can achieve this via Remote Powershell.
https://4sysops.com/archives/use-powershell-invoke-command-to-run-scripts-on-remote-computers/
Obviously, it implies that the script will do things (i.e read/write operations) on the remote computer instead of yours.
Also, remote connection (in the BIOS settings ?) must be allowed on the remote computer.
Answer: You can try installing ssh server where the scripts is located then connect using putty for windows
then execute refer to this
Comment: Thank you Bevin NIno. ComputerNameA is actually a server I am not allow to install anything. Even SSH is available in ComupterNameA, I think I cannot use SSH because that will require supply of user name and password in the script.
Comment: if you dont want to include username and pass use certificate
Comment: Thank you Bevin NIno. I ended up trying to use -credential


Erro android.database.sqlite.SQLiteException: no such table: fs_promocoes

Question: public class PromocaoDAO  {

private static final String DATABASE_NAME = "app_promocoes.db";
private static final int VERSAO_BANCO = 2;

private static final String TABLE_PROMOCOES = "fs_promocoes";

public static final String PROMO_ID = "id";
public static final String PROMO_DESCRICAO = "descricao";
public static final String PROMO_STATUS = "status";
public static final String PROMO_INICIO = "inicio";
public static final String PROMO_TERMINO = "termino";

private DatabaseHelper dbHelper;
private SQLiteDatabase db;

private final Context mCtx;

private static final String TABELA_PROMO =
        "CREATE TABLE if not exists " + TABLE_PROMOCOES + " (" +
                PROMO_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                PROMO_DESCRICAO + "," +
                PROMO_INICIO + "," +
                PROMO_TERMINO + "," +
                PROMO_STATUS + "," +
                " UNIQUE (" + PROMO_ID +"));";

private static class DatabaseHelper extends SQLiteOpenHelper {

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, VERSAO_BANCO);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABELA_PROMO);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_PROMOCOES);
        onCreate(db);
    }
}

public PromocaoDAO(Context ctx){
    this.mCtx = ctx;
}

public PromocaoDAO open() throws SQLException{
    dbHelper = new DatabaseHelper(mCtx);
    db = dbHelper.getWritableDatabase();
    return this;
}

public void close(){
    if(dbHelper != null){
        dbHelper.close();
    }
}

public long inserirPromocao(String descricapo, String inicio, String termino){

    ContentValues values = new ContentValues();
    values.put(PROMO_DESCRICAO, descricapo);
    values.put(PROMO_INICIO, inicio);
    values.put(PROMO_TERMINO, termino);
    values.put(PROMO_STATUS, 1);

    return db.insert(TABLE_PROMOCOES, null, values);
}

public Cursor buscarTodasPromocoes(){

    Cursor mCursor;
    mCursor = db.query(TABLE_PROMOCOES, new String[] {PROMO_DESCRICAO, PROMO_INICIO, PROMO_TERMINO},null,null,null,null,null);
    if (mCursor != null){
        mCursor.moveToFirst();
    }
    return mCursor;
}

public void testeInsertPromocao(){
    inserirPromocao("PROMOCAO DE NATAL", "10/11/2016", "31/12/2016");
    inserirPromocao("PROMOCAO DE PESCOA", "10/11/2016", "31/12/2016");
}

Answer: Isso acontece porque você adicionou uma nova tabela sem mudar a versão do banco.
Você pode desinstalar a aplicação e rodar de novo pra resolver ou somente mudar a versão do banco.
Mas como seu projeto deve estar em desenvolvimento ainda é aconselhável que você desinstale antes de rodar de novo,
Comment: Então Leonardo, eu já fiz isso. Mas continua apresentando o mesmo problema.
Comment: Você desinstalou a aplicação do device e rodou novamente?
Comment: Exato. Fiz isso e mudei a versão do banco também.
Answer: Para evitar que sempre caia no onUpgrade, faça um teste, inserindo uma condição que ocorra apenas se você fizer a troca da versão do Database (VERSAO_BANCO):
    @Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
    if (oldVersion < newVersion){
        String sql = "DROP TABLE IF EXISTS " + TABLE_PROMOCOES;
        database.execSQL(sql);
        onCreate(database);
    }
}


Perrin numbers in terms of the generalized hypergeometric function?

Question: Given the roots of $x^3=x^2+1$, we have sequence A001609,
$M(n) = x_1^n+x_2^n+x_3^n = \,_3F_2\left(\frac{-n}{3}, \frac{1-n}{3}, \frac{2-n}{3};\; \frac{1-n}{2}, \frac{2-n}{2};\; -\frac{3^3}{2^2}\right) = 1, 1, 4, 5, 6, 10, 15, 21,\dots$
for $n = {1,2,3,\dots}$
Question: Given $y^3=y+1$, is there any similar generalized hypergeometric formula for the Perrin numbers?
$P(n) = y_1^n+y_2^n+y_3^n = 0,2,3,2,5,5,7,10,\dots$
The closest I found is the binomial sum,
$ \begin{aligned}P(n) &= n\sum_{k=1}^{n/2} \frac{\binom k{n-2k}}{k} = 0,2,3,2,5,5,7,10,\dots\end{aligned}$
where both start with $n = 1,2,3,\dots$ Anyone knows how to translate that into the generalized hypergeometric function?
Comment: The Wikipedia article (https://en.wikipedia.org/wiki/Perrin_number) notes that P(n) can be computed in log(n) multiplies.
Answer: A solution for calculating P(n) when n is prime using the hypergeometric function can be found at Perrin088.org (Chapter 15)

This equation is derived from an incomplete beta function giving the nth term of the Perrin sequence when n is prime.
Comment: How come google can't find Perrino88.org?
Comment: The site is Perrin088.org


Why find_element_by_xpath() taking 3 positional argument?

Question: *args unpacks the locators in tuple form.but is my case i have given only two arguments,but it is taking three arguments.Need help to understand.
I am newbie to selenium with python and played around some code from github,
but getting error.
TypeError: find_element_by_xpath() takes 2 positional arguments but 3 were given
locator.py
from selenium.webdriver.common.by import By
class elements(object):
      Customer = (By.XPATH, "//button[contains(text(),'Customer')]")

base.py
from selenium import webdriver
from selenium.webdriver.common.by import By

class Page(object):
    def __init__(self,driver,url=None):
        self.url = url
        self.driver = driver

    def find_element_with_click(self,*locator):
        self.driver.find_element_by_xpath(*locator).click()

pages.py
from selenium import webdriver
from base import Page
from locator import *

class CustomerCreation(Page):
    def __init__(self, driver):
        self.locator = elements
        super().__init__(driver)

    def create_customer(self):
        self.driver.find_element_with_click(*self.locator.Customer)

testPages.py
import unittest
from selenium import webdriver
from pages import *
from locators import *
from selenium.webdriver.common.by import By

class TestPages(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.driver = webdriver.Chrome('C:\ChromeDriver\chromedriver')
        cls.driver.get("#server")

    def test_tes_cust(self):
        page = CustomerCreation(self.driver)
        res_page = page.create_customer()          #Getting issue at this stage

    @classmethod
    def tearDownClass(cls):
        cls.driver.close()

if __name__ == "__main__":
    suite = unittest.TestLoader().loadTestsFromTestCase(TestPages)
    unittest.TextTestRunner(verbosity=2).run(suite)

The error log:

test_tes_cust (main.TestPages) ... ERROR
    ======================================================================
      ERROR: test_tes_cust (main.TestPages)
      ----------------------------------------------------------------------
      Traceback (most recent call last):
          File "testPages.py", line 28, in test_tes_cust
              res_page = page.create_customer()
          File "C:\Users###\PycharmProjects\basics\pages.py", line 35, in create_customer
              self.find_element_with_click(*self.locator.Customer)
          File "C:\Users###\PycharmProjects\basics\base.py", line 21, in find_element_with_click
              self.driver.find_element_by_xpath(*locator).click()
      TypeError: find_element_by_xpath() takes 2 positional arguments but 3 were given
Answer: You're passing one extra argument. Your arguments are:

self
By.XPATH
"//button[contains(text(),'Customer')]"

That's what you need to pass to find_element method. While find_element_by_xpath should take two arguments only:

self
"//button[contains(text(),'Customer')]"

So try to update your code as
def find_element_with_click(self,*locator):
    self.driver.find_element(*locator).click()

or you need to modify your Customer as:
Customer = "//button[contains(text(),'Customer')]"

and
def find_element_with_click(self, xpath):
    self.driver.find_element_by_xpath(xpath).click()


How to start bass-guitar plucking?

Question: I am looking for an online beginner tutorial to bass plucking (fingered) technique, something like the image bellow.
Important: I am not looking to learn how to play the notes etc., I would say I don't want to learn to PLAY the bass, but rather just the technique to be able to pluck rythms with my right hand fingers - no left hand.
Comment: I'm dyslexic so I prefer to view videos rather than read instructions. I found the answer to this at http://www.itsabass.com/slap_bass.html
Answer: Index (1) Middle (2) Ring (3)
You should use at least two fingers.
When using two fingers it is very important to alternate the fingers. 1 2 1 2 1 2. Practice slowly and make sure they are alternating. Not alternating your fingers over tires one and slows your playing. It can become a tough habit to break
If you want to use three fingers the method is 1 2 3 2 then repeat.
Really you only need to use two unless you are playing some insanely fast stuff.
You can use your thumb as you'd like for a different sound or style. The main time thumb is used is on double stops. A double stop is when you play two strings at once. So you may play the E string with your thumb while you play say the A string with your index.
Comment: That's exactly what I was looking for. Thank you. If you have an additional guide (fingered) for different rythms (no notes) I would appreciate that a lot.
Comment: Also what's the recommended fingering for triplets?
Comment: For triplets you would still alternate 1 2 1 2 1 2
Answer: The easiest way to start is similar to the picture above...put your thumb on the pickup and use your first finger.  This is the most basic method.  Relax - don't tense up.  put the tip of your thumb on the upper edge of the pickup and start by just plucking the E string ( the one closest to you ) over and over again - try it to the tempo of Queen's "Another one Bites the Dust" ... instant bass player!
Once you've mastered this just move on to the next string - keep your thumb on the pickup for now.
Take breaks - it's a physical instrument.
Then when you're feeling comfortable with this you can switch to alternate fingering: using your first and second finger alternating back and forth. Again try this one string at a time - You can start at the same tempo as before or a bit faster.
Again practice on each string and there you have it - you're ready for your first 4 note gig
Comment: so is there an oficcial method/pattern/guidance for when to use what finger? Will you ever use your thumb for plucking too? What about the 3rd (and 4th)) fingers, do they participate in the plucking as well?
Comment: There is no official method...the most common is the 1st, 2nd finder combo.  But there are people that use mostly one finger ( James Jamerson ) or people who use all 4 ( Alain Caron ) ... using the thumb is not very typical for all styles of music but it can pretty useful along with a palm mute for a very deadened "thump, thump, thump" sound.
Answer: Most of the time, you only need to use your forefinger and middlefinger - for the simplest phrases, even just one of them can suffice.
One of the ways to get a clean sound is to have your finger pluck the string, then keep going and land on the next string. For example, if you play an open G, have the finger land on the D string. This will help keep your finger in a consistent range (giving you a point of reference, which is always good), and will also mute the adjacent string, making it harder to have funny sounds coming from those strings. I usually keep my thumb anchored on the low E string, but on the top of the pickup (as in the picture) is equally valid. When I have my thumb anchored on the low E and want to play on that string, I move it to the top of the pickup. I find that easier, because I like the angle that it puts my wrist at.
If you play with two fingers, it's imperative to practice alternating between them. Otherwise, you're losing the speed that you can get from using two fingers.
For triplets - I like playing 3-2-1 (ring-middle-index).

How to start bass-guitar plucking?


sf::String member of class reverts to blank

Question: These lines of code are run:
Enemy* enemy = new Enemy(m_pSceneManager,"enemy"+ss.str());
std::cout << "Enemy name = " << std::string(enemy->name) << std::endl;
Add(enemy->name,enemy);

in EnemyManager.cpp. EnemyManager inherits from GameObjectManager:
void GameObjectManager::Add(sf::String name,VisibleGameObject* obj){
    std::cout << "GameObjectManager obj name = " << std::string(obj->name) << std::endl;
    gameObjects.insert(std::pair<sf::String,VisibleGameObject*>(name,obj));
}

Enemy inherits from VisibleGameObject, which both have a public sf::String 'name' variable but only Enemy initializes it at any point (in its constructor). The output in the console window is this:
Enemy name = enemy0
GameObjectManager obj name =

Why does the name revert to nothing? I'm assuming it's something to do with the fact that the argument is a VisibleGameObject* and not an Enemy* - if it is, how can I work around this? If I've made a mistake somewhere else, please tell me if there are any details I am missing that are required.
Thanks
Answer: If I understand your description correctly, your code looks like this:
struct VisibleGameObject {
    sf::String name;
};

struct Enemy : VisibleGameObject {
    Enemy(SceneManager*, sf::String newName) : VisibleGameObject(), name(newName)
    sf::String name;
};

struct GameObjectManager {
    void GameObjectManager::Add(sf::String name,VisibleGameObject* obj){
        std::cout << "GameObjectManager obj name = " << std::string(obj->name) << std::endl;
        gameObjects.insert(std::pair<sf::String,VisibleGameObject*>(name,obj));
    }
private:
    std::map<sf::String, VisibleGameObject*> gameObjects;
};

struct EnemyManager : GameObjectManager {
    void foo() {
        //This code probably leads to a memory leak, but you might have solved it in some
        //way that you are not showing.
        Enemy* enemy = new Enemy(m_pSceneManager,"enemy"+ss.str());
        std::cout << "Enemy name = " << std::string(enemy->name) << std::endl;
        Add(enemy->name,enemy);
    }
};

What this means is - when the Enemy object is constructed, the Enemy::name variable is initialised to hold "enemy"+ss.str(). However, the VisibleGameObject::name variable (which is in the VisibleGameObject part of the Enemy) is initialised to hold its default value (in which it holds no text).
In EnemyManager::foo, the name variable that is referenced is the one in Enemy. In GameObjectManager::Add, the name variable that is referenced is the one in the VisibleGameObject base member of Enemy.  VisibleGameObject::name still has its default value, and so nothing gets printed.
Answer: Since, as you say both have a public sf::String 'name' variable but only Enemy initializes it at any point (in its constructor). , there are two name subojects: one is a member of Enemy and another is a subobject of VisibleGameObject. Inside function Add you explicitly refer to the latter one, so that is what you get, and it is not initialised.
You probably want to make name a virtual function returning string; this will make function Add to employ runtime polymorphism and call name() from derived class, i.e. from Enemy.
Simpler (but not necessarily better) design would be to make name protected or public member of VisibleGameObject and let Enemy set it; that also means you will most likely want to remove name from Enemy, otherwise name inherited from VisibleGameObject will be hidden.
Comment: thanks, I was under the impression that making something with the same name would overwrite it (I tried 'virtual name' before).


JQuery Live Binding Multiple Radio Buttons or Radio Button Lists

Question: I am trying to eliminate some redundancy, but I appear to be missing something that is probably obvious...
this does not work...
    $('input[type="radio"][name="rdoQuestionAnswer"][name="rdoQuestionAnswerYes"][name="rdoQuestionAnswerNo"]').live({
    click: function (e) {
...
           }
        });

this does...
    $('input[type="radio"][name="rdoQuestionAnswer"]').live({
    click: function (e) {
...
           }
        });

I don't want to have to create one of these for every radio button or radio button list...
comments, suggestions?
thanks in advance.
Answer: I would add a class (with no accompanying styles) to each of those radio buttons and select that instead:
<input type="radio" class="selectme" name="rdoQuestionAnswer"/>
<input type="radio" class="selectme" name="rdoQuestionAnswerYes"/>
<input type="radio" class="selectme" name="rdoQuestionAnswerNo"/>

jQuery:
$('input.selectme').live('click', function() {...});
// or, to be modern about it:
$(document).on('click', 'input.selectme', function() {...});

Comment: This is definitely the best method. I would +1 but I've hit the daily limit :)
Comment: Started writing that I love the intro to the live() method then realized why I'd never heard of it, it's deprecated in 1.7+. That said the ".on()" is a perfect drop in replacement and I can exclude the selectors which are handled in the parent element, and stick to just the event type and handler. Love it! Thanks.
Comment: The O.P. may have been extremely intentional with his HTML, but, I would like to point out one thing: If you're dealing with mutually exclusive radio button/options, they should all have the same 'name' attribute to begin with, which negates the need to add a class. But, of course.. maybe you have a situation where you're dealing with radio buttons across various groups and this answer would indeed apply.
Answer: Change your selectors, so that they are separated by a comma:
$('input[type="radio"][name="rdoQuestionAnswer"], input[type="radio"][name="rdoQuestionAnswerYes"], input[type="radio"][name="rdoQuestionAnswerNo"]')

On a side note: Are you sure you have to specify type=radio?
Comment: No it does not work without type=WhatEverTypeItIs (i tried with and without it and I am using the latest version of jquery) other than that this approach works... thanks


PHP calculate difference between two dates WITHOUT year

Question: I generally use this method to calculate difference between two dates:
$datediff = strtotime($enddate) - strtotime($startdate);
$totalDays = floor($datediff/(60*60*24));

But now I got a problem. Now I should not consider the year in the calculation. Which means for example the difference between two dates January 2 2014 and January 6 2015 should give me result as 4 days.
For that I changed the date format to m-d, and used the below method:
$startdate = date('m-d',strtotime($startdate));
$enddate = date('m-d',strtotime($enddate));
$datediff = $enddate - $startdate;
$totalDays = floor($datediff/(60*60*24));

But I get the result as 0. Can anyone help me? What is the mistake I am doing?
Comment: Have you considered leap years?
Comment: so many bad solutions :( use the php date time object only pass in m-d part of date and use the date diff function there
Answer: You can replace the year with 1970 and do the calculations against that.
$date1 = '2014-01-17 04:05:54';
$date2 = '2013-01-12 02:07:54';

$date1 = preg_replace('/([\d]{4})/', '1970', $date1);
$date2 = preg_replace('/([\d]{4})/', '1970', $date2);

$timestamp1 = strtotime($date1);
$timestamp2 = strtotime($date2);

$date_diff = gmdate('d H:i:s', abs($timestamp2-$timestamp1));

var_dump($date_diff);

Comment: I would use 1972 so that we can test against leap years too :)
Answer: Please try this :
$startdate = 'January 1 2014';
$enddate =  'February 6 2015';
$startdate = date('d-m-1970',strtotime($startdate));
$enddate = date('d-m-1970',strtotime($enddate));
$datediff = strtotime($enddate) - strtotime($startdate);
$totalDays = floor($datediff/(60*60*24));
echo $totalDays;

Hope this will help
Answer: here is the php DateTime solution
$date1 = new DateTime('2015-01-02');
$date2 = new DateTime('2014-01-06');

switch (true) {
    case ($date1 < $date2) :
        $date2->setDate($date1->format('Y'), $date2->format('m'), $date2->format('d'));
        break;

    case ($date2 < $date1) :
        $date1->setDate($date2->format('Y'), $date1->format('m'), $date1->format('d'));
        break;
}

$interval = $date1->diff($date2);
echo $interval->format('%R%a days'); // +4 days

have fun!
Or just cut off the year and leave away the switch part.
Answer: Just take the "m-d" part of your date and append any year onto the end of it, e.g. "-2014".  The datediff() will then give you the required answer.


What do we do with questions that ask for resources (tutorials, documentation)?

Question: With the public release of Magento 2, questions like this come up more often again:
Suggest me Magento2 Theme development best tutorial

asking for external resources
answers are likely to be "link only"
answers still tend to be useful for a larger audience

On StackOverflow these would immediately be closed as off topic because:

Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.

We don't have this close reason here, so I'd like to gather some opinions about what to do with these questions. Some options:

close as off topic
convert to community wiki
leave them as they are
move links from answers to a related tag wiki
Answer: Fabian,in my mind there are two options

Convert to Community wiki
leave them as they are

If we make it close as off topic that becomes confusion for users as it already  magento related and basic question for a developer.As MSE is great platform for Magento resource,so any one of developer can give answer in links or  multiple answer.Also i have seen some answers of Ben Lessani - Sonassi in long format and those are very use full
Also my point of view leave them as they are,may be in future any user can be  interest to answer this question in brief and long.
So we can use  leave them as they are
Answer: We have this for two or three other questions, where we created a very good, wide and detailed answer, and then closed new questions about this as duplicated
Answer: I would not encourage to support theme or tutorial requests.

Theme requests
Answers to these requests probably only contain links to other resources containing the themes. These links will break in the future making the answer worthless.
Also these kind of questions will come in thousands of variants without them being actual duplicates: "Where can I find a Magento2 red / blue / purple / dark / light / flat / newspaper style theme?" and so on...
Referring to a big community wiki Q&A about it would have my preference.
Tutorial requests
Why does one need a tutorial? Probably there is an underlying problem. So the actual question is not for the tutorial, but how to do something: "Where can I find a tutorial for X?" comes from the OP's original problem "How can I do X?". So the actual question should be just that.
Also again, answers to these requests probably only contain links to other resources containing the actual examples and explanation. These links could break in the future making the answer worthless.
On SE link only answers are not encouraged.


sSMTP on Ubuntu: "ssmtp: Cannot open smtp.gmail.com:587"

Question: I have configured sSMTP on Ubuntu and it worked fine yesterday. But today when I am trying to send email it shows "ssmtp: Cannot open smtp.gmail.com:587" error message.
<code>$ apt-get install ssmtp

$ vi /etc/ssmtp/ssmtp.conf
firstname.lastname@example.com
mailhub=smtp.gmail.com:587
rewriteDomain=
hostname=mycomputerName
UseTLS=YES
UseSTARTTLS=YES
AuthMethod=LOGIN
email@example.com
AuthPass=sender.email.password
FromLineOverride=YES

$ chmod 640 /etc/ssmtp/ssmtp.conf

$ ssmtp email@example.com
Hi
Ctrl+D
ssmtp: Cannot open smtp.gmail.com:587
</code>
Additional info: Yesterday I used public IP, today I am using private IP. I think it is not any problem.
Comment: Your machine can't connect to smtp.gmail.com on port 587, so something must be blocking it. Check any firewalls on the machine or between the machine and the Internet.
Answer: I had the same problem (in my raspberry), but things changed from one day to another. I mean my ssmtp work fine for months and one day it stopped with the same error of your. I don't know why and what is the cause but after some attempts I added the AuthMethod in my ssmtp.conf and it worked.
Now the file look like this:
<code>firstname.lastname@example.com
mailhub=smtp.gmail.com:587
rewriteDomain=gmail.com
hostname=YourComputerHostName
UseTLS=YES
UseSTARTTLS=YES
email@example.com
AuthPass=passwordofmyaccount
AuthMethod=LOGIN
FromLineOverride=YES
</code>
Try copy and paste changing your email, password and raspberry name.
Hope it work


O que realmente é Copyright?

Question: Eu uso a licença MIT e ela tem este formato conforme o exemplo em https://opensource.org/licenses/MIT:
<code>The MIT License (MIT)
Copyright (c) <year> <copyright holders>

Permission is ...
</code>
Também vejo muitos sites adicionando o texto "Copyright" no rodapé, no entanto já ouvi dizer que na verdade esses sites não tem o "copyright", as pessoas colocam isso no rodapé por simplesmente colocar.
Então o que eu gostaria de entender é que digamos que os dados no site não tenham um "licença definida", o copyright no rodapé é quase um erro?
Ou copyright é um termo que eu posso "dizer" quais os direitos de cópia sobre o conteudo ou código?
O que realmente este termo significa?
Comment: "Cópia Certa" ou "Cópia na Certa", rsrsrs. Brincadeira
Comment: Peço que se achou alguma resposta útil aceite uma das respostas.
Answer: Legalmente vc tem todos os direitos a respeito de qualquer coisa que vc crie. Então se vc cria um software (ou um livro, ou uma tela, ou qq coisa) ele é automaticamente protegido pela lei e ninguém pode dispor daquele software pra nada a não ser vc mesmo.
Entretanto, algumas pessoas não sabendo disso, acham que podem pegar qualquer código (imagem, livro, etc) na internet e sair usando, por isso alguns autores acham bom colocar o símbolo de copyright associado à obra, lembrando que aquilo tem dono.
Outros entretanto não fazem questão de seus direitos, então colocam licenças (livres ou não) como a creative-commons abrindo mão de alguns de seus direitos automaticamente.
Lembrando que independente de vc colocar um símbolo de copyright, se alguém infringir esses direitos, vc é que terá que provar que o outro infringiu ("ao acusador cabe o ônus da prova"). Por isso alguns autores quando lançam uma obra publicam em algum grande portal ou de alguma outra forma para terem uma prova que aquilo foi criado por eles primeiro.
Há ainda a possibilidade de registro de obra que confere uma formalidade extra ao ato.
Alguns links úteis:
Copyright: https://pt.wikipedia.org/wiki/Direito_autoral
Licença: https://pt.wikipedia.org/wiki/Licen%C3%A7a
Copyleft: https://pt.wikipedia.org/wiki/Copyleft
Creative Commons: https://br.creativecommons.org/
Licenças GNU: http://www.gnu.org/licenses/licenses.pt-br.html
Answer: Um website, assim como um livro, um logotipo ou uma revista, é facilmente copiado, sendo fundamental o registro para que sua autoria e propriedade seja respeitada.
O código do website pode ser protegido contratualmente, segundo Dr. Wilson Canesin, advogado, um dos diretores da Jonel Contabilidade,  "O contrato de escrow garante que empresas que adquiriram a licença para utilizar um software possam acessar seu código fonte, sem que haja quebra de copyright".
O conteúdo pode ser protegido, idéias e pensamentos não têm direito a copyright, mas criações aplicadas em meios tangíveis sim, tais como, fotografias, textos, projeto-gráfico do site, para isso deve-se fazer o registro de propriedade.
Assim sendo, geralmente, em blogs, o copyright pode ser direto do provedor como por exemplo o "Blogger", eles tem direitos sobre o conteúdo expresso no site.
Porém, se você não tiver nenhum registro e ainda assim colocar o Copyright, não vai valer para quase nada, a menos que você consiga provar que é o autor dessas publicações.
Fonte: http://www.significados.com.br/copyright/

O que realmente é Copyright?