How do I change permissions and ownership after git-pull, to match folder?

Question: The company I work for is using Git for deployment and because of this it overwrites specific permissions and ownerships. What is the best way to make sure that the folder ownerships and permissions are preserved when a git pull is conducted?
I do development on OS X, using MAMP, push to a staging server which is a clone of the environment on production. When it reaches Staging I have to correct the permissions afterward but they are usually set to 664 instead of 644, causing issues with suPHP.
Answer: Can you use one of the git hooks?

http://git-scm.com/book/en/Customizing-Git-Git-Hooks

Probably the post-checkout hook.
Comment: This isn't an answer, it is another question. Not helpful. Don't know why it was accepted. If it does work, then this questionable answer should be updated with an actual answer. Pretty please.
Comment: Would that work with git-pull?
Comment: @geoidesic I added the final result in the below answer. It's been a while since I did this so forgive me if I am forgetting anything.
Answer: The answer ended up being that I had to use the post-merge hook, after reading through the link that was provided by the other answer.
In the .git/hooks folder I created a file called post-merge and included the something like the following code:
#!/bin/sh
sudo chown -R opensaurusrex:staff .
sudo chmod 2775 .
sudo find . -type d -exec chmod 2775 {} \;
sudo find . -type f -exec chmod 0664 {} \;

I don't remember if I had to run it in a specific way to make sure that sudo worked properly. It should work if you replace #!/bin/sh with the current #!/bin/zsh for modern MacOSX distributions where they are using zsh instead.


Comparação de valor dentro de data frame

Question: Olá, tenho um banco de dados, com cerca de 50000 observação, da seguinte forma, valores apenas figurativos:
nome<-c("joão","pedro", "joãoo")
identificador<-c(123456,124578,123456)
valor<-c(2145,350,23)
dados=data.frame(nome,identificador,valor)

gostaria de identificar indivíduos com o mesmo identificador e criar uma nova variável da seguinte forma:
nome=c("joão","pedro", "joãoo","maria","mariaa","carla","felipe","vitor","pedro","vitorr")
identificador=c(123456,124578,123456,000,000,123,156,2222,3232,2222)
valor=c(2145,350,23,32,12,32,1,2,54,4)'
validor=c(1,0,1,2,2,0,0,3,0,3)
dados=data.frame(nome,identificador,valor,validor)

fiz dessa forma para identificar os identificadores iguais, mas n conseguir fazer essa variável.
x<-dados$identificador
length(x)
i=1
k=1
validor=0
validor[1:50000]=0
for(i in 1:50000){
  for(j  in 1:50000){
    if(x[j]==x[i] & i!= j ){
      validor[j]=k
    }
  }
}

gostaria de criar uma função que produzisse a variável validor da forma que foi mostrada.
Espero ter sido claro, e desde já agradeço muito a ajuda.
Comment: Onde está `dados`? Acho que você deveria ter passado o *dataframe* para a variável dados: `dados = data.frame(...` - o igual funcional como o `<-`, só que é um caractere a menos, por isso gosto de usar. Qual o resultado que você espera?
Comment: editei, gostaria de criar a variável "validor" identificando os pares,ou conjunto, de identificador com um algorismos
Comment: Você pode explicar como esta sequencia é formada? `validor = c(1, 0, 1, 2, 2, 0, 0, 3, 0, 3)`. Ao que me parece você criou um vetor com a ordem em que os números se repetem. E.g.: **123456** é o primeiro a repetir, **000** é o segundo a repetir e, por último, **2222** é o terceiro a repetir, portanto, equivalem a 1, 2 e 3, respectivamente. Os outros não repetem, por isso, recebem 0.
Comment: exatamente isso
Answer: Acho que isso é muito próximo do que você quer. A diferença é que os identificadores iguais não estarão nessa ordem:1,2,3...
library(uniqueAtomMat)
library(tuple)
identificador<-c(123456,124578,123456,000,000,123,156,2222,3232,2222)
validor<-grpDuplicated(identificador) # agrupa idenficadores iguais dentro de uma mesma categoria
validor[match(orphan(validor),validor)]<-0  #Atribui zero aos identificaores órfãos.


index match second value

Question: Okay so, i've created a spreadsheet to learn and develop the things i need.
i've done so much, then got stuck.
i have a value i'm trying to index match, the first works, but i can't get the second value no matter what i do.
the first cell contains this formula:
<code>=IF(ISERROR(INDEX(A2:R4,SMALL(IF(A2:A4=A11,ROW(A2:A4)),ROW(1:1)),11)),"NOPE",INDEX(A2:R4,SMALL(IF(A2:A4=A11,ROW(A2:A4)),ROW(1:1)),11))
</code>
with ctlr shift enter to create the array.
the second contains:
<code>=IF(ISERROR(INDEX(A2:R4,SMALL(IF(A2:A4=A11,ROW(A2:A4)),ROW(2:2)),11)),"NOPE",INDEX(A2:R4,SMALL(IF(A2:A4=A11,ROW(A2:A4)),ROW(2:2)),11))
</code>
I HAVE DUPLICATE VALUES I'VE CHECKED 1000 TIMES.
I've only posted here once before and i got told to google etc, and i have done that till my fingers hurt but i can't get this to work.
any suggestions
the second should show the 2nd result row(2:2) but i get an N/A result, or NOPE as in my formula. so i have two duplicate values and i want the results from column number 11. the first formula provides the first result, i'm trying to obtain the second. they are close to identical, with the exception of the row (the two formulas that is). i'm still new so i apologise if this doesn't make to much sense, googled most of my excel and sql life.
Comment: I don't understand the question. The two expressions are identical, are they not? Is that the problem or did you mean them to be different?
Comment: the second should show the 2nd result row(2:2) but i get an N/A result, or NOPE as in my formula. so i have two duplicate values and i want the results from column number 11. the first formula provides the first result, i'm trying to obtain the second. they are close to identical, with the exception of the row (the two formulas that is). i'm still new so i apologise if this doesn't make to much sense, googled most of my excel and sql life.
Comment: just figured out to comment to you rather than edit, my apologies
Answer: =IF(ISERROR(INDEX(A2:R4,SMALL(IF(A2:A4=A11,ROW(A2:A4)),ROW(2:2))-1,11)),"NOPE",INDEX(A2:R4,SMALL(IF(A2:A4=A11,ROW(A2:A4)),ROW(2:2))-1,11))
I figured it out, hours and hours, probably due to league of legends and vodka interrupting.  the above worked for me. thank the heavens.
I hope this might help others also.
Comment: it seems with the 2:2 I had to add the -1

index match second value


Populate Multiple Select Controls with the Same Values using jQuery

Question: I have two select controls that I want to populate with the exact same options.
I started with the following code (which does not work):
var result = // raw <option></option> html from ajax call

$("#selImbServiceType").html(result);
$("#selRemitImbServiceType").html(result);

If I comment out either of the statements above then the one left works, but when they are both uncommented only the first one works.
Then I changed the code to the following (this works as expected):
var result = // raw <option></option> html from ajax call

$("#selImbServiceType,#selRemitImbServiceType").html(result);

The second version populates both controls.
I am using jQuery 1.4.4 with Firefox 5.0.1
Any idea why the first version does not work?
result variable HTML
Here is the contents of the result variable:
<option value="27b3dc65-d60c-46e3-8d9c-bdffad8bc25f">Return To Sender</option>
<option value="bcf435c9-d197-4a54-8d90-f4507c2ac505">Shred And Return Electronically</option>

Surrounding HTML

    Client

    <select id="listClients" onchange="clientSelectionChanged()"></select>

    IMB Service Type

    <select id="selImbServiceType" name="imbServiceType"></select>

    Stream Name

    <input id="txtStreamName" type="text" maxlength="128" name="streamName" />

    Processor Module

    <input id="txtProcessorModule" type="text" maxlength="256" name="processorModule"/>

    Advanced Location Logic Enabled

    <select id="selAdvancedLocationLogicEnabled" name="advancedLocationLogicEnabled">
      <option value="1">Yes</option>
      <option value="0">No</option>
    </select>

    Force Mail Enabled

    <select id="selForceMailEnabled" name="forceMailEnabled">
      <option value="1">Yes</option>
      <option value="0">No</option>
    </select>

    File Stream Configuration

    <select id="selFileStreamConfig"></select>

    Remit IMB Service Type

    <select id="selRemitImbServiceType" name="remitImbServiceType"></select>

    NCOA Enabled

    <select id="selNcoaEnabled" name="ncoaEnabled">
      <option value="1">Yes</option>
      <option value="0">No</option>
    </select>

    Skip Logic Enabled

    <select id="selSkipLogicEnabled" name="skipLogicEnabled">
      <option value="1">Yes</option>
      <option value="0">No</option>
    </select>

    Active

    <select id="selActive" name="active">
      <option value="1">Yes</option>
      <option value="0">No</option>
    </select>

Comment: We could do with seeing your HTML as well as your jQuery. [Your code works fine for me in this jsFiddle I created](http://jsfiddle.net/gothick/Lfb6A/1/), by the way.
Comment: Even with your provided HTML, it still works. http://jsfiddle.net/r6C2p/
Comment: Are you meant to be missing the period before the `html` in the second line?
Comment: Oops, no that was a typo in the question.
Comment: Ideally, you should use [`$.append()`](http://api.jquery.com/append/). BTW are you sure result does not contain any broken html?
Comment: @Dana Your actual data [works fine for me](http://jsfiddle.net/gothick/Lfb6A/4/), too. You didn't try to hardcode the data (which has double quotes) as a string wrapped with double quotes, for testing in my example, did you? Because no, that won't work. But it seems unlikely to be your actual problem in the real code.
Comment: @Matt Gibson: Yes, I spoke too soon about the jsFiddle, I had a mismatched quote in there at first when it didn't work.
Comment: It's possible it's an issue with the HTML of your page. Can you provide enough of the page source to show the two `select` elements with some context, please?
Comment: @Matt: Sure, I updated the question with the surrounding HTML.
Comment: I just double checked it for about the fifth time, and it definitely does not work on my development machine. All the code/html is exactly the same as above. I may just have to chalk this one up to gremlins. :)
Comment: I hard coded the result variable HTML in my page, and it does work. The HTML for the result variable in the question is a copy and paste from the AJAX call though. Must be some glitch somewhere. I don't have time to debug further since the second method is working. I'll try to come back and update the question when I have more time. Thanks everyone for taking the time to offer your advice.
Comment: Oh yes, I almost forgot. I want to give a quick shoutout to the anonymous downvoter.
Answer: Well, I would maybe try to update your jQuery version.
See this example
I'm using jQuery 1.5 and it's working
EDIT: weird, it works with 1.4.4, too
I'd try to look on ajax result, if it's exactly same and you could also try to hardcore your ajax result
Comment: @karim79: `try to hardcore` - I see hardcore, am I missing something?


Is there a way to find $x^n$ by using $(x-1)^n$?

Question: Basically I was playing a game which the inventory items went up to 64 in the same stack and accidentally removed 15 (8+7) of those items(49) (i know it was kinda stupid how i found this fomula).
Long story short: I found this formula that helps me find the next or the last square giving one of the squares in consideration (works in any square):
(x+1)^2 = x^2 + 2x + 1  - square above
(x-1)^2 = x^2 - 2x + 1  - square below
So i was thinking, is there any kind of formula that would work in x^n in the same way?
if not, would there be some kind of formula for that would work the same in x^3?
Comment: Just expand the binomial formula.  You will get the Pascal's Triangle, which tells you how to go from $x^n$ to $(x\pm 1)^n$.
Comment: I'm not sure what you are asking here. Both your formulas are special cases of the binomial theorem: https://en.wikipedia.org/wiki/Binomial_theorem
Comment: So, you're given $a=(x-1)^n$ and want $b=x^n$, without knowing $x$ but knowing $n$?
Answer: You know that
$(x+1)^2 = x^2+2x+1$
So if you replace $x$ by $x-1$ and $x+1$ by $x$ you get
$x^2 = (x-1)^2 + 2(x-1) + 1$
The equivalent formulae for $x^3$ are
$(x+1)^3 = x^3 + 3x^2 + 3x + 1 \\x^3 = (x-1)^3 + 3(x-1)^2 + 3(x-1) +1$
For other powers of $n$ see the binomial theorem.
Comment: "(x+1)^3=x^3+3x^2+3x+1"
ah that was what i was missing in my x^3 one!
thank you, i was almost literally breaking my head over this.
Answer: Multiplying a polynomial by $x+1$ is the same as

increasing the degree of all terms (factor $x$),
adding back the polynomial (factor $1$).

Hence
$$(x+1)(x+1)=(x^2+x)+(x+1)=x^2+2x+1$$
$$(x+1)^2(x+1)=(x^3+2x^2+x)+(x^2+2x+1)=x^3+3x^2+3x+1$$
$$(x+1)^3(x+1)=(x^4+3x^3+3x+x)+(x^3+3x^2+3x+1)=x^4+4x^3+6x^2+4x+1$$
and so on.
The coefficients of these polynomials are known as the binomial coefficients, and they can be arranged to form Pascal's triangle. From the previous considerations, you understand that a coefficient is the sum of the two coefficients above it.


Creating a dynamic street panorama in info window (Google Maps Javascript API)

Question: I am trying to create a panorama street view to a google marker info window  that is currently selected. So far, I have the info window that appearing with the location title. However, I wish to show the panorama right below it. I am getting errors such as 'cannot read properties such as style of undefined'.
Below is the functionality I have so far:
var map;
var markers = [];

var ViewModel = function() {

  var self = this;

  //Pushes the array of location titles onto the DOM
  self.locationsArray = ko.observableArray(locations);

  //Zooms to location on the map of currently clicked location
  //Place refers to the current location selected in the DOM
  //Example place = locations[current # in array]
  self.goToLocation = function(place,status) {
    console.log('Lat='+place.location.lat+', Lng='+place.location.lng);
    var coordinates = [place.location.lat,place.location.lng];
    var latlng = new google.maps.LatLng(coordinates[0],coordinates[1]);
    map.panTo(latlng);
    map.setZoom(16);
  };

  self.zoomIn = function() {
    map.setZoom(map.zoom+1)
    if(map.zoom >= 20) {
      alert('Whataya doin, lookin for ants?');
      map.setZoom(map.zoom-6);
    }
  };

  self.zoomOut = function() {
    map.setZoom(map.zoom-1)
    if(map.zoom <= 10) {
      alert('Ay fugetaboutit.. you\'re way atta Brooklyn! Zoom in to see the gabagool.')
      map.setZoom(map.zoom+4);
    }
  };

  // http://knockoutjs.com/documentation/click-binding.html#note-1-passing-a-current-item-as-a-parameter-to-your-handler-function
  // click binding's callback method
  // write a string to the console (first goal)

  // filter funcionality

};

function initMap() {

  var self=this;

    var styles = [
      {
        featureType: 'water',
        stylers: [
          {color: '#000000'}
        ]
      },{
        featureType: 'administrative',
        elementType: 'labels.text.stroke',
        stylers: [
          {color: '#ffffff'},
          {weight: 6}
        ]
      }];
    //Below stores the map
    map = new google.maps.Map(document.getElementById('map'),{
      //Below sets the initial location of the map on the screen
      center: new google.maps.LatLng(40.6251388,-74.0282899),
      //{lat: 40.6301388,lng:-74.0282899},
      //Below sets the level of zoom (1 = farthest away possible)
      zoom: 14,
      styles: styles
    });

    //Storing the infoWindow constructor to recall dynamically
    //for each location array
    var infoWindow = new google.maps.InfoWindow();
    //var panorama = new google.maps.StreetViewPanorama();
      //map.setStreetView(panorama);

    //For every location, create a marker(with specified properties)
    for (var i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position : new google.maps.LatLng(locations[i].location),
        map : map,
        title : locations[i].title,
        animation : google.maps.Animation.DROP,
        icon : 'forkknife.png'
      });

      //Attach a click event to each marker displaying the infoWindow
      //It will zoom to level 16, set the content to the appropriate location
      //then open it
      google.maps.event.addListener(marker, 'click', (function(marker, i) {
          return function() {
            map.setZoom(16);
            infoWindow.setContent(locations[i].title+'
'/*+Pano to go here*/);
            infoWindow.open(map, marker);
          }
        })(marker, i));
    }

    // create markers objects, for example, here
    // viewModel.locations()[index].marker = marker
}

ko.applyBindings(new ViewModel());

Below is the data:
var locations = [
  {
    title: 'Nino\'s Pizza',
    location: {
      lat: 40.620057,
      lng: -74.032894
    }
  },
  {
    title: 'Shore Road Bike Path',
    location: {
      lat: 40.623089,
      lng: -74.040596
    }
  },
  {
    title: 'Paneantico Bakery',
    location: {
      lat: 40.619418,
      lng: -74.0322818
    }
  }]

And lastly the View
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Map Project - Thomas Grimes</title>
    <link href="styles.css" rel="stylesheet">
    <link href="bootstrap/css/bootstrap-grid.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Asap+Condensed" rel="stylesheet">

          Where to eat in . . .

               Bay Ridge

            <button type="button" style="background-color:black;color:white;width:50px;" data-bind="click:zoomIn">+</button>
            <button type="button" style="background-color:black;color:white;width:50px;" data-bind="click:zoomOut">-</button>

          <input type="text" id="title">
          <input type="text" id="lat">
          <input type="text" id="lng">
          <button type="button" name="button">Add location</button>

Comment: There are syntax errors in the posted code.  Please post a [mcve] that demonstrates your issue.
Comment: possible duplicate of [Google maps adding streetview to each infowindow](https://stackoverflow.com/questions/28227255/google-maps-adding-streetview-to-each-infowindow)
Comment: Mistake should be fixed now. I only added a snippet and not the full functionality. It should be fine now.
Comment: Are you trying to do something like [this](http://www.geocodezip.com/v3_StreetViewInInfoWindowB.html)?
Comment: Please provide a [mcve] that exhibits the issue.  Your posted code is not minimal (where is `ko` defined?)
Comment: @geocodezip Yes! That is exactly what I am trying to do. PS apologies for the code troubles.
Comment: @geocodezip I am using the knockout JS framework and the MVVM format for data/view. I did post the entire code I have with exception to the styles which I don't believe is necessary.
Answer: In the marker click handler, you need to create some DOM elements on you own, that you pass to the infoWindow content slot, instead of html.
By doing so, you'll be able to pass the reference of a div element to the google.maps.StreetViewPanorama constructor,
Take the example there and replace document.getElementById('pano') by some div element created in your click handler and also passed to infoWindow.content among other elements.
https://developers.google.com/maps/documentation/javascript/streetview


Algebra on function can change behavior?

Question: Rookie question, but I am confused here :)
So, lets say we have the following function:
$$f(x) = \frac{x-1}{x^2 -1}$$
It also equals to:
$$g(x) = \frac{1}{ x + 1}$$
$g(x)$ is defined at $x=1$ but $f(x)$ isn't. In a similar way, we could make any function undefined at any point $p$, at a $x$-coordinate we desire simply by multiplying the function by $\frac{p - x}{ p -x}$.
What am I missing here?
Answer: It comes down to understanding how functions are defined. A function $f$ is a subset of a Cartesian product of two sets $A$ and $B$, satisfying certain properties. That is, $f$ is a set of ordered pairs in the form $(a, b)$, where $a \in A$ and $b \in B$. It must additionally satisfy the following two properties:

For all $a \in A$, there exists a $b \in B$ such that $(a, b) \in f$,
If $(a, b_1), (a, b_2) \in f$, then $b_1 = b_2$.

The first condition states that every element $a \in A$ must occur in at least one ordered pair $(a, b) \in f$, and the second condition states that every element $a \in A$ must occur in at most one ordered pair $(a, b) \in f$. So, in total, every element $a \in A$ must occur in exactly one ordered pair $(a, b) \in f$. This means, for every element of $a \in A$, there is a unique associated $b \in B$, and we denote this $b$ by $f(a)$.
We call the set $A$ the domain of $f$, and $B$ the codomain of $f$. As coffeemath points out, it's important to specify the domain and codomain. Technically speaking, the rule $x \mapsto \frac{x^2 - 1}{x - 1}$ does not define a function from $\Bbb{R}$ to $\Bbb{R}$, as it fails to associate some $b \in \Bbb{R}$ to $a = 1$, in violation of the first property.
Instead, this rule can be naturally turned into a function on $\Bbb{R} \setminus \{1\}$. This is the largest subset of $\Bbb{R}$ on which this rule defines a function. This is what is often called the "natural domain". If you consider a rule like $x \mapsto \frac{x^2 - 1}{x - 1}$ to be a function, the domain is typically taken to be the natural domain, which is (again) $\Bbb{R} \setminus \{1\}$.
Compare this to the rule $x \mapsto x + 1$. This is defined for every $x \in \Bbb{R}$, so its natural domain is $\Bbb{R}$. Without specifying domains, and simply defining
\begin{align*}
f(x) &= \frac{x^2 - 1}{x - 1} \\
g(x) &= x + 1,
\end{align*}
then, by convention, you are defining $f$ and $g$ as functions on their respective natural domains (to the codomain $\Bbb{R}$). This means $f$ and $g$ are not the same! As sets, we have $(1, 2) \in g$ (as $g(1) = 2$), but $(1, 2) \notin f$.
In fact, simply knowing that $1$ lies in the domain of $g$, but not in $f$, is enough to know that these functions are not equal. From the first condition, we know that $(1, b) \in g$ for some $b$, but since $f$ is a subset of its domain multiplied to its codomain, and $1$ does not lie in its domain, then there is no element of the form $(1, b)$ in $f$. Thus, necessarily, $f \neq g$.
Answer: We can say that
$$\left(f(x) = \frac{x - 1}{x^2 - 1}\right) \land (x \neq 1)$$
$$\Leftrightarrow g(x) = \frac{1}{x - 1}.$$
Answer: $f(x)=\frac{x-1}{x^2-1}$ is a function that is (naturally) defined for all real $x \neq 1,-1$.
If we assume $x \neq 1$ then $x-1 \neq 0$ and we can divide both parts of the fraction by $x-1$ and get $f(x)=\frac{1}{x+1}$ for all $x \neq 1$ and this formula is not defined for $x=-1$, just as the previous one wasn't. But in this formula we can substitute $x=1$ to get $f(1)=\frac{1}{2}$. So what is the case is that $$\lim_{x \to 1} \frac{x-1}{x^2-1} = \frac12$$
so the original function has a "hole" in its graph at $(1,\frac12)$ which can be filled (continuous extension) so that its domain has one point more. This is a removable discontinuity in $\frac{x-1}{x^2-1}$. It agrees with $\frac{1}{x+1}$ for all of $\Bbb R\setminus \{1\}$. Usually we simplify such functions and divide out common factors, but you have to keep in mind that the original function wasn't defined at that point.
This helps limits and integrals, but for equations like $f(x)=h(x)$ you have to remember to check any found $x$ in the original unsimplified equations, to check that we don't introduce "fake" solutions on the way.
Answer: Yes you will make any expression undefined at $p$ by multiplying by $\dfrac{p-x}{p-x}$. This way you define a different function, as the domain is part of the definition.
You might as well multiply by $\dfrac{\log x}{\log x}$ or even $\dfrac{\sqrt{-x^2}}{\sqrt{-x^2}}$.
Answer: Let consider the simpler
$$f(x)=\frac x x $$
which is equal to $1$ for any  $x\in\mathbb R\setminus\{0\}$ since $x/x$ is not defined.
The point $x=0$ is a so called removable discontinuity point since we can obtain a continuous function by defining $f(0)=1$.


Transform key-value pairs to a "ragged" list

Question: I am looking for a generic way to transform a key-value pair data-frame into a "ragged" list.
key <- c("1","1","2")
val <- c("101","102","101")
x <- data.frame(key,val)

desired output:
[[1]]
[1] "101" "102"

[[2]]
[1] "101"

Answer: We can use split
setNames(split(as.character(x$val), x$key), NULL)
#[[1]]
#[1] "101" "102"

#[[2]]
#[1] "101"

Or with unstack
unstack(x, as.character(val)~key)


Number of ways of choosing five numbers of the form $10a + b$, where $1 \leq a, b \leq 5$, with conditions

Question: Let $N$ be the number of ways of choosing a subset of $5$ distinct numbers from the set
$$ \left\{10a+b:1\leq a\leq 5,1 \leq b \leq 5 \right\}$$
where $a,b$ are integers such that no two have the same tens digit and no two have the same units digit.
What is the remainder when $N$ is divided by $73$?
Comment: I'm confused. First you say that $1 \leq a \leq 5$ and $1\leq b \leq 5$ and then you say that "no two have the same tens digit", meaning that the "tens" digit in $a$ and $b$ should be different. But it should be $0$ in both cases. Did I understand this wrong?
Comment: What is "PNC" ?
Comment: Permutations N Combinations
Comment: So what does the "N" mean?
Comment: The set is of the two digit numbers i.e.
Comment: N is just abbreviation for and
Comment: 11,12,13,14,15,21...,54,55
Comment: You are to choose an element in such a way that from this set of two digit numbers. Which satisfy the above conditions.
Answer: You can choose first number in 25 ways, the second in 16 (4 possibilities for unit digit and 4 possibilities for tens digit), the third in 9, the fourth in 4 and the last is obliged. So since $25*16*9*4*1=(5*4*3*2*1)^2=120^2$ and in this way you are counting with order (clearly $\{11,22,33,44,55\}$ is the same of $\{22,33,44,55,11\}$) you have to divide by number of permutation of five elements so: $N=120^2/5!=120\cong 47 mod73$
Comment: Thanks for the soln.


Como mudar a cor da fonte de um JTextArea?

Question: Por toda a internet apenas achei gente querendo saber como estilizar parte do texto e sendo "redirecionado" ao JTextPane, então não há respostas para a minha pergunta por aí.
Então lá vai: tenho um JTextArea em um JFrame como posso trocar a cor da fonte de todo o texto do JTextArea?
Código atual:
import javax.swing.*;
import java.awt.*;
class MyFrame extends JFrame{
    private JTextArea text;
    public MyFrame(){
        text = new JTextArea();
        text.setBackground(Color.BLACK);
        text.setFont(new Font("Consolas", Font.BOLD, 14));
        //Trocar cor da fonte para branco aqui...
    }
}

Answer: JTextArea herda de JComponent, que automaticamente ganha setForeground, portanto, você pode fazer por exemplo:
jTextArea.setForeground(Color.RED);
jTextArea.setForeground(new java.awt.Color(r, g, b));


Use multifield values to create new nodes

Question: I have a multifield field_staff_required of unlimited cardinality containing two subfields: field_staff_category and field_staff_quantity.
Example: I have an event node containing the staff_required multifield to which I add the following values:
Category: Manager / Qty: 1
Category: Steward / Qty: 5
Category: Security / Qty: 3
On saving the node I would like it to automatically generate new 'staff booking' nodes for each of the staff required. The staff booking node will contain a 'Staff_category' field which would be auto populated with the category from the multifield, and an entity reference field to refer each staff booking node back to the event node.
So the result in the example above is that I end up with 9 new nodes created, one with category set to Manager, five set to Steward, and three set to Security, all referring back to the event node.
Can the above be achieved using Rules? The multifield subfields don't seem to be accessible to Rules. I assume it will be necessary to write a custom module to achieve this. Any suggestions gratefully received!
Answer: I managed to solve this by swapping the Multifield for a Double Field which does play nicely with Rules.
I was then able to use Rules Action: generate a list from an integer to loop through the quantity for each category and create a new node for each, populating the required fields.
The only downside is that Double Field does not allow to populate a select list from a taxonomy vocabulary, and I could not get the Field Remove Item or Multiple Fields Remove Button modules to work with it.


using underscorejs in a couchapp list

Question: I'm using couchdb 1.2.x, and I'm trying to use underscorejs in a list, without success.
here is how I proceed:
function(head, req) {
  var _ = require('vendor/underscore/underscore');
  log(_);
}

By looking at the couchdb log, I can see that var _ is undefined. Also, underscorejs log says:

1.3.0 — Jan. 11, 2012
  Removed AMD (RequireJS) support from Underscore. If you'd like to use Underscore with RequireJS, you can load it as a normal script, wrap or patch your copy, or download a forked version.

I'm not sure exactly how to proceed; any clues?
Thanks
Answer: As the error message in the log states, Underscore.js is no longer formatted as an AMD module out of the box.  You have two possible solutions: shim or use an AMD-ified underscore.
Shim:
Shim will wrap underscore in the necessary AMD boilerplate and be relatively transparent to you, allowing you to use an unmodified version of _.
In your case it's easy, configure requireJS like so:
require.config({
  paths: {
    underscore: "vendor/underscore/underscore"
  },
  shim: {
    underscore: {
      exports: '_'
    }
  }
});

Note: I also defined a path alias for underscore for convenience but it's not necessary to make the shim work.
AMD-ify:
An AMD-ified version of underscore (and backbone) is maintained by the author of requireJS here: https://github.com/amdjs/underscore
Comment: @rhaper
Thanks, unfortunatly It doesn't work. I think this is because couchdb has support for requirejs v1 only, but I might be wrong as I'm not very accurate on this. The AMD-ify version does not work as well (`var _ = require('vendor/underscore'); log(_);` returns undefined). Any idea? Thanks
Answer: The only suggest I have is to use the drop-in replacement Lo-Dash.
Among other things if offers AMD loader support.
Comment: Thanks, unfortunatly I haven't been able to use lodash as well. Here is what i've done: `var _ = require('vendor/lodash'); log(_.VERSION);`. I have also tried the various ways indicated on http://lodash.com/ without success. Any clue?
Answer: Looks like you're trying to create a couchdb list function. Here's how I pulled in underscore. This is all in coffeescript...
In my design document I import and declare the library then pull that in from the list function:
designDoc =
  ...
  lib:
    underscore: "<actual underscore code as a string>"
  ...
  list:
    listFunction: "<list function as a string, see below>"
  ...

In the list function itself:
(head, req) ->
  _ = require 'lib/underscore'

using underscorejs in a couchapp list


Green Function for a Segment in $\mathbb{R}$

Question: Besides just plugging and seeing that it works, is there a neat way to find the green function for Poisson's equation (Dirichlet BC) on a segment $[0,L]$?
I know it supposed to be of the form:
$$
G(x,y)=\left\{\begin{array}{cc}
-\frac{y}{L}\left(x-L\right) & x>y \\
\left(1-\frac{y}{L}\right)x & x\leq y
\end{array}\right.
$$
But I'd like to learn how to derive it.
Answer: A Greens function $G(x,y)$ is a continuous function such that for each $x$,
$$ -\partial_y^2 G(x,y) = \delta_x,\\ G(x,y)|_{y\in\{0,L\}}=0$$
These two conditions are enough to show that $f(x)=\int_0^L g(y)G(x,y) dy$ solves $-f''=g$ with Dirichlet boundary data.
If you do not know what the first equation means, you can take it to mean that $\partial_yG$ is a function such that
\begin{align} y\neq x &\implies \partial^2_y G(x,y) = 0, \tag{A}\\
 \epsilon>0 &\implies \partial_y G(x,x+\epsilon) - \partial_y G(x,x-\epsilon) = -1 \tag{B}
\end{align}
(A) means that $\partial_y G$ is locally constant in $y$, away from $y=x$. (B) means that for each $x$, there is a single jump discontinuity in $\partial_y G$ at $y=x$. Hence, for each $x$, $G(x,y)$ is two line segments, one from $y=0$ to $y=x$ and another from $y=x$ to $y=L$. Therefore, there are $A(x),B(x),C(x),D(x)$ such that
$$G(x,y) = \begin{cases}A(x)y+B(x) & y<x \\ C(x)y + D(x) & y \ge x   \end{cases}$$
with the constraints
\begin{align}
 G(x,0) = 0  &\implies B(x) = 0 \tag{1}
\\ G(x,L) = 0 &\implies D(x) = -C(x)L \tag{2}
\\ G(x,y) \text{ is $C^0$ at $y=x$} &\implies A(x)x = C(x)(x-L)  \tag{3}
\\ \partial_y G(x,y+) - \partial_y G(x,y-) = -1 &\implies C(x) = A(x)-1 \tag{4} \end{align}
(4) into (3) gives
$$A(x)x=(A(x)-1)(x-L)=A(x)x-x+L-LA(x) \\ \implies A(x)=-(x-L)/L $$
in summary
\begin{align} A(x)&=-(x-L)/L \\ B(x) &= 0 \\ C(x) &=-x/L \\ D(x) &= x
\end{align}
giving the formula.


Normal distribution to triangular distribution

Question: I would like to know if it is possible to convert a normal distribution into a triangular distribution. If it is, how it can be done?
I know the mean and the coefficient of variation of the normal distribution.
Comment: @COOLSerdash The var of a symmetric triangular distribution with mean 0 and upper limit 1 is 1/6. So to get variance matching, you'll have a factor involving $\sqrt{6}$ coming in.
Comment: Note: As an aside, I think you have the mean and *variance*...
Comment: I don't know if this is going to help in this particular situation here, but if $X\sim \mathrm{N}(\mu, \sigma^{2})$ then $\Phi\left(\frac{X-\mu}{\sigma}\right)\sim U(0,1)$, where $\Phi$ denotes the [CDF of the normal distribution](http://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function). Once you have a $U(0,1)$ distributed rv, you can easily generate a triangular distribution as described on the [Wikipedia page](http://goo.gl/XMNS3w). But if you have only the coefficient of variation, I don't know how to do it.
Comment: Since you have the **CV** it's really easy to calculate the variance from that.
Comment: @Cool If you just want to match moments, use $(v+\sqrt{6})\mu/v$ for the upper limit and $\mu-\mu\sqrt{6}/v$ for the lower limit of the triangular distribution where $\mu$ is the Normal mean and $v$ is its CV. (Whether this makes any sense or not in the OP's application is entirely another matter.)
Comment: It might help if you add some context to this question. Why do you want to do this anyway?
Comment: I'm doing some statistics for my thesis and my Professor suggested that i should do it.
Comment: So did your Prof. mean that you should "replace" the normal distribution with the triangular distribution?
Comment: Yes, I only have the mean and the CoV of the normal distribution and I should transform it into a triangular distribution.
Comment: It would help if you edit your question to include a little bit of background as to what it is you're doing--I think a little context could be helpful.
Comment: I got this distribution law from a book and it was written that for geometric purposes (my case), it should be a normal distribution with a CoV=10%. It is all i know.
Comment: First, you only need two things (*parameters*) to define a **Normal Distribution**--the **mean** and the **variance**. In contrast, you say you have the "mean" and "*covariance*", which is something different.
Comment: @COOLSerdash: **+1** -- It didn't occur to me that it was the *Coefficient of Variation*.
Comment: How old is the book you're using?
Comment: @SteveS's point is spot on: If you know the mean $\mu$ and the [coefficient of variation](http://en.wikipedia.org/wiki/Coefficient_of_variation) $\mathrm{CV}$ of the distribution, then its standard deviation is simply: $\sigma = \mu\cdot \mathrm{CV}$.
Comment: @whuber Thanks for the hint. Could you expand how this comes about? I don't understand how $\sqrt{6}$ ends up in there.
Comment: What exactly are you after when you say 'convert'? Are you asking for a transformation that takes a normally distributed random variable to a triangular one? Or are you asking for something else?
Answer: Yes, it is possible. Basically, what you need is a function $T:{\mathbb R}\rightarrow[a,b]$ such that $F_{a,b}(x)=\Phi_{\mu,\sigma}\left[T\left(x\right)\right]$, where $F_{a,b}$ is the triangular distribution on $[a,b]$, $\Phi_{\mu,\sigma}$ is the normal distribution with mean $\mu$ and variance $\sigma^2$, and $x\in[a,b]$. Then,
$$T\left(x\right)=\Phi^{-1}_{\mu,\sigma}[F_{a,b}(x)].$$
For $\mu=0,\sigma=1,a=-1,b=-1$, $T$ looks as follows

Also, note that the argument used by @COOLSerdash is valid, but the uniform is on the closed interval $[0,1]$, otherwise you cannot transform it into a closed interval $[a,b]$.
Comment: The affine transformation $x\to (b-a)x + a$ maps the interval $(0,1)$ into $(a,b)$ in a one-to-one fashion (provided $a\ne b$). We don't have to worry about the endpoints.
Comment: I do not understand that last comment about closed intervals. Since the uniform distribution assigns no probability to the endpoints $\{0,1\}$ it would seem to make no difference whether the interval is open or closed.
Comment: That's not the issue: of course they are different objects. But the distinction makes absolutely no difference in the definition of continuous distributions.
Comment: @whuber I was just recalling the [Inverse transform sampling](http://en.wikipedia.org/wiki/Inverse_transform_sampling#Definition). I think it is impossible to transform (0,1) into [a,b] with an affine (necessarily in this specific case) function. Please, correct me if I am wrong.
Comment: @whuber Not in practice, in theory the intervals $(a,b)$ and $[a,b]$ are different objects.


change Font in HTML/CSS file

Question: I downloaded the source code of this online portfolio project but I don't know how to change that weird font family. can anyone help? https://github.com/akashyap2013/PortFolio_Website
Comment: not sure if i got you but check this https://github.com/akashyap2013/PortFolio_Website/blob/master/css/fonts.css

that where he define his font
Comment: What did you try? Did you do any research before asking? Because there's a post titled [Changing font in CSS](https://stackoverflow.com/q/44648605/215552) that probably answers your question. In any case, please take the [tour] and read [ask], where it says, "...**copy the code into the question itself.** Not everyone can access external sites, and the links may break over time. Use [Stack Snippets](https://meta.stackoverflow.com/q/358992) to make a live demo of inline JavaScript / HTML / CSS."
Answer: To change the font, you can add the @font-face in the CSS.
For example:
@font-face{
    font-family: Helvetica;
}

If you use another font like Roboto, you may need to add its source link:
@font-face{
    font-family: Helvetica;
    src: 'source link here',
}

Or you may just set in the text itself like this:

span {
  font-family: helvetica;
}

p {
  font-family: serif;
}
Helvetica

Serif

In that repository, the font style is defined in: https://github.com/akashyap2013/PortFolio_Website/blob/master/css/fonts.css
Answer: Go to your CSS folder and to the fonts.css
/* @font-face */

@font-face{
font-family: "Roboto";
src: '../fonts/Roboto/Roboto-Regular.ttf';
}

then change this to any font you want. just download a new font pack online and replace the font folder. Then route that new font folder this css.
i.e
/* @font-face */

@font-face{
font-family: "super-cool";
src: '../fonts/super-cool/super-cool-Regular.ttf';
}

change Font in HTML/CSS file


Don't put the current value in the form

Question: Faced such a problem that the current values about the user are not passed to the form. What I want to do is to combine the user model and the profile model, then display the current user data in two forms for editing. It seems to be done correctly, but for some reason it does not work. Please tell me who understands this)
file views.py:
class ProfilePage(UpdateView):
        model=Profile
        template_name="market/profile.html"
        form_class=ProfileUpdateForm
        second_model = User
        second_form_class= UserUpdateForm

        def get_context_data(self, **kwargs):
            context = super(ProfilePage,self).get_context_data(**kwargs)
            context['UserUpdateForm'] = UserUpdateForm(
                prefix='UserUpdateForm',
                data = self.request.POST,
                instance=self.request.user,
            )
            context['ProfileUpdateForm'] = ProfileUpdateForm(
                prefix='ProfileUpdateForm',
                data = self.request.POST,
                files = self.request.FILES,
                instance=self.request.user.profile,
            )
            return context

        def post(self, request, *args, **kwargs):
            super(ProfilePage,self).post(self, request, *args, **kwargs)
            context = self.get_context_data(**kwargs)
            if context['UserUpdateForm'].is_valid():
                context['UserUpdateForm'].save()
            elif context['ProfileUpdateForm'].is_valid():
                context['ProfileUpdateForm'].save()
            return self.render_to_response(context)

file forms.py:
class UserUpdateForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ("username",)

class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model=Profile
        fields=('valuta','slug','avtor')

file models.py:
class Profile(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    avtor=models.ImageField(default='user_images/default.jpg', upload_to='user_images',blank=True)
    slug=models.SlugField(max_length=50, unique=True,blank=True)
    valuta=models.ForeignKey(Valuta,default="5", on_delete=models.CASCADE)

file profile.html:
<form method="POST">
    {% csrf_token %}
    {{UserUpdateForm.as_p}}
    <button type="submit">send</button>
</form>
<form action="" enctype="multipart/form-data" method="POST">
    {% csrf_token %}
    {{ProfileUpdateForm.as_p}}
    <button type="submit">send</button>
</form>

Comment: When you say `current values about the user are not passed to the form` do you mean when the form is initialized, the form fields aren't prefilled with the User object values? Or do you mean when POSTing?
Comment: when the page is loaded and it issues this https://ibb.co/BfYwbzk,
I want the form to contain the current data about the user, there is his username
Comment: Is the template just doing {{ form }}? You can declare `initial` as a kwarg in the init function of the form if you need to. Let me know if you don't know what I mean and I'll write an answer
Comment: Yes, I think this is what I need. I need the user to see their data immediately. And I updated the question by adding template
Answer: When you create your forms in your get_context_data, you also pass self.request.POST. So it tries to render the form with the POST data (whereas it is empty at first).
You should add or None for this line for UserUpdateForm and ProfileUpdateForm :
data = self.request.POST or None,

And also for the ProfileUpdateForm where it uses files :
files = self.request.FILES or None,

Then it will render the form with the instance data and use POST data when it exists.
Comment: When I click submit, the form is saved, everything is correct, but now another problem has appeared - the page is loaded, where another form is empty and with an error :(
Comment: I believe this is because you separated in two forms in your HTML. When you submit, only one form is being passed through your request, thus the other form doesn't have required data when loaded then.
Comment: It's sad, because when I have forms together, then there is also a bug, when I save the form, I get an error in the login field - "this user already exists." Okay, thanks anyway

Don't put the current value in the form


Spring Batch - How to handle an object buffering on the ItemProcessor's level

Question: I am using a Spring Batch under the hood in my application.
I have a lot of the already written ItemReader(s), ItemWriter(s) and a composite ItemProcessor(s) that allow me to build a Job that contains a chunk steps. All of the components share the same domain object "Product".
public class CustomReader implements ItemReader<Product> {

@Override
public Product read() throws Exception {
    //business logic for reading a products
    return null;
 }
}

public class CustomWriter implements ItemWriter<Product> {

@Override
public void write(List<? extends Product> items) throws Exception {
    //business logic for writing a products
  }
}

public class CustomProcessor extends ItemProcessor<Product, Product> {

@Override
public Product process(Product product) throws Exception {
    //custom logic for data processing
    return null;
 }
}

Currently I need to have a possibility to use a new ItemProcessor that will be sending an http requests. However, from the Processor's perspective I have an access only to the individual Product object, but instead of sending an http request for a single product, I need to gather a 10 products together (get their ids) and execute a batch request. Then I need to map the response and return a multiple Products back to the ItemWriter.
public class CustomHttpProcessor extends ItemProcessor<Product, Product> {
@Override
public List<Product> process(List<Product> product) throws Exception {
    //custom logic for sending a batch requests via http
    return null;
 }
}

Is there any other option than changing the base domain object from Product to List everywhere in the codebase (I have a feeling that I will significantly decrease the performance of the entire application and skyrocket the memory usage?) Are there any other Spring Batch's features that I can use, or any patterns that I can use?
Thanks in advance for any help!
Answer: You can do that with an ItemWriteListener#beforeWrite(Chunk<Product> products). This callback gives you access to the chunk or items just before they are written, so you can perform your REST batch request at that point and transform them as needed before the write operation.


Delete Trigger according to function name

Question: I have a example function with the name ClimaParaTestes():
function ClimaParaTestes() {
}

I have a trigger that every 30 minutes this function is activated.
If a certain value in the spreadsheet appears, I want the trigger to be activated every 1 minute instead of 30 minutes.
For that, as I understand it, I need to delete the current Trigger and create a new one.
As I have several Triggers in the same file, I'm trying to delete according to the function name, so I tried to use:
function DeleteTriggerClima() {
  var Triggers = ScriptApp.getProjectTriggers();
  for (var i = 0; i < Triggers.length; i++) {
    if (Triggers[i].getHandlerFunction() == "'Run' ClimaParaTestes") {
      ScriptApp.deleteTrigger(Triggers[i])
    }
  }
}

Nothing happens and when I try to pull Logger.log in this way to understand the values received:
function DeleteTriggerClimaParaTestes() {
  var Triggers = ScriptApp.getProjectTriggers();
  Logger.log(Triggers);
}

The Result is:
[Trigger, Trigger]

So I couldn't understand how I can manage to delete the trigger. How should I proceed?
Answer: Try this:

function deleteTriggerWithName(name) {
  const trs = ScriptApp.getProjectTriggers().map(t => t.getHandlerFunction());
  const ts = ScriptApp.getProjectTriggers();
  ScriptApp.deleteTrigger(ts[trs.indexOf(name)]);
}

Comment: name is a parameter.  It's the name of the Handlerfunction that the trigger is assigned to
Comment: `deleteTriggerWithName("ClimaParaTestes")`
Comment: My mistake, it needs a trigger rather than a handlerfunction name.
Comment: Thanks for the help @Cooper, I'm not familiar with the use of ```(name)```, I'm having trouble understanding how I can set ```name``` to ```"ClimaParaTestes"```, could you explain or indicate a link to learning? Thanks in advance!
Comment: I created a new function to call ```deleteTriggerWithName("ClimaParaTestes")``` and the answer was: The parameters (String) do not match the method signature for ScriptApp.deleteTrigger. --> Note: The log response to ```trs```is: ```[ApagarHistóricoDoClima, ClimaParaTestes]```.
Comment: Now it's perfect mate, if you want, adjust ```SriptApp``` to ```ScriptApp``` (add one "c") in the ```const ts``` line, so future readers won't ask you why giving an error in the line.


Unable to start services in Centos 7 with error "Authorization not available" even as root user

Question: I am not able to start services for the following Centos 7 server
[root@myserver home]# uname -r
3.10.0-1160.11.1.el7.x86_64
[root@myserver home]# cat /etc/centos-release
CentOS Linux release 7.9.2009 (Core)

I first realised there was a problem when I observed that docker was down, so I ran the following as root
[root@myserver home]# systemctl start docker
 Authorization not available. Check if polkit service is running or see debug message for
 more information.
 Failed to start docker.service: Connection timed out
 See system logs and 'systemctl status docker.service' for details.
[root@myserver home]# systemctl status docker.service
 ● docker.service - Docker Application Container Engine
 Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
 Active: inactive (dead)
 Docs: https://docs.docker.com

I then ran
 [root@myserver home]# systemctl | grep -i fail
 ● firewalld.service                          loaded failed     failed      firewalld - dynamic firewall daemon
 ● plymouth-start.service                     loaded failed     failed      Show Plymouth Boot Screen
 ● polkit.service                             loaded failed     failed      Authorization Manager
 ● systemd-machined.service                   loaded failed     failed      Virtual Machine and Container Registration Service
 ● tuned.service                              loaded failed     failed      Dynamic System Tuning Daemon

Also
 [root@myserver home]# systemctl status polkit.service
 ● polkit.service - Authorization Manager
    Loaded: loaded (/usr/lib/systemd/system/polkit.service; static; vendor preset: enabled)
    Active: failed (Result: timeout) since Thu 2021-02-04 11:14:54 GMT; 5h 45min ago
      Docs: man:polkit(8)
   Process: 7932 ExecStart=/usr/lib/polkit-1/polkitd --no-debug (code=killed, signal=TERM)
  Main PID: 7932 (code=killed, signal=TERM)

  Feb 04 11:13:23 myserver.com systemd[1]: Starting Authorization Manager...
  Feb 04 11:13:48 myserver.com polkitd[7932]: Started polkitd version 0.112
  Feb 04 11:14:54 myserver.com systemd[1]: polkit.service start operation timed out. Terminating.
  Feb 04 11:14:54 myserver.com systemd[1]: Failed to start Authorization Manager.
  Feb 04 11:14:54 myserver.com systemd[1]: Unit polkit.service entered failed state.
  Feb 04 11:14:54 myserver.com systemd[1]: polkit.service failed.

I am not aware of any updates made to the server. I think these problems began after an unplanned reboot, but I can't establish the reason for the reboot. Why would starting the Authorization Manager time out? Does anyone have any suggestions for further investigation?
Answer: Just document my case, this could help some one
polkit is a policy service that means some other services need it's authorization before executing actions
The problem appears after kvm backup restore
guest VM uses centos 7
if I tried to start or restart any service like network or sshd the system reboots after showing this message for secons
Authorization not available. Check if polkit service is running or see debug message for more information.
In my case polkit was complaining about dbus error like
Failed to connect to system bus: Connection refused
journalctl -b -p err
I found that missing disk casus issues with dbus
Solution was easy remove the missing disk from fstab
Also I found similar problem here https://www.thegeekdiary.com/authorization-not-available-check-if-polkit-service-is-running-or-see-debug-message-for-more-information-centos-rhel-7-ssh-service-error/
Answer: I issued a
[root@myserver home]# reboot

command and it seems to be working. Before, when I was having the initial problem, I had used
[root@myserver home]# shutdown -r now

I am curious as to why the difference in the two commands caused my initial problem...


How should I represent/store a song duration as a property? I want to use a common song duration format such as "HH:MM:SS"

Question: I have a custom class called Song. Each instance of this class needs to have a property which represents its duration, and I want that duration in a normal "songy" format like HH:MM:SS. The Song instances will be receiving data, such as duration, from JSON network calls, and they also might be persisted via Core Data or some other method.
What are my options to store this duration? Do I need to store it has a string like
self.duration = @"0:2:14";

or
 self.duration = @"0.2.14";

Would storing it as a NSNumber of NSDate be better? If so, how do I convert it to those types? If I need to store it as a string, is there a better way to convert it into a number/time interval than splitting the colons?
Comment: Neither `NSNumber` or `NSDate`, both have some specific properties behaviours.

In your case you need only to store value to show it as `05hours:23minutes:04seconds` i.e., `05:23:04`

These are fixed value, and you require it as string, so store them as string. Also storing it as string  doesn't matter how you use, any one will be fine.
Comment: Store it as an integer representing the number of seconds. That would provide the flexibility of changing the format easily if requirements change.
Comment: @AnoopVaidya What do you mean by `specific properties behaviours`?
Comment: NSNumber with two decimals (2.4.5) or (d:f:e) i guess look awkward, and nsdate stores timeinterval from gmt 1jan1970. so all your songs needs to be based on 1970. do you really need that/
Answer: You should store the duration in seconds (or milliseconds if you want to be that exact) as an integer. Then convert that to a pretty format when displaying the time, for example through a method -(NSString*)displayDuration
If you declare your duration property like this
@property (nonatomic) int duration;

then you could write a method to get an NSString for display:
- (NSString*)displayDuration {
    int remainingDuration = self.duration;
    int seconds = remainingDuration%60;
    remainingDuration/=60;
    int minutes = remainingDuration%60;
    remainingDuration/=60;
    int hours = remainingDuration;
    return [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}

Comment: Isn't there a better way to do that with `NSDateFormatter` or something like it?
Comment: +1 for the general idea of storing as time interval and converting to "pretty format", but I would use double (same as NSTimeInterval) type, not integer, and I would consider using NSDateFormatter to create pretty strings. For HH:MM:SS only your suggestion works though.
Answer: Use NSDateComponent
let cal = NSCalendar.currentCalendar()
let comps = cal.components([.Day, .Hour, .Minute], fromDate: self, toDate: otherDate, options: [])
return (comps.day , comps.hour , comps.minute)

where self is a NSDate and otherDate is also a NSDate (this was implemented as an extension to NSDate)
Add components as you like (here are only days, hour, minutes)
The example code returns a tuple. Accessible via .0, .1, .2 allowing string formatting in whatever way necessary.
Code is in Swift 2


How to display all suppliers in order detail?

Question: I want to display a list of ALL suppliers available in the order detail page in a select box and all suppliers available for that product in another select box.
What I tried to do is add to \prestashop\admin\themes\default\template\controllers\orders\helpers\view\view.tpl:

    {l s='Supplier'}

            <select id="id_supplier" name="id_supplier">
                {foreach from=$suppliers item='supplier'}
                    <option value="{$supplier.id_supplier}">{$supplier.name}</option>
                {/foreach}
            </select>

But this doesn't work (the select box is empty).
Comment: are you sure that there is availlable $suppliers smarty variable? put {debug} in template.
Answer: there's no $supplier in controllers/admin/AdminOrdersController.php which means that you need to get informations about Suppliers by using this code:
$suppliers = Supplier::getSuppliers();
of course you need to foreach this loop and check which supplier is already in order and create another array for second select
after that you need to assign those variables in renderView method in controller


A problem on rationals limit point etc.

Question: $B=\cup_n(r_n - 2 ^ {-n-2}, r_n + 2 ^ {-n-2})$ where $r_1, r_2, \dots$ is an enumeration of the rationals in $(0,1]$. I want to understand the set $(0,1]-B$ like limit point of that set. Hint enough.
Answer: This is meant to be an example to make you realize that some weird things can happen with infinite sets - even sets we think we understand, like unit interval.
The main thing about $B$ is that it contains all the rationals in $(0,1]$.  Since the rationals are a dense subset of $(0,1]$, this means that every element of $(0,1]$ is expressible as the limit point of elements on $B$.
The measure of $B$, on the other hand, is quite small. The $n$th open interval in the construction of $B$ has length $2^{-n-1}$, which means that by subadditivity, the measure of $B$, denoted $\lambda(B)$ satisfies:
$$\lambda(B)\leq \sum_{n=0}^{\infty}2^{-n-1}=\frac{1}{2}.$$
It follows immediately that $\lambda((0,1]\setminus B)\geq \frac{1}{2}$.
(It is also easy to see that a set with similar properties can be found with an arbitrarily small measure.)
Finally, since $B$ is defined as a union of open intervals, it follows that $B$ is open, and that $(0,1]\setminus B$ is closed.
So, $(0,1]\setminus B$ is a largish set in $(0,1]$ (and can be made arbitrarily large by making the open intervals used in the construction of $B$ smaller). It is a closed set.  It contains only irrational numbers, which means it is totally disconnected.  And it lies in the closure of $B$.
Does this make the set easier to understand?
Comment: I want to prove that if $(0,1]-B \subset \cup_{k=1}^{\infty} I_k$ ($I_k$'s are half-open interval) then $\sum_{k=1}^{\infty}|I_k|$ is at least some positive number. I want to do it using the definition of negligibility and without notion of "measure".
Comment: Well since $(0,1]\setminus B$ is closed (its complement is open), and since it contains no non-empty open intervals (since every non-empty open interval contains a rational number), it follows that it is nowhere dense, and hence a negligible set. Is that what you wanted?  What are the $I_{k}$s?
Comment: no,it is not a negligible set. I want to prove that.
Comment: Moreover, a nowhere dense set may or may not be negligible.
Comment: $B$ is the union of open sets, and so is open. The complement of $B$ is therefore closed. Furthermore, $B$ contains all the rational numbers.  Since every non-empty open interval contains at least one rational number, the complement of $B$ cannot contain any rational numbers and so cannot contain non-empty open intervals. So, $\left(\overline{(0,1]\setminus B}\right)^{\circ}= ((0,1]\setminus B)^{\circ}=\emptyset$.  The complement of $B$ is therefore nowhere dense.  Since all nowhere dense sets are negligible, it must be true that the complement of $B$ is negligible.
Comment: A set is negligible if it is the union of a countable family of nowhere dense sets.  A family of one is countable, so nowhere dense sets are negligible.
Comment: negligibility has some connection with measure. a set is negligible iff it has measure zero. But, this sets have measure at least $\frac{1}{2}$. A set is negligible if it can be covered by countable union of half-open intervals such that the sum of length of the intervals can be made arbitrarily small. your definition is of "first category" according to me.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/12774/discussion-between-unwisdom-and-aaaaaa)

A problem on rationals limit point etc.


Heat equation steady state boundary condition question

Question: consider the following question and the part of the solution to calculate the radial part:

The solution for the R part

Could someone please clarify why c2 = 0 as i am a bit confused as to why this is.
Comment: Otherwise, as $r$ approaches 0, $R$ increases without bound.
Answer: Boundary condition 3 and not 1 states that $R(r)$ is finite everywhere. So $R(0)$ must also be finite and it's the case only if $c_2=0$ then $R(0)=0$ and is defined. If $c_2 \neq 0$ then:
$$R(0)=c_1r^l+c_2r^{-l-1}=c_1\times 0 + \frac {c_2} 0$$


Como tornar único um elemento *Filho* (Onde o filho do filho tem a mesma class)

Question: Como tornar único um elemento Filho (Onde o filho do filho tem a mesma class)?
Alguém pode trazer uma solução de preferencia em CSS?
Exemplo abaixo:

Comment: obs: não é possivel adicionar, alterar ou remover nenhuma class de lá, quero somente capturar o filho, sem mudar as propriedades do filho do filho.
Comment: Vc quer dizer que por exemplo a classe .vitrine vai ter alguns estilos que vc não quer que seja aplicado tb ao filho?
Comment: exatamente!!!!!
Answer: Cara tem omo sim, o problema é que algumas classes são herdadas por default, como por exemplo propriedades de texto tipo color e font-family.
Vc vai precisar usar o seletor :not(), para evitar que o elemento com as classes .vitrine e .centraliza-vitrine ao mesmo tempo não receba os estilos. Mas vc não vai conseguir bloquear os estilos de texto herdados.
Com a regra .vitrine:not(.centraliza-vitrine) { }

SEM a regra .vitrine:not(.centraliza-vitrine) { }

Código da imagem acima

#conteudo {
    color: green;
}

.vitrine:not(.centraliza-vitrine) {
    border: 1px solid #000;
    box-shadow: 0 0 10px green;
    margin-top: 20px;

/* estilos herdados */
    color: red;
    font-size: 20px;
    font-family: sans-serif;
}

        Filho

            Filho do filho

        Filho

            Filho do filho

DICA
Vc pode tentar "restar" os estilos do elemento filho do filho, por exemplo colocando um all:initial nele, porém ele vai ficar com os estilos "zerado".

#conteudo {
    color: green;
}

.vitrine:not(.centraliza-vitrine) {
    border: 1px solid #000;
    box-shadow: 0 0 10px green;

/* não vai herdar esses estilosestilos herdados */
    color: red;
    font-size: 20px;
    font-family: sans-serif;
    margin-top: 20px;
}
/* estilos iniciais padrão do elemento */
.vitrine.centraliza-vitrine {
    all:initial;
}

        Filho

            Filho do filho

        Filho

            Filho do filho

Comment: Hugo, MUITO OBRIGADO!!! a propriedade ".vitrine:not(.centraliza-vitrine)" funcionou perfeitamente, era isso mesmo, sabia que a propriedade :not existia mas não sabia pra que servia, agora sei ahahahah vlw mesmo!
Comment: @LucasPereira legal que ajudou ai! Se vc acredita que o problema foi resolvido e a resposta te ajudou, considere marca-la como Aceita, nesse ícone ✔ abaixo das setinhas no lado esquerdo da resposta :) Assim o site não fica com perguntas abertas pendentes sem resposta aceita. Vc pode remover a aceitação, ou mudar para outra resposta caso apareça alguma que te atende melhor. Abs


AWS Bucket Policy permissions to Load Balancer denied

Question: So far my S3 Bucket policy looks like this which I have got from the Generator Policy, I included my Account ID as the Principle to generate the policy but when I go to add this within my Load Balancer attributes it says that "Access Denied for bucket: bucket2. Please check S3bucket permission" What is denying access and how could I fix it?
<code>{
    "Version": "2012-10-17",
    "Id": "Policy1630018580759",
    "Statement": [
        {
            "Sid": "Stmt1630018536294",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::615298492481:root"
            },
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::elb-bkt/logs/AWSLogs/615298492481/*"
        }
    ]
}
</code>
Answer: TL;DR
Replace elb-account-id in "Principal" with appropriate region ID from the below list:
========================================================

========================================================
The policy mentioned in the docs looks something like this:
<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::elb-account-id:root"
      },
      "Action": "s3:PutObject",
      "Resource": "my-s3-arn"
    }
  ]
}
</code>
Here we need to update two things - elb-account-id and my-s3-arn.
The common pitfall we all get into is that we insert the AWS account ID in place of the elb-account-id. This is what you did here. Replace the AWS account ID with the region ID and it should work.


Does firebase charge when downloading backup files?

Question: You can enable Firebase Realtime DB to be automatically backed up daily.
Do they charge when downloading data to backup? Or do they charge when we download a backup file (.zip file).
Answer: The backups of the Firebase Realtime Database are written to a Google Cloud Storage bucket. There is no bandwidth charge for the  writing of the backups to the bucket.
You will be charged for the storage space the backups occupy, and for downloading the backups from the bucket. Both are charged as a normal GCS operations.
Also see the cost section of the documentation for the backup feature:

The backups feature can be enabled for Blaze projects for no additional cost. However, you will be charged at the standard rates for the backup files placed in your Google Cloud Storage bucket. You can enable Gzip Compression and Storage 30 day Lifecycle to reduce your storage costs.
Comment: You guys are really quick. Thank you very much for the quick response. :)


Problema com class org.hibernate.validator.InvalidValue ao fazer upgrade do Hibernate 3.X para 4.X

Question: Tenho um projeto desenvolvido usando JBoss Seam 2.2.2.Final juntamente com Hibernate 3.6. Estou tentando fazer um upgrade deste projeto subindo e migrando as versões do componentes que ele usa. Uma dessas migrações é subir a versão do Hibernate para a versão 4.6.3.Final, que na data dessa postagem é a última versão estável.
Como o projeto está no Maven, a primeira coisa que fiz, foi atualizar as dependências do projeto subindo as versões do Hibernate. Da seguinte forma:
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.4.Final</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>4.3.4.Final</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-envers</artifactId>
    <version>4.3.4.Final</version>
    <scope>provided</scope>
</dependency>

No entanto, ao fazer as atualizações de versões no pom.xml, o projeto começou a apresentar erro de compilação justamente em algo relacionado ao Hibernate. Veja o trecho de código abaixo:
ResourceBundle bundle = SeamResourceBundle.getBundleNamed(NOME_BUNDLE);
StringBuilder msg = new StringBuilder("");
msg.append(bundle.getString(MSG_GERAL));
StatusMessages.instance().add(msg.toString()); //Erro ocorre aqui

Na quarta linha do trecho acima, ocorre um erro relacionado a classe org.hibernate.validator.InvalidValue (link documentação). O erro que ocorre é mostrado pelo Eclipse:

The type org.hibernate.validator.InvalidValue cannot be resolved. It
  is indirectly referenced from required .class files

Alguém sabe como corrigir esse problema? Ou sabem algum workaround para isso?
Answer: O hibernate validator foi atualizado na versão 4 do hibernate.
Adicione nas suas dependências:
  <dependency>
     <groupId>org.hibernate</groupId>
     <version>4.0.2.GA</version>
     <artifactId>hibernate-validator-legacy</artifactId>
   </dependency>

Para manter a compatibilidade.


Check if words from a file occur in a SQL query in an efficient way

Question: I have a .txt file with words and small phrases separated by , and I wish to see which of these words occur in each row returned by
 for line in cur.execute("select text from reviews where business_id = (?) ", (s,)): (s takes values from an outer for loop).
My goal is to add +1 to a counter whenever a word from the .txt file is occuring in the rows returned by the SQL query (these rows are string of varying sizes, usually big enough to make slicing them and checking each word seperately time-consuming).
Is there another way to do so?
What I've tried:
for words in line:
   with open("good_words.txt", "r") as check:
     for x in check:
        if x in words:
        goods += 1

Which leads to my PC burning up and basically crushing.
Comment: Turn every word and phrase in a RegEx and have multiple if-then-else statements? That would be just as time-consuming but I will try it.
Comment: You could turn the words into regular expressions, and then use a regexp search for them.
Comment: `for words in line:` iterates over the characters in `line`, not the words. It should be `for words in line.split()`
Comment: No `if/then/else` statements, just a `for` loop that iterates over all the regexps.
Comment: @Barmar how can I split tuples?
Answer: Read all the words and phrases into a list of regexps.
good_words = []
with open("good_words.txt", "r") as f:
    for line in f:
        good_words.append(re.compile(r'\b' + re.escape(line) + r'\b'))
for line in cur.execute("select text from reviews where business_id = (?) ", (s,)):
    for word in good_words:
        if word.search(line[0]):
            goods += 1

\b matches word boundaries, so you don't have to split up the line into words.


Definir largura para editor nicEdit

Question: Alguem sabe definir a largura do editor nicEdit?
Comment: Você quer definir `inline`? Se sim, é só usar HTML simples: `width: 100px`
Answer: Defina no seu textarea no seu style o width: no valor de 100% ou em pixel o valor desejado (300px), exemplo:
<textarea name="area" style="width: 100%;">
    Some Initial Content was in this textarea
</textarea>

<textarea name="area" style="width: 300px;">
    HTML content default in textarea
</textarea>

Site referência: Demo -  NicEdit
Comment: Não sabia que tinha que definir direto no componente, Agradeço novamente maria.
Comment: Não @Marconi ... esse comportamento estranho você poderia abrir outro questionamento ...

Definir largura para editor nicEdit


"No acceptable module found" on Android emulators using com.google.android.gms play-services 9.2.0

Question: I have recently updated to com.google.android.gms:play-services 9.2.0 and am attempting to use the new Chromecast library and Firebase Analytics but am receiving the error "com.google.android.gms.internal.zzsj$zza: No acceptable module found. Local version is 0 and remote version is 0." in the Activity  onCreate method at com.google.android.gms.cast.framework.CastContext.(Unknown Source). Any ideas if this is due to the Cast functionality not working with the emulators or if it's a version issue? The emulators I am testing with are running 5.0 and 5.1.
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FirebaseAnalytics mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
    setupCastListener();
    mCastContext = CastContext.getSharedInstance(this);
    mCastSession = mCastContext.getSessionManager().getCurrentCastSession();
    mCastContext.getSessionManager().addSessionManagerListener(mSessionManagerListener, CastSession.class);
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
}

Thanks
Comment: I got error message that "No acceptable module found. Local version is 0 and remote version is 0" , i add run-time permission and problem solved.
Answer: The version of Play Services on your emulator does not support 9.2.0. At this time, I don't think any of the emulator images support 9.2.0.  Your options are to downgrade to 9.0.2, or run on a real device until an updated emulator image is released.
If you look carefully at your logcat output you should see a message like this:
W/GooglePlayServicesUtil: Google Play services out of date.  Requires 9256000 but found 9080030

You can see the GPS version number the emulator is using by going to Settings/Apps, finding Google Play Services, and tapping on it to get the App Info.
You can get the GPS version number from code by calling GoogleApiAvalability.GOOGLE_PLAY_SERVICES_VERSION_CODE.
This answer contains some related information about emulator versions.
Update for Adrian Cretu's questions regarding real devices
My experiments indicate that it is possible for a Cast app running on a real device to detect an older version of Play Services and initiate resolution processing.  I experimented with the CastVideos sample app.  My solution may not be the best, but demonstrates the concept.  I created a new activity that runs on launch and checks the availability of Play Services.  I changed the manifest to make this activity the launcher activity instead of VideoBrowserActivity:
public class InitActivity extends AppCompatActivity {
    private static final String TAG = "InitActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        GoogleApiAvailability googAvail = GoogleApiAvailability.getInstance();

        int status = googAvail.isGooglePlayServicesAvailable(this);
        Log.i(TAG, "onCreate: Status= " + googAvail.getErrorString(status));

        googAvail.makeGooglePlayServicesAvailable(this)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                Log.i(TAG, "onComplete: Done");
                if (task.isSuccessful()) {
                    Log.i(TAG, "onComplete: Starting VideoBrowser");
                    startActivity(new Intent(InitActivity.this, VideoBrowserActivity.class));
                    finish();
                } else {
                    Log.e(TAG, "onComplete: RESOLUTION FAILED");
                }
            }
        });
    }
}

If Play Services is present, up to date, and enabled, the task that checks for availability completes immediately and starts VideoBrowserActivity, the original launch activity. Otherwise, a dialog is presented telling the user that Play Services must be upgraded, and after the user accepts, the Play Store is opened and the user can initiate a download of the latest version.
I was unable to find a way to cleanly transition back to the VideoBrowserActivity.  I had to restart the app. With more work, I think a clean recovery from out-of-date Play Services is possible.  At least something better than an app crash.
Comment: Thanks for the sample. After some digging it appears the crash occurs when CastContext.getSharedInstance() is called, which I'm actually calling from a Service. Your approach, while perfectly valid, is not at all developer-friendly. Cast v2 was a pain exactly because of the entire Google API client boiler-plate: connection flow, errors, callbacks, and user resolutions such as opening activities and waiting for the results, all for just calling loadMedia of a simple URL... I guess deleting all those hundreds of lines of code and switching to v3 was not a good idea.
Comment: Thanks qbix. Maybe I should re-think using this version for a bit. Too bad the cast functionality was much improved.
Comment: Sounds like a significant issue that deserves a separate question.  Although Google claims that updates to Play Services are pushed out to phones in a few days, there will always be cases where a device does not the latest version.
Answer: This crash also happens on real devices with non-updated GPS. I am using Google Cast SDK v3 and GPS 9.2.0
I didn't see anywhere mentioned that the device actually requires GPS 9.2.0 in order for the Cast v3 to work. What is the workaround or at least a solution for the app not to crash on startup?
Comment: I think the only solution is for users to upgrade to the new upgrade play services and handle the errors unfortunately.
Comment: I don't use Cast and am not familiar with its dependencies.  In general, it is possible to use the methods in [GoogleApiAvailability](https://developers.google.com/android/reference/com/google/android/gms/common/GoogleApiAvailability) to resolve problems with Play Services not being present or not updated to a needed version.  I recall there is a guide on how to do this in the documentation but can't find it. You might find some examples or more info if you search for it.
Comment: @qbix - the Cast SDK v3 explicitly doesn't require any interaction with GPS client availability as a feature for simplified usage. The exception occurs before the activity is even created, so there's no actual hook to override and check availability, etc; unfortunately because now is over-simplified to work behind the scenes, the app just crashes when the latest GPS is not present. Looks like a bug to me more than a feature.
Comment: I updated my answer in response to your comments.  I hope my experiments were with Cast SDK v3.  I'll check that now.
Answer: When I updated the google play developer services app, I was able to solve it.
Comment: This looks more like a comment and not an answer.


Specific fingering for barre chords on guitar

Question: I have noticed that when playing the standard F barre chord, guitarists use their pinky finger on the D-string and the ring finger on the A-string - the ring finger is vertically above the pinky.
<code> %1/T.3/3.3/4.2/2.1/1.1/1[F]
</code>
The same holds when, for example, playing the standard C chord with a G in the bass (332010). I, however, always play these chords with my pinky vertically on top of my ring finger - i.e. pinky on the A-string and ring finger on the D-string when playing the F barre chord.
<code>  %1/T.3/4.3/3.2/2.1/1.1/1[F]
</code>
At the moment, it doesn't seem to be causing me any problems, but I am wondering whether or not my fingering is potentially problematic in some way?
Thank you in advance!
Comment: Can you check the diagrams I added, and confirm they're what you mean?
Comment: I usually use my thumb to play the bottom F, but other than that, they're perfect! Thank you, slim. Replaced the '1's on the bottom E-string with 'T's - not sure if this is correct notation.
Answer: Everyone's fingers/thumbs have different proportions. Most people will find that actually barring an 'E'-shaped chord is easier and more effective using a barre with their index finger ( the clue's in the name), but there's no rule that states this HAS to be the case.   If you find that thumbing the bottom string works , then continue. It may be that your digits lend themselves well to this sort of fingering. You may find, however, that changing to the barre A-shape becomes problematic, in that you have to change the whole attitude of your forearm to go from one to the other.This will slow down the changes: it's difficult to use the thumb to cover 6th and 5th strings together ! It would appear that your pinky is relatively longer than most pinkies ! This can be pretty useful to a guitarist !     Generally one's ring finger covers the A string because its reach is better than one's pinky's. Also for putting a 6th or b7th note in on 2nd string, the pinky is favourite. You may need to reconsider later, or even now........
Comment: For C7 (or any similar shape further up the fingerboard) use of ring finger on 5th string is a good pivot to and from E-shape barre chord on the same fret.(e.g. A, 5th fret barre,  to E7; ring finger can stay on 5th string, 7th fret to move to an E7 chord, C7 shape.)
Comment: Thank you for your response, Tim, but my question has nothing to do with whether or not to use my thumb when playing barre chords. My question is about the placement of my ring and pinky finger when playing barre chords - with or without thumb(unless pinky/ring placement should change depending on whether or not you're using your thumb?).
Comment: My apologies, I didn't fully read your response! Would you say that as long as I am comfortable with my pinky on top, it isn't problematic? I do play barre chords without my thumb also, so disregarding the drawbacks of using your thumb.
Comment: Quite agree with Tim. Though your fingers's size will have a word on it, your configuration for F on the E-Shape will mean extra "energy" spent when changing for A-shaped chords or for a C7, which by the way is the V7 for a song in the tone of F.
Answer: Since you didn't mark this as answered yet, I'll add my two cents. I used the same fingering you're describing when I began playing guitar, and I switched when I realized it was more difficult (at least for me) to add embellishments and motion within chord lines.
For example, if you're playing a 6-string barre shape Bmaj (799877) and you want to make a quick move to a Bsus4 (79x977), I found it was very difficult to do with my ring finger on the D string as you've described. By switching to the more standard fingering, I found it much easier to use my pinky to hit the E on the G string 9th fret and my ring finger to mute the D string.
This was problematic for me and for years now after switching I've found the standard version to be easier on my wrist. If it's comfortable for you and doesn't appear to impede your play in any way, I'd say there's no reason to consider changing at the moment.


How should I start studying jazz standards?

Question: I am beginning to learn guitar itself.
I can read music sheet, have studied music theory well enough to understand chord progressions.
But I have not played much other than Bach's Bourree and some church songs and pop songs because nothing much draws my attention.
Without much experience and ears to pick up melodies and chords, how should I start studying Jazz standards?
Comment: This has already been answered here: https://music.stackexchange.com/questions/49220/i-want-to-start-playing-jazz-music-where-should-i-start
Comment: Fakebooks are usually filled with chord symbols in addition to the melody, so maybe you should practise playing chords symbols too.
Comment: Does this answer your question? [I want to start playing jazz music, where should I start?](https://music.stackexchange.com/questions/49220/i-want-to-start-playing-jazz-music-where-should-i-start)
Comment: There are many valid approaches, making this question perfect for the chat room, but not a fit for the main site. In the chat room, the various approaches can be listed and discussed as needed.
Comment: If you want to do it like people used to, when jazz standards were made, you'll learn to play by ear and you listen to definitive recorded versions of the tunes, and play them by ear. I'm not convinced that reading real/fake books can lead to becoming a jazz musician. You _will_ need to be able to play by ear. I don't see any benefit in starting from anything else than playing by ear.
Answer: By listening to recordings.  'Jazz Standards' can refer to both songs from the American Songbook (Gershwin, Cole Porter, etc.) as well as songs written by jazz musicians (Ellington, Monk, Bill Evans, Joe Henderson, etc.).
For the former, the original musicals or movies these songs come from are a great place to start.  Then find jazz singers you like.  I would recommend Ella Fitzgerald.  For the latter, find tunes you want to learn and musicians you gravitate towards and check out the recordings.
As far as actually learning the tunes, the best way is to actually transcribe them yourself, lyrics, melody and chords.  In addition to developing your ear to hear melodic and harmonic relationships (which is important if you want to improvise), transcribing from recordings will also help you learn the phrasing used by singers, as opposed to just the quarter-note rhythms you might see in sheet music.  Fake books also can have errors.
Then you need to play with other musicians.


Find not event.target using querySelectorAll() :not()

Question: I have a group of elements that have 'click' event listeners attached.
When triggered, I want to find which elements are not the target of the event.
I've been using querySelectorAll() with :not(), but this selects all of the elements including the target:
https://codepen.io/wrgt1/pen/rNMqbpm?editors=1010

const thumbnail = document.querySelectorAll(".thumbnail");

thumbnail.forEach(function(thumb) {
  thumb.addEventListener("click", (e) => {
    const target = "." + e.target.classList[1];
    const notTarget = document.querySelectorAll(".thumbnail:not(target)");
    console.log(target);
    console.log(notTarget);
  });
});
#thumbnails {
  position: relative;
  display: flex;
}

.thumbnail {
  height: 100px;
  width: 100px;
  margin: 10px;
  background: #FF7400;
  cursor: pointer;
}

Project 1

Project 2

Project 3

Comment: You did not insert the _value_ of the variable `target` into your selector, you put the _static text_ `target` into it. None of your `.thumbnail` elements has the _tag name_ `target`, so this selects all of them …
Answer: target is a variable and needs to be concatenated into the selector:

const thumbnail = document.querySelectorAll(".thumbnail");

thumbnail.forEach(function(thumb) {
  thumb.addEventListener("click", (e) => {
    const target = "." + e.target.classList[1];
    const notTarget = document.querySelectorAll(".thumbnail:not(" + target + ")");
    console.log(target);
    console.log(notTarget);
  });
});
#thumbnails {
  position: relative;
  display: flex;
}

.thumbnail {
  height: 100px;
  width: 100px;
  margin: 10px;
  background: #FF7400;
  cursor: pointer;
}

Project 1

Project 2

Project 3

Comment: That will break if the project class moves
Comment: @mplungjan yep of course, but just a direct correction of the OP code. Your solution is of course the one we'd all pick!
Answer: If you delegate you can do this

const container = document.getElementById("thumbnails");
container.addEventListener("click", function(e) {
  const tgt = e.target.closest("div"); // handle clicks inside the divs too
  if (tgt.classList.contains("thumbnail")) {
    console.log(tgt.textContent, "clicked");
    const thumbs = [...container.querySelectorAll(".thumbnail")]; // here in case thumbs are added
    const others = thumbs.filter(thumb => thumb !== tgt); // this is what you wanted
    const texts = others.map(thumb => thumb.textContent);
    console.log(texts, "not clicked");
  }
});
#thumbnails {
  position: relative;
  display: flex;
}

.thumbnail {
  height: 100px;
  width: 100px;
  margin: 10px;
  background: #FF7400;
  cursor: pointer;
}

Project 1

Project 2

Project 3

Answer: What you want to do here is select all the other elements that match your criteria, then run through them and exclude the event.target, i.e. the current element.
const allSiblings= allThumbnailsArray.filter( element => element != target);
Made a codepen for you here:
https://codepen.io/pghiran/pen/mdrzYYO?editors=1010
You shouldn't use a new query with a "not" selector because that's not reliable as classes are not made for identifying elements, but classifying or grouping them(i.e. if you have 2 sections with thumbnails, you'll exclude thumbnail project4 from both of them) if you're working with classes, and it's also more costly(slow) than processing an array.
Comment: Who says that :not() was "not reliable with classes"? You might have some specific case in mind here, but as an across-the-board statement, this is simply not true.
Comment: I already [suggested that](https://stackoverflow.com/a/65704199/295783) but delegated and posted the code here instead using the snippet editor
Comment: @mplungjan well, haven't noticed that but this answer is more geared towards the reasoning behind the change, not just slapping the code together for a quick reply. Also, your answer seems to be incorrect as it uses the event handler differently, which means clicking other children or grand children (and so on) or clicking the blank space between the thumbnails triggers the function which can lead to issues.
Comment: @CBroe true, I might've expressed my point incorrectly, sorry about that.
Comment: @PaulGhiran That clicking inside or outside took less time to fix than writing this comment. I delegate which is recommended over adding a listener to every single element and not handling if new elements are added later
Comment: No, it really isn't. It's better in some cases, and worse in others. Delegation isn't a silver bullet. (nor is it a part of the question)
Comment: Whenever there is a loop and addEventListener, the silver bullet IS delegation - especially if you need to process siblings


Radiobuttonlist check is checked

Question: How to check radiobuttonlist is selected or not using jQuery
if ($("#<%=rblMaritalStatus.ClientID %> input[type=radio]:checked").length < 0) {
    $(".error").text('Select at least one marital satus');
    $("#ConfirmationModal").modal('show');
    return false;
}

Comment: @Satpal OP wants to execute that block if length === 0.. :|
Answer: You could use JQuery is, to check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. Since input[type=radio]:checked is single selection it nicely fits this purpose.
if ($("#<%=rblMaritalStatus.ClientID %>").is('input[type=radio]:checked')) {
    $(".error").text('Select at least one marital satus');
    $("#ConfirmationModal").modal('show');
    return false;
}

Comment: **Thank you** @LIUFA you are right i had just common mistake
Answer: Try bellow code it could help you
    if ($("#<%=rblMaritalStatus.ClientID %> input:radio").is(":checked")) {
$(".error").text('Select at least one marital satus');
$("#ConfirmationModal").modal('show');
return false;
}

Radiobuttonlist check is checked


dpkg error installing on Ubuntu 10.04

Question: I'm trying to install the nginx on ppa:nginx/stable on Lucid after removing the one that comes from the default sources but I get this error:

` Setting up nginx-common (0.8.54-4ppa13~lucid) ...
dpkg: error processing nginx-common (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of nginx-full:
 nginx-full depends on nginx-common (= 0.8.54-4ppa13~lucid); however:
  Package nginx-common is not configured yet.
dpkg: error processing nginx-full (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of nginx:
 nginx depends on nginx-full; however:
  Package nginx-full is not configured yet.
dpkg: error processing nginx (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 nginx-common
 nginx-full
 nginx`

I've try apt-get clean, dpkg --configure -a, apt-get -f install nginx-common but nothing is helping. Am I missing something?
Here's the output from dpkg-query -W -f='${Package}\t${Version}\n' nginx*

`nginx   0.8.54-4ppa13~lucid
nginx-common    0.8.54-4ppa13~lucid
nginx-extras
nginx-full      0.8.54-4ppa13~lucid
nginx-light`
Comment: Ran into this issue. apt wouldn't configure nginx-full because Apache was already running on port 80. `sudo service apache2 stop` fixed the problem, nginx successfully installed.
Answer: Edit /var/lib/dpkg/info/nginx-common.postinst, comment "chmod -f 0640 $logdir/*" line. Then run install:
sudo apt-get install nginx

Or create file access.log:
sudo touch /var/log/nginx/access.log
sudo apt-get install nginx

/var/lib/dpkg/info/nginx-common.postinst:
    chmod 0750 $logdir
#    chmod -f 0640 $logdir/*
    ;;

I write small note(Russian language!)
Comment: sudo mkdir /var/log/nginx && sudo touch /var/log/nginx/access.log && sudo apt-get install nginx
Comment: test -d /var/log/nginx/ || sudo mkdir /var/log/nginx && sudo touch /var/log/nginx/access.log && sudo apt-get install nginx. if /var/log/nginx exist, touch and apt-get don't run.
Comment: Awesome, thanks! It worked perfectly. Commenting out `chmod -f 0640 $logdir/` fixed the isssue
Answer: The postinst script, which runs at the end of the nginx-common installation, encountered an error. You can find the script at /var/lib/dpkg/info/nginx-common.postinst. If you look at this script and can figure out what is failing, you can report the problem to the maintainers of ppa:nginx/stable.

dpkg error installing on Ubuntu 10.04


Does the idea of 'Class' in C++/C#/Java come from struct in C?

Question: I had this doubt long time ago. The dot operator is first used in struct in C. Is the idea of Class or the design of Class based on struct in C? Actually I highly doubt it is, just haven't seen any official doco about this.
EDIT: What I am asking is if the idea of creating Class syntax (in C++) comes from struct in C, not why C is not an OOP language!
Comment: Have you read the book Object-oriented programming with ANSI-C?? What I am asking is if the idea of creating Class syntax comes from struct in C, not why C is not an OOP language!
Comment: Struct in C has a lot less capabilities. C is not an OOP language
Comment: struct and class coexist in the oop world
Answer: No1.
While the syntax is vaguely similar, that's just syntax. The concepts of "classes" and "objects" predate C by several years2.
Simula was developed during the 60's:

Simula is a name for two simulation programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo ..
Simula 67 introduced objects, classes, inheritance and subclasses, virtual methods, coroutines, discrete event simulation, and features garbage collection. Subtyping was introduced in Simula derivatives.
Simula is considered the first object-oriented programming language. As its name implies, Simula was designed for doing simulations, and the needs of that domain provided the framework for many of the features of object-oriented languages today ..
The influence of Simula is often understated, and Simula-type objects are reimplemented in C++, Java and C#. The creator of C++, Bjarne Stroustrup, has acknowledged that Simula 67 was the greatest influence on him to develop C++ ..

1 Even though some concepts can be emulated in C, this does not imply that Object-Oriented Programming originated from, or is a result of, C structs or implementation.
2 Simula 67 was formally standardized in 1968, while the "the most creative period" in C development wasn't until 1972 when support for structs was added. The de-facto early standard for C ("The C Programming Language") wasn't published until 1978.
Comment: sure. to complete answer : C birth is 1972. even ancestor B was not earlier than 1969.
Comment: ["C++ got the key notions of classes, derived classes, virtual functions (in other words, the notions of encapsulation, inheritance and polymorphism) from Simula just like Smalltalk did."](http://www.stroustrup.com/bs_faq.html#from-Smalltalk)
Comment: @philippelhardy Thanks. I added more refined dates to the answer.
Answer: In early versions of C++ (or C with Classes), an object was directly implemented with struct. When you used cfront you could see it. Now it might be, but that's implementation dependent. As for the syntax, I believe it comes from algol (but I'm not certain).


PIVOT or PIVOT XML without listing the columns explicitly on Oracle

Question: I am working on PL/SQL Developer v10 on Oracle 11g database.
The idea is instead of writing 145 columns listed in PIVOT statement write an Pivot XML and get data from there, I am working on a basis of this answer, as I have never done PIVOT XML before on Oracle so my expectations might be wrong
select * from (
                    select
                      tqs.transactiondetailid as transactiondetailid,
                      q.productid as productid,
                      tqs.answer as QAnswer,
                      regexp_substr(q.questiondescription,'(WIF|DT|WT)[([:digit:]|.)]*') as QDesc,
                      tqs.transactionversion as transactionversion
                    from TRANSACTIONDETAILQS tqs
                    inner join question q on q.questionid = tqs.questionid and (
                          q.questiondescription like 'DT%'
                          or  q.questiondescription like 'WT%'
                          or q.questiondescription like 'WIF%')
    ) pivot xml(
    min(QAnswer) for QDesc in (
    select regexp_substr(q.questiondescription,'(WIF|DT|WT)[([:digit:]|.)]*') as r from question q
    where regexp_substr(q.questiondescription,'(WIF|DT|WT)[([:digit:]|.)]*') IS NOT NULL)
    )

in XML column does not return any data they all are empty, however following statement where I list columns explicitly works just fine
select * from (
                    select
                      tqs.transactiondetailid as transactiondetailid,
                      q.productid as productid,
                      tqs.answer as QAnswer,
                      regexp_substr(q.questiondescription,'(WIF|DT|WT)[([:digit:]|.)]*') as QDesc,
                      tqs.transactionversion as transactionversion
                    from TRANSACTIONDETAILQS tqs
                    inner join question q on q.questionid = tqs.questionid and (
                          q.questiondescription like 'DT%'
                          or  q.questiondescription like 'WT%'
                          or q.questiondescription like 'WIF%')
    ) pivot (
    min(QAnswer) for QDesc in (
    'DT01.','DT02.','WT01.')
    )

How to pivot without listing the columns explicitly?
Comment: not certain, but your `regexp_substr(q.questiondescription,'(WIF|DT|WT)...` may be wrong. What happens if you reduce the complexity, and try to output just one column name as match, before trying to get all of them? Good luck.
Comment: @shellter 9 months later I figured out where the problem lies, see update. :)
Answer: I boiled it down to the problem of
min(QAnswer) for QDesc In (
    select 'DT01.','DT02.','WT01.' from dual )
)

not working, but
min(QAnswer) for QDesc In (
    'DT01.','DT02.','WT01.')
)

working fine.
One way to do this is create dynamic PL/SQL but I don't have enough courage to do this.