Why a decision tree can't learn this simple rule?

Question: I wonder which ML algorithm is able to learn the appearently simple rule:
If [category] == 1 Then [A]
Below a demo script with an input variable [A] that contains noise, but if [category] == 1 then [A] matches exactly the target variable. Even after 5000 samples it doesn't get the rule right.
Which ML algorithm would you recommend that is able to learn that rule in a regression problem?
from math import floor, ceil
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeRegressor

seq_length = 6
rows = 5000
max_value = 100
test_data_factor = 0.2

input = pd.DataFrame(np.random.uniform(0, max_value, size=(rows)), columns=["target"])
input["category"] = (list(range(1, seq_length + 1)) * ceil(rows / seq_length))[:rows]

def f_a(row):
    if row["category"] == 1:
        return row["target"]
    else:
        return row["target"] * np.random.uniform(0.8, 1.2)

input["A"] = input.apply(f_a, axis=1)

cnt_input_data = len(input.index)
rows_test_data = floor(cnt_input_data * test_data_factor)
rows_train_data = cnt_input_data - rows_test_data

train_data = input.head(rows_train_data)
test_data = input.tail(rows_test_data)

model = DecisionTreeRegressor()
model.fit(train_data.drop("target", axis=1), train_data["target"])
test_data["pred"] = model.predict(test_data.drop("target", axis=1))

print(test_data[test_data["category"] == 1])

Comment: It looks like you have a randomly-generated input category variable, and a randomly generated target variable. When the category is 1, the true output is just the target variable, but if it's not, the true output is some scaling between 0.8 and 1.2 times the target. But the target is still just a random number at heart - there is no link between category and target, since the target is always random no matter what - choosing whether to return the random number or some scaling of a random number doesn't change anything. You're asking an ML algorithm to predict a randomly generated number, no?
Comment: category is a sequence, target is a random number and column A matches exactly the target if category==1. So even when the target is a random number, there is a very simple rule that enables the prediction of that target exactly if category==1. Obviously the tree is not able to learn it, I wonder if there are other methods that can do this?
Comment: OK, so the input consists of the category *and* column A? That makes more sense.
Comment: yes exactly category and A are both inputs
Answer: The reason that the Decision Tree does poorly here is the algorithm isn't equipped to deal with the situation you're throwing at it. You need to understand how a CART model gives its predicted output value for a continuous response.
You fit a CART model to the response target, predicted by inputs category and A. You want the decision tree to learn the rule if category == 1, predict target = A. But all the classical CART algorithm can do is partition the space based on the input values, and then output a final predicted value based on the responses only (target) that fall into the given partition; it doesn't incorporate predictor information like you want it to in the final prediction. So it can only do things like if category == 1, predict target = (mean target of all observations with category == 1). Since the observations that fall into category 1 are just uniform random variates, you won't do very well predicting their value by grouping them up and just taking the mean, right?
Sounds like a "model-tree" based approach might be more appropriate (disclaimer: I'm not an expert in these). In the terminal node of the tree, instead of simply predicting the mean of all values falling into that node (like CART), model-trees fit a linear model to all observations in the terminal node, using all predictors that gave rise to the splits that define that terminal node (that's a mouthful, I know, not sure how else to say it).
I'll give an example in sloppy R code (sorry, too nooby in Python) wherein I:

setup dummy data
fit a CART model to show how bad it is
fit a Cubist model to show that it fits well on the category == 1 data and poorly on the category != 1 data

Step 1: Setup data
set.seed(111)

library(rpart) # CART model
library(Cubist) # model-trees model

seq_length = 6
rows = 30000
max_value = 100
test_data_factor = 0.2

df <- data.frame(category = as.character(rep(1:seq_length, length.out = rows)),
                 target = runif(rows, 0, max_value))

df$A <- df$target
for(i in 1:rows) if(df$category[i] != 1) df$A[i] <- df$A[i] * runif(1, 0.8, 1.2)

test_ind <- 1:floor(test_data_factor * nrow(df))

training <- df[-test_ind, ]

test <- df[test_ind, ]
test_1 <- test[test$category == 1, ] # Test observations w/ cat 1
test_not1 <- test[test$category != 1, ] # Test observations w/ other categories

Step 2: Fit a CART model and show how crappy it is
treemod <- rpart(data = training, target ~ .)

treepred_1 <- predict(treemod, newdata = test_1) # CART predictions in category 1
treepred_not1 <- predict(treemod, newdata = test_not1) # CART predictions in other categories
print(paste0("Mean Absolute Error of CART Model in Category 1: ", round(mean(abs(treepred_1 - test_1$target)), 3)))
print(paste0("Mean Absolute Error of CART Model other Categories: ", round(mean(abs(treepred_not1 - test_not1$target)), 3)))

[1] "Mean Absolute Error of CART Model in Category 1: 4.061"
[1] "Mean Absolute Error of CART Model other Categories: 6.178

Step 3: Fit a Cubist model and show improvement in Category 1
cubistmod <- cubist(x = training[ , -2], y = training$target)

cubistpred_1 <- predict(cubistmod, newdata = test_1)
cubistpred_not1 <- predict(cubistmod, newdata = test_not1)

print(paste0("Mean Absolute Error of Cubist Model in Category 1: ", round(mean(abs(cubistpred_1 - test_1$target)), 3)))
print(paste0("Mean Absolute Error of Cubist Model other Categories: ", round(mean(abs(cubistpred_not1 - test_not1$target)), 3)))

[1] "Mean Absolute Error of Cubist Model in Category 1: 0.01"
[1] "Mean Absolute Error of Cubist Model other Categories: 4.434"

So the test error in category 1 has gone from about 4.1 to 0.01 by switching from CART to Cubist. The error is non-zero so it's not learning like a human might that if the category is 1, then just return A exactly. But perhaps the analyst might notice the minute error and consider that this is likely just numerical precision issues. Indeed, if you check summary(cubistmod), which lists the model splits and resulting models, you'll see among the rules:
if
    category = 1
    then
    outcome = 0 + 1 A

I'm not sure what other kinds of algorithms could help you out, but just some random thoughts: you could maybe check out association rule learning or literature in the data mining community ("data mining" being kind of a buzzword but this idea of finding hidden relationships among variables in the dataset seems to be a common motif in the lit of the self-professed miners)
Comment: fwiw, There were some discussions for model-based recursive partitioning in sklearn:  https://github.com/scikit-learn/scikit-learn/issues/11647
Comment: Thx. for sharing this I got the idea. I think model trees (M5) are a nice approach, unfortunately poorly supported in Python (sklearn). But honestly I am surprised that such simple interaction rules are obviously not an easy thing for standard ML methods.
Comment: @HansHupe This is kind of like complaining that a screwdriver doesn't do a very good job of driving nails. There are many types of machine learning models because there are many types of problems, and a model which does well against one problem may not do well against another type of problem. For more information, you may be interested in reading about the so-called "No Free Lunch Theorem." https://en.wikipedia.org/wiki/No_free_lunch_theorem
Comment: Sorry for complaining, but it looks like that no algorithm of the widely used ML toolbox sklearn in Python is able to learn that rule in a satisfying way (maybe MLPRegressor could but it would be overshooting I think and needs a lot of tuning). For me this structure of problem is a very practical challenge.
Comment: @HansHupe `sklearn` is convenient, but limiting yourself to the models that it implements will not give you very deep coverage of the kinds of problems you might need to solve. Indeed, you've discovered one such blindspot in the case of this problem.
Answer: This is not how decision trees work. Roughly speaking, decision tree splits data into bins (branches), conditionally on the features, and per each bin it predicts mean of the target variable. So for decision tree to predict something like identity function $y = f(y)$, you would need decision tree with the number of branches equal to the size of the data, i.e. one that literally memorized the data.


Graphing Polar Curves?

Question: So recently I ran into this problem, and I was very much stuck at the sight of it. I was wondering if there is an easy way to depict the polar curve of a specific function without necessarily having to graph points. Thanks!
Answer: We have $\displaystyle r=-\csc(t)=-\frac{1}{\sin(t)}$.
We multiply both sides by $\sin(t)$ to get $r\sin(t)=-1$.
By definition of polar coordinates, we have $r\sin(t)=y$.
So this graph in polar coordinates corresponds to $y=-1$, or option (B).
Comment: yep, simple and effective explanation.

Graphing Polar Curves?


build a graph with smallest diameter, N verteces, each vertex has degree $\ge k$

Question: I need to build a graph with number of vertexes N such that each vertex has degree at least k and the graph has the smallest diameter. I believe that this question should be well studied.
EDIT: yes complete graph is an answer, but not interesting. I am changing the question a little bit: each vertex has degree k.
Comment: This is almost a good question.  The problem is that it appears you have put almost no effort into the question yourself.  May I suggest including (a) necessary conditions on the existence of k-regular n-vertex graphs (b) resolving the 1-regular, 2-regular, (n-1)-regular and n-regular cases.  Note, that PhD theses are written about the [degree-diameter problem](http://en.wikipedia.org/wiki/Degree_diameter_problem), and this is not far off -- it might be difficult to answer this question just for 3-regular (cubic) graphs.
Answer: The complete graph on $N$ vertices, $K_N$, will be hard to beat.  If $k \gt N-1$ are you allowed multiple edges between a given pair of vertices?  I hope so.
Comment: well, k  < N - 1


Como colocar um efeito :focus na div

Question: Tenho 5 input e cada um fica dentro de um div, gostaria de saber como colocar um efeito focus em cada div que segura o input e ao clicar fora da div remover o efeito.

    Nome *
    <input type="text" name="nome" class="txt txt_nome" placeholder="seu nome..."

Comment: E porque você não usa o :focus no input? (Me parece que você terá de usar um css para pintar a borda da div, simulando um focus)
Comment: Porque  a `span` tem o efeito como se estivesse dentro do input, com CSS não tem como colocar o `focus` na `div`, creio que com `js` teria como só não sei como fazer
Comment: Possível duplicata de [Tem como usar o :focus em div?](https://pt.stackoverflow.com/questions/243448/tem-como-usar-o-focus-em-div)
Answer: Acho que o evento de foco na div não tem como aplicar.
Mas você poderá conseguir o que está buscando com javascript, utilizando esse exemplo ficaria assim:
function fOnFocus(){
     this.parentNode.classList.add("div-focus");
}

function fOnBlur(){
     this.parentNode.classList.remove("div-focus");
}

var inputs = document.querySelectorAll(".txt");

for (var indice = 0; indice < inputs.length; indice++) {
  var input = inputs[indice];
  input.onfocus = fOnFocus;
  input.onblur = fOnBlur;
}

Nesse caso bastaria criar uma classe div-focus no seu CSS.
Answer: Como dito no  post anterior "Se você der foco a div, não será possível dar foco ao input para digitar algo" a solução é aplicar um estilo a div simulando foco.
No HTML coloque nos ids das divs as respectivas classes CSS.
No script recupere esse valor a aplique na função addClass

$(document).ready(function(){
    $(".busca").click(function(){
       var status = $(this).attr('id');
       $(this).addClass(status);
    });

    $(document).mouseup(function(e){
    var container = $(".busca");
    if (!container.is(e.target))
    {
       //procura elementos cuja ID começa por uma dada string, neste caso estilo
       //https://api.jquery.com/attribute-starts-with-selector/
       $('div[id^="estilo"]').removeClass();
    }
 });

});
.estilo1{
    box-shadow: 0 0 36px rgba(0, 0, 238, 1);
    padding: 3px 0px 3px 3px;
    margin: 5px 1px 3px 0px;
    border: 2px solid rgba(255, 25, 10, 10);
    background-color: green !important;
}

.estilo2{
    box-shadow: 0 0 36px rgba(0, 0, 238, 1);
    padding: 3px 0px 3px 3px;
    margin: 5px 1px 3px 0px;
    border: 2px solid rgba(25, 255, 10, 10);
    background-color: red !important;
}

.estilo3{
    box-shadow: 0 0 36px rgba(0, 0, 238, 1);
    padding: 3px 0px 3px 3px;
    margin: 5px 1px 3px 0px;
    border: 2px solid rgba(25, 25, 10, 10);
    background-color: yellow !important;
}

.estilo4{
    border: 2px solid #96BED9;
    background-color: gray !important;
}

.estilo5{
    border: 4px solid #FF00FF;
    background-color: azure !important;
}

    Nome *
    <input type="text" name="nome" class="txt txt_nome" placeholder="seu nome...">

    Nome *
    <input type="text" name="nome" class="txt txt_nome" placeholder="seu nome...">

    Nome *
    <input type="text" name="nome" class="txt txt_nome" placeholder="seu nome...">

    Nome *
    <input type="text" name="nome" class="txt txt_nome" placeholder="seu nome...">

    Nome *
    <input type="text" name="nome" class="txt txt_nome" placeholder="seu nome...">

Nota: o efeito é clicando em qualquer parte da div e não em um elemento especifico dentro da div reveja post anterior
Comment: perfeito esse exemplo era oque eu precisava, só teria um problema, como remover o background quando o usuário clica fora da `div`?
Comment: ta legal amigo, você me ajudou bastante obrigado
Comment: @mayron2017, vou editar sua pergunta de modo a haver compatibilidade com a minha resposta!!

Como colocar um efeito :focus na div


C# Overriding the GetHashCode method

Question: In this example, the poster has overridden the get hash code method. I understand that this has been done in order to provide a better hash value for the returned object, to reduce the number of collisions, and therefore reduce the number of occasions it will be necessary to call Equals().
What i would like to know, is how this algorithm been calculated:
return 17 + 31 * CurrentState.GetHashCode() + 31 * Command.GetHashCode();

Is there a particular reason that the numbers in question were chosen? Could i have simply picked my own numbers to put into it?
Comment: Just for info, the MS C# compiler (for anon-types) uses a seed of `-1134271262`, and a multiplier of `-1521134295`. Just sayin'
Comment: @MarcGravell: Do you have the source for that?
Comment: @DeepSpace101 ILDASM ;p
Comment: @MarcGravell: I see the same `-1521134295` multiplier in ILDASM but the `seed` appears to be a composite seed (it's a random int32 multiplied by the same multiplier). So the seed's not only *NOT* prime (contrary to popular belief), it's also random based on the anon-type member names/type/count. Weird. Any ideas why?
Comment: @DeepSpace none. Interesting.
Answer: Generally you should choose primes. This helps you to avoid getting the same hash-value for different input parameters.
Answer: Prime numbers are usually used in hashcode computation to minimize the collisions. If you search for hashcode and prime numbers on this iste, you will find some detailed explanations on this (note that it is note language specific):

What is a sensible prime for hashcode calculation ?
Why does Java's hashCode() in String use 31 as a multiplier ?
Answer: You typically want to use prime numbers (as is done above) because it reduces the chance of collisions (two instances yielding same result). For more info, see: http://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/

C# Overriding the GetHashCode method


naming ids using Razor C# syntax

Question: I have a for loop in my razor document:
@for(var i = 0; i < Model.Content.Cars; i++)
{

 This is a car.

}

I am trying to get something like this:

 This is a car.

 This is a car.

 This is a car.

 This is a car.

How do I achieve this effect?
Answer: Put i in ()

 This is a car.

naming ids using Razor C# syntax


Syncing clock to external midi with iPad

Question: I am trying to integrate the ModStep iPad app into my setup.  I have a Moog Matriarch and a Moog Mother-32.  What I would like to do is sequence the Mother-32 using the ModStep iPad app and have the Matriarch use the same clock from ModStep.
I have successfully sequenced the Mother-32 using ModStep.  This is not using the Mother-32 clock (the sequencer on the Mother-32 is not running).  I have tried to get the Matriarch to use the same clock.  What I have tried is setting the assign output on the Mother-32 to be the sequencer clock and then patched that into the clock in on the Matriarch.  This results in no clock at all on the Matriarch, which makes sense because the sequencer on the Mother-32 is not running.
How can I get the iPad to be the master clock for both Mother-32 and the Matriarch?
Comment: Maybe a silly question but I've never used this kind of apps, how are you linking the iPad to the Mother? Adaptator toward MIDI-din or USB-MIDI, or something else?
Comment: I'm using a USB midi adapter with the Apple camera connection kit. It works well for connecting USB devices to iPad.
Comment: Neat, it works like an OTG so!
Answer: I see that there is no THRU MIDI on the Mother-32… But there is one on the Matriarch!
Why not connecting the Matriarch to Modstep, and then connecting the Mother to the Matriarch using the THRU MIDI port of the latest (and the MIDI in of the Mother)?
As the MIDI Thru is giving a copy of the received signal, both Moogs will be fed with the clock produced by ModStep.
Comment: @SteveH.  That's a start! This is weird, the midi clock is producing a lot of signal (24 per beat if I remember well) but normally that should not saturate the midi… The easiest way to check that is to output this MIDI on a computer if you have a sound card which is accepting MIDI signals…
Comment: Thanks for this- I tried this and got a bit closer but now I think I'm having a different issue.  I could set ModStep to send on Midi channel 8 and I set the Matriarch to ignore channel 8, so everything worked- the matriarch is seeing the midi clock signal from the iPad and the Mother-32 is playing the notes—- well, most of them.  That's the next issue I'm having- I've tried several apps and it always seems to be hit and miss about playing notes.  Just looping one bar has different results :(  Not sure if it is a problem with my USB adapter, but I'll keep looking.


isn't big Oh asymptotic notation {O(f(n)}the slowest runtime an algorithm can have?(it gives asymptotic upper bound which means slowest runtime)

Question: i was reading a book called "Introduction to algorithms" and they were analyzing an algorithm called Strassen's algorithm for matrix multiplication and it said this-
""one might at first think that any matrix multiplication algorithm must take omega(n3)time, since the natural definition of matrix multiplication requires that many mul-tiplications. You would be incorrect, however: we have a way to multiply matrices in O(n3) time.""
isn't O(n3) time slower than omega(n3) time.
as omega gives asymtotic lower bound means fastest runtime.
than why the book say that we can do it in O(n3) like it is faster tha omega(n3) time.
Comment: No, big oh does *not* mean worst-case, nor does omega means best case. Both big oh and big omega can be used to describe best/average/worst time/memory/error progression/...
Comment: Big omega is however a "tight bound" in the time complexity class, whereas big oh is not. For example if an algorithm runs in *O(n^2)*, you can as well say it runs in *O(n^3)*: https://en.wikipedia.org/wiki/Big_O_notation#Family_of_Bachmann%E2%80%93Landau_notations
Comment: Try to think of big O and big Omega as "at most" and "at least", then it makes sense: "You might think this dinner might take at least $30, but we have a way to have this dinner in less than $30."
Comment: i know it does not mean best case or worse case and that runtime is generally different for different cases. i just want to know that isn't O(n) a poorer runtime{the poorest runtime for that case (best/average/worst)} than big omega(n){the best runtime an algo can have for that particular case.}
Comment: @ElProfessor: no, the idea of *O(...)* is that if you take a look at the definition of it, it makes it very easy to "over exaggerate". For example an algorithm that runs linear is *O(n)*, but it is *O(n^2)*, *O(2^n)*, etc. as well. Since all these function dominate *O(n)*. Big omega, means that if you take the limit, the limit is greater than zero, but still dominates, so that means that if an algorithm runs linear, you can not say it runs *Omega(n^2)*, since then the limit is 0, it is thus a "smaller" set of functions than big oh.
Comment: okay,thanks for helping me but i still have one  doubt.  if someone asks to rate T1(n)=omega(n),T2(n)=O(n),T3(n)=theta(n) {for the same problem for eg, a matrix multiplication problem} in increasing or decreasing order.  than what will be the answer or is it just a wrong question to ask.
Comment: @ElProfessor: you can not say what the best one will be, all possible orders (from best to worst) all possible.
Comment: You can think of it as such: O(n) means "at most linear" (could be less, even constant), Omega(n) means "at least linear" (could be exponential) and Theta(n) means "about linear" (3*n is an example, (1+0.5*cos(n))*n is another). So asymptotically, and ignoring constant factors, O(n) would be at most as slow as Omega(n) and Theta(n), Omega(n) is at least as slow as O(n) and Theta(n), Theta(n) is as least as slow as O(n) and at most as slow as Omega(n). See https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/big-big-theta-notation for nice explanations.
Answer: First of all it is not true that, as people commonly seem to believe, Big-O is worst case, Big-Omega is best case, and Big-Theta is average case.
Big-O is an upper bound. We are often interested in an upper bound on the worst case so Big-O gets associated with worst case behavior, but we can also be interested in an upper bound on  average case behavior, etc.
When we are using asymptotic notation applied to running times, "higher" functions are worse so upper bounds are good. If the algorithm has an upper bound, O(n^3), time this is better than it having a lower bound, Ω(n^3), because a lower bound means that it could be worse, could be slower, that it is no better than the lower bound.


Php syntax error while trying to delete all rows or one row with same codes

Question: I'm writing a delete function in codeigniter. Users have two selection. Delete all or delete one row. I don't want to repeat same codes and I use a function like that. But there is an error ' Parse error: syntax error, unexpected T_ELSE'. How can I solve that problem? Only way to repeat codes?
public function _delete_port()
{
    if ($_GET['delete_all']):
        foreach ($_GET['delete_id'] as $delete_id):
    else:
        $delete_id = $_GET['delete_id'];
    endif;
        // Some controls
        // ...

        $this->db->delete('ma_port', array('id' => $delete_id));

    if ($_GET['delete_all']) :
        endforeach;
    endif;

    redirect($url);
}

Comment: You have no body following the `foreach():`.  The alternate flow control syntax (using the `if/endif foreach/endforeach` is not recommended outside of HTML templating.  Use proper bracketed control structures and this stuff becomes easy to spot. `if () {...} else {...}` and `foreach() {... }`
Comment: Oh wait a minute, what are you trying to do here? It almost looks like you are attempting to procedurally construct the PHP code by conditionally starting and ending loops.
Comment: @MichaelBerkowski I must repeat the codes? Is it only solution?
Comment: *nested and dirty... So CHEARS*
Comment: @revo I must repeat the codes? Is it only solution?
Comment: @curiosity4834 I think I understand what your code is trying to do and I'll translate it into a working answer to explain what went wrong...
Answer: The main issue facing your code seems to be a misunderstanding of how flow control works. The approach you have taken is to attempt to use the if / else / endif to construct how you want your code to look instead of what you want your code to do.
Your procedure is to use a loop if $_GET['delete_all'] is present as an array, and to otherwise use $_GET['delete_id'].  So first check the contents of the variables and then take the appropriate action.  The whole thing can be simplified by placing $_GET['delete_id'] into an array if $_GET['delete_all'] isn't there.
// Empty array we'll fill later
$delete_ids = array();

// If the delete_all array is available, use it as the array to delete from
if (isset($_GET['delete_all']) && is_array($_GET['delete_all'])) {
  $delete_ids = $_GET['delete_all'];
}
// Next if delete_id is present
else if (isset($_GET['delete_id'])) {
  // Place it into the array to use later
  $delete_ids[] = $_GET['delete_id'];
}
else {
  // Neither was set, you have an error state, so handle it however you need to
  // Redirect, display an error, whatever.
}

// Now loop over your array and perform the action.
// The array either contains the original array from $_GET['delete_all'] or the single element $_GET['delete_id']
// Or it may be empty entirely, and therefore won't do anything
foreach ($delete_ids as $delete_id) {
  $this->db_delete('ma_port', array('id' => $delete_id));
}

// And finish with your redirect
redirect($url);

Answer: That was so dirty, I should be a better translator thoguh:
public function _delete_port()
{
    if ($_GET['delete_all']):
        foreach ($_GET['delete_id'] as $delete_id):
            // Some controls
            // ...
            $this->db->delete('ma_port', array('id' => $delete_id));
        endforeach;
    else:
        $delete_id = $_GET['delete_id'];
        $this->db->delete('ma_port', array('id' => $delete_id));
    endif;
    redirect($url);
}


Form calculations skip previous

Question: I'm working on a calculation script and it works perfect in all versions of FX but in other browsers any total values that were already filled in are lost after submitting if any required fields were left blank.
On this form  ,if you select a Membership status near the top and then go down to Summary of entries and fill in two values the totals to the right and the grand total at the bottom(above "Are you human") calculates correctly.
If you submit the form the validation kicks in and if you fill in another value the grand total only reflects that value and not the previous two which are still there.
I'm stumped since it works great in FX. I've looked for some kind of a reason for a week but this cross browser stuff is tricky. Thanks for any input.
<code>        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

        <script>
        var jQ = $.noConflict(true);

        // version 7
        jQ( document ).ready(function() {

//***  Member calculations
jQ('input[name="Class1-3Total"]').prop('readonly', true);

jQ('select[name="member_status"]').on('click', function() {
      if(jQ(this).val() == "FULL MEMBER"){
       // jQ('#docContainer #item303').css("display","none");//this hides the member stable days
      // jQ('#docContainer item298').css("display","none");//this hides the breedshow_grandtotal
       }
   });

jQ('input[name="quantity_class1-3"]').on('keydown keyup', function() {
if(jQ.isNumeric(this.value)){
     var Class1_3Total = jQ(this).val() * 12;
  if(jQ('select[name="member_status"]').val() == "FULL MEMBER"){

        jQ('input[name="Class1-3Total"]').val(Class1_3Total);
        jQ('input[name="Class1-3Total"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
            jQ('input[name="Class1-3Total"]').val("");
        jQ('input[name="Class1-3Total"]').removeClass( "sum" );

   }
   calc_total();
 });

 jQ('input[name="class4_total"]').prop('readonly', true);
jQ('input[name="quantity_class4"]').on('keydown keyup', function() {
if(jQ.isNumeric(this.value)){
       var class4_total = jQ(this).val() * 12;
  if(jQ('select[name="member_status"]').val() == "FULL MEMBER"){

        jQ('input[name="class4_total"]').val(class4_total);
        jQ('input[name="class4_total"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
            jQ('input[name="class4_total"]').val("");
        jQ('input[name="class4_total"]').removeClass( "sum" );

   }
   calc_total();
});

    jQ('input[name="class19_total"]').prop('readonly', true);
    jQ('input[name="quantity_class19"]').on('keydown keyup', function() {
    if(jQ.isNumeric(this.value)){
       var class19_total = jQ(this).val() * 20;
  if(jQ('select[name="member_status"]').val() == "FULL MEMBER"){

        jQ('input[name="class19_total"]').val(class19_total);
        jQ('input[name="class19_total"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
            jQ('input[name="class19_total"]').val("");
        jQ('input[name="class19_total"]').removeClass( "sum" );

   }
   calc_total();
});

       jQ('input[name="moorbennhall_total"]').prop('readonly', true);
        jQ('input[name="quantity_moorbennhall"]').on('keydown keyup', function() {
        if(jQ.isNumeric(this.value)){
       var moorbennhall_total = jQ(this).val() * 16;
  if(jQ('select[name="member_status"]').val() == "FULL MEMBER"){

        jQ('input[name="moorbennhall_total"]').val(moorbennhall_total);
        jQ('input[name="moorbennhall_total"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
            jQ('input[name="moorbennhall_total"]').val("");
        jQ('input[name="moorbennhall_total"]').removeClass( "sum" );

   }
   calc_total();
});

       jQ('input[name="lakenview_total"]').prop('readonly', true);
        jQ('input[name="lakenview_quantity"]').on('keydown keyup', function() {
        if(jQ.isNumeric(this.value)){
       var lakenview_total = jQ(this).val() * 16;
  if(jQ('select[name="member_status"]').val() == "FULL MEMBER"){

        jQ('input[name="lakenview_total"]').val(lakenview_total);
        jQ('input[name="lakenview_total"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
            jQ('input[name="lakenview_total"]').val("");
        jQ('input[name="lakenview_total"]').removeClass( "sum" );

   }
   calc_total();
});

       jQ('input[name="foalclasses_total"]').prop('readonly', true);
        jQ('input[name="quantity_foals"]').on('keydown keyup', function() {
        if(jQ.isNumeric(this.value)){
       var foalclasses_total = jQ(this).val() * 8;
  if(jQ('select[name="member_status"]').val() == "FULL MEMBER"){

        jQ('input[name="foalclasses_total"]').val(foalclasses_total);
        jQ('input[name="foalclasses_total"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
            jQ('input[name="foalclasses_total"]').val("");
        jQ('input[name="foalclasses_total"]').removeClass( "sum" );

   }
   calc_total();
});

        jQ('input[name="total_allothers"]').prop('readonly', true);
        jQ('input[name="quantity_allothers"]').on('keydown keyup', function() {
        if(jQ.isNumeric(this.value)){
       var total_allothers = jQ(this).val() * 16;
  if(jQ('select[name="member_status"]').val() == "FULL MEMBER"){

        jQ('input[name="total_allothers"]').val(total_allothers);
        jQ('input[name="total_allothers"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
            jQ('input[name="total_allothers"]').val("");
        jQ('input[name="total_allothers"]').removeClass( "sum" );

   }
   calc_total();
});

       jQ('input[name="firstaid_total"]').prop('readonly', true);
        jQ('input[name="firstaid_quantity"]').on('keydown keyup', function() {
        if(jQ.isNumeric(this.value)){
       var firstaid_total = jQ(this).val() * 5;
  if(jQ('select[name="member_status"]').val() == "FULL MEMBER"){

        jQ('input[name="firstaid_total"]').val(firstaid_total);
        jQ('input[name="firstaid_total"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
            jQ('input[name="firstaid_total"]').val("");
        jQ('input[name="firstaid_total"]').removeClass( "sum" );

   }
   calc_total();
});
        jQ('input[name="catalogues_total"]').prop('readonly', true);
        jQ('input[name="quantity_catalogues"]').on('keydown keyup', function() {
        if(jQ.isNumeric(this.value)){
       var catalogues_total = jQ(this).val() * 4;
  if(jQ('select[name="member_status"]').val() == "FULL MEMBER"){

        jQ('input[name="catalogues_total"]').val(catalogues_total);
        jQ('input[name="catalogues_total"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
            jQ('input[name="catalogues_total"]').val("");
        jQ('input[name="catalogues_total"]').removeClass( "sum" );

   }
   calc_total();
});

//*******  Stable cost for members
        jQ('input[name="stables_days_total"]').prop('readonly', true);
    jQ('input[name="stables_days_required[]"],select[name="stable_reqd"]').on('change', function() {
           if(jQ('select[name="member_status"]').val() == "FULL MEMBER"){

           var values = new Array();
         jQ.each(jQ('input[name="stables_days_required[]"]:checked'), function() {
           values.push(jQ(this).val());

              if(values.length == 1){
                 var stabledays = 50;
              }else if(values.length == 2){
                 var stabledays = 80;
              }else if(values.length == 3){
                 var stabledays = 100;
              }

                if(stabledays > 0){
                jQ('input[name="days_stable"]').val(stabledays);
                }else{jQ('input[name="days_stable"]').val("");}

          if(jQ('select[name="stable_reqd"]').val() != "Please choose" && jQ('select[name="stable_reqd"]').val() == "ONE"){
                 var stable_reqd = 1;
             }else if(jQ('select[name="stable_reqd"]').val() != "Please choose" && jQ('select[name="stable_reqd"]').val() == "TWO"){
                 var stable_reqd = 2;
             }
              jQ('input[name="stables_days_total"]').val((stabledays*stable_reqd));
              if((stabledays*stable_reqd) > 0){
              jQ('input[name="stables_days_total"]').addClass( "sum" );

            }else{ jQ('input[name="stables_days_total"]').removeClass( "sum" );}
        });
        }
        calc_total();
  });
  //*** End of member stable calculations

 jQ('input[name="hogroast_total"]').prop('readonly', true);
jQ('input[name="quantity_hogroast"]').on('keydown keyup', function() {
if(jQ.isNumeric(this.value)){
       var hogroast_total = jQ(this).val() * 16;
  if(jQ('select[name="member_status"]').val() == "FULL MEMBER"){

        jQ('input[name="hogroast_total"]').val(hogroast_total);
        jQ('input[name="hogroast_total"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
            jQ('input[name="hogroast_total"]').val("");
        jQ('input[name="hogroast_total"]').removeClass( "sum" );

   }
   calc_total();
});

    jQ('input[name="electric_total"]').prop('readonly', true);
    jQ('input[name="quantity_hookup"]').on('keydown keyup', function() {
    if(jQ.isNumeric(this.value)){
       var electric_total = jQ(this).val() * 25;
  if(jQ('select[name="member_status"]').val() == "FULL MEMBER"){

        jQ('input[name="electric_total"]').val(electric_total);
        jQ('input[name="electric_total"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
            jQ('input[name="electric_total"]').val("");
        jQ('input[name="electric_total"]').removeClass( "sum" );

   }
   calc_total();
});

jQ('input[name="voluntary_donation"]').on('keydown keyup', function() {
if(jQ.isNumeric(this.value)){

  if(jQ('select[name="member_status"]').val() == "FULL MEMBER"){
        jQ('input[name="voluntary_donation"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
        jQ('input[name="voluntary_donation"]').removeClass( "sum" );

   }
   calc_total();
});
jQ('input[name="breed_totalamount"]').prop('readonly', true);
    function calc_total() {
      var sum_member = 0;
        jQ('.sum').each(function(){
        if(jQ.isNumeric(this.value)){
         sum_member += parseFloat(this.value);
          jQ('input[name="breed_totalamount"]').val(sum_member);
          jQ('input[name="breedshow_grandtotal"]').val(sum_member);
          }

        });
        if(!sum_member){

           jQ('input[name="breed_totalamount"]').val("");
          jQ('input[name="breedshow_grandtotal"]').val("");
          }
    }

    // ******* end of member calculations

  //*** Non-member calculations

    jQ('select[name="member_status"]').on('click', function() {
      if(jQ(this).val() == "Associate member/Non-member"){
        //jQ('#docContainer #item332').css("display","none");//this hides the non-member stable days
       // jQ('#docContainer item298').css("display","none");//this hides the breedshow_grandtotal
       }
   });
   jQ('input[name="Class1-3_none_T"]').prop('readonly', true);
jQ('input[name="quantity_class1-3_none"]').on('keydown keyup', function() {
if(jQ.isNumeric(this.value)){
     var Class1_3_none_T = jQ(this).val() * 17;
  if(jQ('select[name="member_status"]').val() == "Associate member/Non-member"){

        jQ('input[name="Class1-3_none_T"]').val(Class1_3_none_T);
        jQ('input[name="Class1-3_none_T"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
        jQ('input[name="Class1-3_none_T"]').val("");
        jQ('input[name="Class1-3_none_T"]').removeClass( "sum" );

   }
   calc_non_member_total();
 });

 jQ('input[name="Class4-4_none_T"]').prop('readonly', true);
jQ('input[name="quantity_class4_none"]').on('keydown keyup', function() {
if(jQ.isNumeric(this.value)){
       var Class4_4_none_T = jQ(this).val() * 17;
  if(jQ('select[name="member_status"]').val() == "Associate member/Non-member"){

        jQ('input[name="Class4-4_none_T"]').val(Class4_4_none_T);
        jQ('input[name="Class4-4_none_T"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
        jQ('input[name="Class4-4_none_T"]').val("");
        jQ('input[name="Class4-4_none_T"]').removeClass( "sum" );

   }
   calc_non_member_total();
});

     jQ('input[name="class19_none_T"]').prop('readonly', true);
    jQ('input[name="quantity_class19_none"]').on('keydown keyup', function() {
    if(jQ.isNumeric(this.value)){
       var class19_none_T = jQ(this).val() * 35;
  if(jQ('select[name="member_status"]').val() == "Associate member/Non-member"){

        jQ('input[name="class19_none_T"]').val(class19_none_T);
        jQ('input[name="class19_none_T"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
        jQ('input[name="class19_none_T"]').val("");
        jQ('input[name="class19_none_T"]').removeClass( "sum" );

   }
   calc_non_member_total();
});

         jQ('input[name="lakenview_none_t"]').prop('readonly', true);
        jQ('input[name="lakenview_quantity_none"]').on('keydown keyup', function() {
        if(jQ.isNumeric(this.value)){
       var lakenview_none_t = jQ(this).val() * 24;
  if(jQ('select[name="member_status"]').val() == "Associate member/Non-member"){

        jQ('input[name="lakenview_none_t"]').val(lakenview_none_t);
        jQ('input[name="lakenview_none_t"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
        jQ('input[name="lakenview_none_t"]').val("");
        jQ('input[name="lakenview_none_t"]').removeClass( "sum" );

   }
   calc_non_member_total();
});

       jQ('input[name="foalclasses_none_t"]').prop('readonly', true);
        jQ('input[name="quantity_foals_none"]').on('keydown keyup', function() {
        if(jQ.isNumeric(this.value)){
       var foalclasses_none_t = jQ(this).val() * 12;
  if(jQ('select[name="member_status"]').val() == "Associate member/Non-member"){

        jQ('input[name="foalclasses_none_t"]').val(foalclasses_none_t);
        jQ('input[name="foalclasses_none_t"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
        jQ('input[name="foalclasses_none_t"]').val("");
        jQ('input[name="foalclasses_none_t"]').removeClass( "sum" );

   }
   calc_non_member_total();
});

       jQ('input[name="allothers_none_t"]').prop('readonly', true);
        jQ('input[name="quantity_allothers_none"]').on('keydown keyup', function() {
        if(jQ.isNumeric(this.value)){
       var allothers_none_t = jQ(this).val() * 24;
  if(jQ('select[name="member_status"]').val() == "Associate member/Non-member"){

        jQ('input[name="allothers_none_t"]').val(allothers_none_t);
        jQ('input[name="allothers_none_t"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
        jQ('input[name="allothers_none_t"]').val("");
        jQ('input[name="allothers_none_t"]').removeClass( "sum" );

   }
   calc_non_member_total();
});

       jQ('input[name="firstaid_none_t"]').prop('readonly', true);
        jQ('input[name="firstaid_quantity_none"]').on('keydown keyup', function() {
        if(jQ.isNumeric(this.value)){
       var firstaid_none_t = jQ(this).val() * 5;
  if(jQ('select[name="member_status"]').val() == "Associate member/Non-member"){

        jQ('input[name="firstaid_none_t"]').val(firstaid_none_t);
        jQ('input[name="firstaid_none_t"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
        jQ('input[name="firstaid_none_t"]').val("");
        jQ('input[name="firstaid_none_t"]').removeClass( "sum" );

   }
   calc_non_member_total();
});

        jQ('input[name="catalogues_total_none"]').prop('readonly', true);
        jQ('input[name="quantity_catalogues_none"]').on('keydown keyup', function() {
        if(jQ.isNumeric(this.value)){
       var catalogues_total_none = jQ(this).val() * 4;
  if(jQ('select[name="member_status"]').val() == "Associate member/Non-member"){

        jQ('input[name="catalogues_total_none"]').val(catalogues_total_none);
        jQ('input[name="catalogues_total_none"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
        jQ('input[name="catalogues_total_none"]').val("");
        jQ('input[name="catalogues_total_none"]').removeClass( "sum" );

   }
   calc_non_member_total();
});

//*******  Stable cost for non members
        jQ('input[name="stables_days_none_t"]').prop('readonly', true);
    jQ('input[name="stables_days_required_none[]"],select[name="stable_reqd_none"]').on('change', function() {
           if(jQ('select[name="member_status"]').val() == "Associate member/Non-member"){

           var values = new Array();
         jQ.each(jQ('input[name="stables_days_required_none[]"]:checked'), function() {
           values.push(jQ(this).val());

              if(values.length == 0){
                 var stabledays = "";
              }else if(values.length == 1){
                 var stabledays = 70;
              }else if(values.length == 2){
                 var stabledays = 100;
              }else if(values.length == 3){
                 var stabledays = 120;
              }

                if(stabledays > 0){
                jQ('input[name="days_stable_none"]').val(stabledays);
                }else{jQ('input[name="days_stable_none"]').val("");}

          if(jQ('select[name="stable_reqd_none"]').val() != "Please choose" && jQ('select[name="stable_reqd_none"]').val() == "ONE"){
                 var stable_reqd = 1;
             }else if(jQ('select[name="stable_reqd_none"]').val() != "Please choose" && jQ('select[name="stable_reqd_none"]').val() == "TWO"){
                 var stable_reqd = 2;
             }
              jQ('input[name="stables_days_none_t"]').val((stabledays*stable_reqd));
              if((stabledays*stable_reqd) > 0){
              jQ('input[name="stables_days_none_t"]').addClass( "sum" );

            }else{ jQ('input[name="stables_days_none_t"]').removeClass( "sum" );}
        });
        }
        calc_non_member_total();

  });

//*** End of non_member stable calculations

jQ('input[name="hogroast_none_t"]').prop('readonly', true);
jQ('input[name="quantity_hogroast_none"]').on('keydown keyup', function() {
if(jQ.isNumeric(this.value)){
       var hogroast_none_t = jQ(this).val() * 16;
  if(jQ('select[name="member_status"]').val() == "Associate member/Non-member"){

        jQ('input[name="hogroast_none_t"]').val(hogroast_none_t);
        jQ('input[name="hogroast_none_t"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
        jQ('input[name="hogroast_none_t"]').val("");
        jQ('input[name="hogroast_none_t"]').removeClass( "sum" );

   }
   calc_non_member_total();
});

    jQ('input[name="quantity_hookup"]').on('keydown keyup', function() {
    if(jQ.isNumeric(this.value)){
       var electric_total = jQ(this).val() * 25;
  if(jQ('select[name="member_status"]').val() == "Associate member/Non-member"){

        jQ('input[name="electric_total"]').val(electric_total);
        jQ('input[name="electric_total"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
        jQ('input[name="electric_total"]').val("");
        jQ('input[name="electric_total"]').removeClass( "sum" );

   }
   calc_non_member_total();
});

jQ('input[name="voluntary_donation"]').on('keydown keyup', function() {
if(jQ.isNumeric(this.value)){

  if(jQ('select[name="member_status"]').val() == "Associate member/Non-member"){
        jQ('input[name="voluntary_donation"]').addClass( "sum" );

   }
   }else if(!jQ(this).val()){
        jQ('input[name="voluntary_donation"]').removeClass( "sum" );

   }
   calc_non_member_total();
});

    function calc_non_member_total() {
      var sum_non_member = 0;
        jQ('.sum').each(function(){
        if(jQ.isNumeric(this.value)){
         sum_non_member += parseFloat(this.value);
          jQ('input[name="breed_totalamount"]').val(sum_non_member);
          jQ('input[name="breedshow_grandtotal"]').val(sum_non_member);
          }
        });
        if(!sum_non_member){

           jQ('input[name="breed_totalamount"]').val("");
          jQ('input[name="breedshow_grandtotal"]').val("");
          }
    }

});</script>
</code>
Comment: How can we possibly know what's wrong? You didn't provide any piece of code. It's like saying "My car har a problem" and expecting the miracle answer from the mechanic. Besides, what is FX?
Comment: FX= Firefox. It always works in every version but Chrome for example loses those previous values and calculates on anything added after the validation.
Answer: I ended up getting the above script to work in all browsers after doing some more testing and finding out that the validation script that was being provided by another source was the ultimate issue that was tripping up Chrome. We made some tweaks to that to reduce the number of errors it would show to one and changed the position of my calculation script in the head of the page in relation to the other provided scripts. For others that have browser compatibility issues keep digging and trying different things to eliminate and or pinpoint where the issue is coming from.

Form calculations skip previous


Is it possible to generate 0 to 100 as selection for select_tag?

Question: I have the input field just like this code now.
But I want to make select tag in which I can choose the number from 0 up to 100.
Is there any way to generate that select tag easily?
<%= f.number_field :age %>

Answer: Something like below:
<%= f.select :age, (0..100).to_a.map{|n| [n, n]} %>

Answer: select("user[]", "age", 0..100.to_a.map{|n| [n, n]}, {}, { :index => nil })

or
f.select :age, options_for_select( 0..100.to_a.map{|n| [n, n]}, @object.age )

Comment: get rid of your array and use (1..100).to_a. Rails will do the string conversion
Answer:  <%= f.select("person", "age", [1..100], { :include_blank => true })%>

Answer: <%= f.select :age, options_for_select((0..100).to_a) %>

Comment: Please provide some exmplanation of what is happening here - don't just post code.


(Python) tenho tambem um arquivo de texto com algumas palavras

Question: def carrega_palavras():
with open("palavras.txt", 'r', encoding='utf-8') as arquivo:
    palavras = []

    for linha in arquivo:
        linha = linha.strip()
        palavras.append (linha)
return palavras

def palavra_lower(palavras):
palavras_lower = []
for palavra in palavras:

palavras_lower.append(
palavra.lower())
return palavra_lower

def analisa_letras(palavra_lower):
aparicoes = Counter(palavra_lower())
total_de_caracteres = sum(aparicoes.values())

proporcoes = [(letra, frequencia / total_de_caracteres) for letra, frequencia in aparicoes.items()]
proporcoes = Counter(dict(proporcoes))
mais_comuns = proporcoes.most_common(15)
for caractere, proporcao in mais_comuns:
  print("{} → {:.2f}%".format(caractere, proporcao * 100))

palavras = carrega_palavras()
palavra_lower(palavras)
analisa_letras(palavra_lower)

Comment: Exatamente qual é a pergunta?
Answer: Tudo indica que você está tentando calcular o histograma dos caracteres das palavras contidas no arquivo de entrada.
Assumindo que seu arquivo de entrada seja algo como:
Lorem
Ipsum
Dolor
Sit
Amet
Consectetur
Adipiscing
Elit
Etiam
Aliquet
Urna
Vitae
Ipsum
Ullamcorper
Aliquam

Seu código pode ser ajustado da seguinte forma:
from collections import Counter

with open('./palavras.txt', 'r', encoding='utf-8') as arq:
    palavras = [linha.strip().lower() for linha in arq]

aparicoes = Counter(''.join(palavras))

proporcoes = {caractere : aparicoes[caractere] / len(aparicoes) * 100.0 for caractere in aparicoes}

mais_comuns = sorted(proporcoes.items(), key=lambda x: x[1], reverse=True)[0:15]

for caractere, proporcao in mais_comuns:
    print("{} → {:.2f}%".format(caractere, proporcao))

Saída:
i → 64.71%
e → 52.94%
a → 52.94%
t → 47.06%
l → 41.18%
m → 41.18%
u → 41.18%
r → 35.29%
o → 29.41%
s → 29.41%
p → 23.53%
c → 23.53%
n → 17.65%
d → 11.76%
q → 11.76%

Veja funcionando no Repl.it


How useful is spectrum analysis when transcribing music?

Question: When the Spectrum Analyzer window is open in Cubase, I can hover the mouse over the graph and a little white circle tracks the graph, telling me the note name corresponding to each peak.
Is there any easy way to tell whether that note name is an actual fundamental note or is a harmonic of a lower-pitched note? Currently I'm certain I've got more peaks than there are notes in the chord…
BTW when I transcribe I start with my ears then use SA to confirm what I think I'm hearing. SA isn't my primary transcription technique.
Answer: You're right, spectrum analysis is not as much use as we might hope!   And it's best on simple material that is simply analysed by ear.
But there are different ways of presenting a spectrum.   Cubase probably aims at the engineer looking to e.q. a recording.  A musician looking to transcribe notation needs a different approach.  Do you know Transcribe!?   The spectrum display coupled with 'Note guesses' is rather neat.  In this example it's pretty clear we're hearing a F major chord.   (It's only fair to say that results aren't always so clear-cut!)
(Other transcription utilities are available.)
https://www.seventhstring.com
Comment: Anecdotally, I've found the spectrum useful for confirming my "guesses" for low bass notes that are overshadowed by drums, but otherwise it's not very useful.


Multi line chart from mysql data c3

Question: I have a mysql table with date, hour of day and a parameter value. I want to display a graph with hour of day as x-axis and multiple lines, one for each day. I have got the data into json format, how can i display multiple lines, one for each day in c3.js ?
json format: [
    {"hour":"00:00:00","day":"2017-04-18","kpi":"41.54"},
    {"hour":"01:00:00","day":"2017-04-18","kpi":"0.00"},
    {"hour":"02:00:00","day":"2017-04-18","kpi":"0.00"},
    {"hour":"03:00:00","day":"2017-04-18","kpi":"0.00"},
    {"hour":"04:00:00","day":"2017-04-18","kpi":"0.00"},
    {"hour":"05:00:00","day":"2017-04-18","kpi":"0.00"},
    {"hour":"06:00:00","day":"2017-04-18","kpi":"31.94"},
    {"hour":"07:00:00","day":"2017-04-18","kpi":"47.44"},
    {"hour":"08:00:00","day":"2017-04-18","kpi":"35.05"},
    {"hour":"09:00:00","day":"2017-04-18","kpi":"43.24"},
    {"hour":"10:00:00","day":"2017-04-18","kpi":"32.40"},
    {"hour":"11:00:00","day":"2017-04-18","kpi":"32.03"},
    {"hour":"12:00:00","day":"2017-04-18","kpi":"37.22"},
    {"hour":"13:00:00","day":"2017-04-18","kpi":"30.85"},
    ...
    {"hour":"00:00:00","day":"2017-04-19","kpi":"44.88"},
    {"hour":"01:00:00","day":"2017-04-19","kpi":"0.00"},
    {"hour":"02:00:00","day":"2017-04-19","kpi":"0.00"},
    {"hour":"03:00:00","day":"2017-04-19","kpi":"0.00"},
    {"hour":"04:00:00","day":"2017-04-19","kpi":"0.00"},
    {"hour":"05:00:00","day":"2017-04-19","kpi":"0.00"},
    {"hour":"06:00:00","day":"2017-04-19","kpi":"38.75"},
    {"hour":"07:00:00","day":"2017-04-19","kpi":"40.03"},
    {"hour":"08:00:00","day":"2017-04-19","kpi":"37.36"}
]

Answer: Looking at the Timeseries example, you can make a chart that shows hours of the day:
var xHours = ['myXValues', "00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"],
    timeFormat = '%H:%M';

var chart = c3.generate({
    bindto: '#chart',
    data: {
        x: 'myXValues',
        xFormat: timeFormat,
        columns: [
            //xHours,
            //['test', 30, 20, 10, 40, 15, 25],
        ],
    },
    axis: {
        x: { type: 'timeseries' }
    }
});

Then you need to split that long json array: For each day, create an array that contains that date's kpi values.
Finally, load each of those smaller arrays into the chart (chart.load()).
Example with added comments: https://codepen.io/Sphinxxxx/pen/BRLPwP?editors=0010

Multi line chart from mysql data c3


Harvard MIT math question

Question: Let P be a point selected uniformly at random in the cube $[0, 1]^3$. The plane parallel to x+y+z = 0
passing through P intersects the cube in a two-dimensional region R. Let t be the expected value of
the perimeter of R. If $t^2$ can be written as $\frac{a}{b}$, where a and b are relatively prime positive integers,compute 100a + b
Let me know if the solution below is right?
Let $x_1,y_1,z_1$ be any point P in the cube.
The plane that passes through the point parallel to x+y+z 0
is ($x+y+z=x_1+y_1+z_1 = t$)
This plane cuts the x axis at say (x,0,0) then x = t and the point is (t,0,0)
This plane cuts the y axis at say (0,y,0) then y = t and the point is (0,t,0)
This plane cuts the z axis at say (0,0,z) then z = t and the point is (0,0,t)
The region of intersection is an equilateral triangle whose perimeter is given to be $P = 3\sqrt{2t^2} = 3\sqrt{2}t$
Was it a fluke that i hit the correct answer or is the rationale correct?
$E(P) = 3\sqrt{2}\int_{0}^{1}\int_{0}^{1}\int_{0}^{\sqrt{3}-x_1-y_1} (x_1+y_1+z_1)dz_1dy_1dx_1 = \frac{11}{2\sqrt{2}}$.  After extraction the answer is $12108$
Comment: Could you write the details of your evaluation of your integral ? I did not find the same result.
Comment: I evaluated in wolfram alpha.  Here is the evaluation. https://www.wolframalpha.com/input/?i=%5Cint_%7B0%7D%5E%7B1%7D%5Cint_%7B0%7D%5E%7B1%7D%5Cint_%7B0%7D%5E%7B%5Csqrt%7B3%7D-x-y%7D+%28x%2By%2Bz%29dzdydx
Comment: Wolfram alpha evaluates this integral as $\frac{11}{12}$, not $\frac{11}{2\sqrt{2}}$, so you did not get the right answer. I think the whole premise of this question is flawed.
Comment: In wolfram alpha, I did not multiply $3\sqrt{2}$.  After multiplying, I get $\frac{11}{2\sqrt{2}}$
Comment: It came in a contest, I doubt it to be flawed, but could be!!
Comment: OK, I see. I'll have to think a bit more about how this gets the right answer (while, at first sight, it shouldn't). I mean, the rational is wrong, but the coincidence is still amusing.
Comment: The rational is it slices the cube from 0 and spans across the diagonal of the cube and that is the reason why I chose $\sqrt{3}$  where $x+y+z = \sqrt{3}$ which is a plane parallel to x+y+z=0.  I initially thought, mine was correct but then at the vertex (1,1,1) it should satisfy x+y+z = 3 but it does not.
Comment: Mine could still be right, whenever a plane slice the cube, all the points in the plane is covered, at x+y+z=0, it touches the cube at the origin, slowly it progresses to slice the cube from the origin in not the z direction but diagonally at each increment forming the initial tetrahedron.  The base of which is equilateral triangle. Again at x+y+z=2 and above it forms a tetrahedron.  In the middle, if forms annexation of two tetrahedrons annexed on their bases to form triangular antiprism.
Comment: annexation of two square bipyramids ( not tetrahedrons)
Comment: A simple issue with your integral is that in a naive approach $x$, $y$ and $z$ belong to $[0,1]$: they are the coordinates of the random point. In your integral, $z$ may take negative values (e.g. $x=y=1$, $z=\sqrt{3}-2$), and I don't see how to interpret these.
Answer: If you take a unit cube and try to cut it along a plane $x + y + z = r$, then you will notice that the two-dimensional region can be two different shapes.
More precisely, if $r \leq 1$ or $r \geq 2$ (which are symmetric via $x, y, z \mapsto 1 - x, 1 - y, 1 - z$), then the region $R$ is a triangle with side length $\sqrt 2 r$ or $\sqrt 2 (3 - r)$, respectively. Thus $R$ has perimeter $3\sqrt 2 r$ and area $\frac {\sqrt 3} 2 r^2$ when $r \leq 1$ (and symmetrically when $r \geq 2$).
If $1 < r < 2$, then the region $R$ will be a hexagon, whose angles are all $120^\circ$ and whose side lengths are $\sqrt 2(r - 1)$ and $\sqrt 2(2 - r)$, alternatively. In this case, $R$ has perimeter $3\sqrt 2$ and area $\frac{\sqrt 3}2 (-2r^2 + 6r - 3)$.
Since the point $P$ is chosen uniformly in the cube, the probability density of the plane being $x + y + z = r$ is proportional to the area of $R$. Therefore the expected value of the perimeter is calculated as
$$t = \left(2\int_0^1 3\sqrt 2 r \cdot \frac {\sqrt 3} 2 r^2 dr + \int_1^2 3\sqrt 2 \cdot \frac{\sqrt 3}2 (-2r^2 + 6r - 3)dr\right)/\left(2\int_0^1 \frac {\sqrt 3} 2 r^2 dr + \int_1^2 \frac{\sqrt 3}2 (-2r^2 + 6r - 3)dr\right) = \frac {11} 4 \sqrt 2.$$ Therefore $t^2 = \frac{121}{8}$ and the final answer is $12108$.

Harvard MIT math question


PostgreSQL bulk import from CSV failing. ERROR: invalid input syntax for integer: "1990-01-02"

Question: I am importing data from a CSV file into a postgreSQL table.
The table looks like this:
CREATE TABLE foo_stats (
                        td                      DATE NOT NULL,
                        ins_id                  INTEGER CHECK (ins_id > 0) NOT NULL,
                        df_id                   INTEGER CHECK (df_id > 0) NOT NULL,
                        pc                      REAL NOT NULL DEFAULT 0.0,
                        ph                      REAL DEFAULT 0.0 NOT NULL,
                        pl                      REAL DEFAULT 0.0 NOT NULL,
                        av                      REAL DEFAULT 0.0 NOT NULL,
                        cv                      BIGINT DEFAULT 0 NOT NULL,
                        avi                     REAL DEFAULT 0.0 NOT NULL,
                        cmi                     BIGINT DEFAULT 0 NOT NULL,
                        vwp                     REAL CHECK (vwp >= 0) NOT NULL,
                        atr                     REAL NOT NULL DEFAULT -99999,
                        pv                      REAL NOT NULL DEFAULT -99999,
                        pr                      REAL NOT NULL DEFAULT -99999,

                        PRIMARY KEY                     (ins_id, df_id, td)
                        );

BEFORE the bulk copy, I drop the primary key using ALTER TABLE DROP CONSTRAINT PRIMARY KEY
Here is a trace of the CL when I invoke the COPY command at the psql CLI:
mydb=# COPY foo_stats FROM '/path/to/data/foo_stats.csv' WITH CSV;
ERROR:  invalid input syntax for integer: "1990-01-02"
CONTEXT:  COPY foo_stats, line 1, column id: "1990-01-02"
mydb=#

Here is what the first few lines of the input CSV file looks like:
"1990-01-02",388,3,-99999,0.913,0.91,0.0,0,0.0,0,0,-99999,-99999,-99999
"1990-01-02",388,4,-99999,0.913,0.91,0.0,0,0.0,0,0,-99999,-99999,-99999
"1990-01-02",388,1,-99999,0.913,0.91,0.0,0,0.0,0,0,-99999,-99999,-99999
"1990-01-02",388,7,-99999,0.913,0.91,0.0,0,0.0,0,0,-99999,-99999,-99999
"1990-01-02",388,6,-99999,0.913,0.91,0.0,0,0.0,0,0,-99999,-99999,-99999

The data columns in the input file are in the same order as in the table schema. Can anyone explain why I am getting the error message?
PS: I am using PostgreSQL 8.4 on Ubuntu 10.0.4 LTS
Comment: Something is missing here. I just created a table using your definition, copied sample data into the file and imported it with `COPY foo_stats FROM 'c:\tmp\foo_stats.csv' WITH CSV;` — all works just fine!
Answer: Cutting and pasting your table definition and sample data here shows everything working.
So - either your table definition or your file are not as you think they are. If your table columns are in a different order, you can specify columns in the COPY command.
If the file is different, it's presumably something not visible to the naked eye, or you would have spotted it before asking. I don't suppose this file has come from a Windows machine by any chance?
Three things to check for:

Unnecessary byte-order-mark (BOM) at the start of the file
Line-endings of \r\n rather than \n
Any other control-codes

Try cutting + pasting your sample data and see if that imports. If so, try opening your real file in a text editor and re-saving it. If that fixes things, get a hex editor and take a look at the actual bytes in your sample file.
Comment: Thanks to drawing my attention to this possibility. It turns out, my db schema had been changed in the db during prior testing, and was different to what I had expected. fixed now.


Search first row for a value then get the full column range

Question: I want to search the first row for different values then use the column range in a formula.
In my VBA I have a formula like;
=INDEX('Othersheet'!$J:$J,MATCH($C5,'Othersheet'!$E:$E,0))

This worked fine until someone added columns to 'Othersheet'. So I thought I'd just search for the header I need and use the column it returns, but I can't work out how to do this.
Something like;
Range("1:1").Find("TEXT").Entirecolumn.Select

But that will select the column and what I need is to use the column range so I can replace the "'Othersheet'!$J:$J" with this column if it's now not in J:J.
Comment: `.Address` perhaps?
Answer: Try this:
address = Sheets("Othersheet").Columns(WorksheetFunction.Match("TEXT", Range("'Othersheet'!1:1"), 0)).Address(, , , True)

To explain a bit, it finds the heading match from "1:1" as the question recommended, and then locate the reference of the exact column, and output the address with External flag set to True.
Comment: Using this, playing with this (removing the parts after .address), I've got a much better understanding here now. Thank you.


Fisher's exact test in more than 2 variables

Question: I have some data with three independent categorical variables (one has a sense of order, the others do not) and one dependent categorical variable. Is there an analogue to Fisher's exact test where I can simultaneously evaluate whether the independent variables affect the dependent one?
Specific details for anyone who is curious:
Subjects (37) do a series of 3 different activities. After completing all activities, we ask them to rank the activities in order of their preference (6 possible ranking orders: ABC, ACB, BAC, BCA, CAB, CBA) (dependent variable). We also collect their age range (4 levels, ordered), impairment (4 categories: cognitive, motor, motor and cognitive, none), and order they performed the activities (2 possible). So, in multiple dimensions, this creates a table of 6x4x4x2.
I can certainly run fisher's exact test for each factor with the dependent variable. But that doesn't seem complete or satisfying.
Comment: Are you sure the ranking orders are the independent variable? Please state precisely which are the independent and with is the dependent variables.
Comment: wow, I need more sleep. Thanks @frank for calling that out. Edited to fix.
Comment: You might want to consider a [multinomial probit model](https://en.wikipedia.org/wiki/Multinomial_probit). Here you model the preference of the categories A, B, C as random draws from conditional Gaussian distributions, and these Gaussian distributions relate to the categorical probability of the different orders ABC, ACB, BAC, BCA, CAB, CBA as function of the independent variables.
Comment: Hmm, that is actually really interesting. I am going to explore using linear models for this a bit more. Thanks
Answer: If you want to know, whether your dependent variable is affected by the combination of all your independent variables, you simply consider the two-way table where one dimension is your independent variables and the other one contains all the possible combinations of your independent variables, i.e. (young, cognitive, order1), (young, cognitive, order2), (young, motor, order1), ..., where you will obtain 4x4x2 = 32 possibilities.
Finally, you apply the Fisher test to this 6x32 table.
Of course, it is always a good idea to, in addition to the above, also consider the effect of only single independent variables (e.g. only age, resulting in a 6x4 table) and smaller combinations of independent variables (e.g. the effect of age and impairment, resulting in a 6x16 table), to find out the relevant predictors.
Comment: that makes sense. My concern is the number of tests that would be run blowing up my chances of false rejections. I can correct using the Holm method (I think that is the least conservative method that I am confident I meet the assumptions for), but there will still be a loss of power for anyone of the test.
Comment: You base your decision just on one single test, the Fisher test on the 6x32 table. So no correction is necessary. The other tests I mentioned above were just for getting to know your data better.
Comment: Gotcha. I will have to think about how I present the results of those tests. Thanks for your help.


What to do with my sweaty daily clothes?

Question: I play tennis daily, and I sweat alot.
I tend to use dri-fit shirts, which are great for playing, but as they get older, they tend to smell even after they're washed. They smell great after you wash them, but once they start "warming up", they begin to smell awful.
I tend to wash on weekends, so what can I do with these dri-fit clothes once I use them daily?
Christmas is coming, and I'll be getting lots of these dri-fit shirts and shorts, so I would like to maintain them properly.
Thanks.
Comment: I am a football enthusiast and really want to know the answer to this.
Comment: I do a load of laundry of just workout clothes with a cup of white vinegar.  Also Tide for Sports helps.
Answer: I used to play tennis 3 or 4 days a week and sweat a lot too and I live in the Phoenix, Arizona area where it's 100+ F four or five months a year so I experienced the same thing as you with my dri-ft and clima-cool tennis clothing.
Here is something you can try that I had some good results with:

Musty smells can occur if your clothing is stored in enclosed
  wardrobes that aren't cleaned regularly or are prone to damp. To
  remove the smell, soak your clothing in a bowl of cold water mixed
  with one cup of baking soda. The baking soda will help release any
  odours that are trapped in the fabric
Answer: I have a lot of workout clothes that have not entirely disintegrated yet, which is the only way my stuff gets tossed out, so some items date back to the 1980s.
Needless to say, you get a bit of perma-funk after a while.  My ways of combating that, in order of what I feel the success is -
1) Salt water.  Give the clothes a good rinse and wring to rinse out some of the residual sweat and residue, then soak them in hot salted water in the kitchen sink, maybe do some agitation by hand after they've sat for a little bit.  The reason why meats are preserved with salt (dry-cured ham, bacon, etc) is because the salinity kills bacteria, which is the cause of most of the stink.  After soaking I put them into the washing machine for a spin-only cycle, and then either sit/hang them out with salty residue still in there, or do a regular wash on them.
2) Baking soda.  I usually add a bunch to the washing machine tub.
3) Hot water washes - this is pretty tough on the fabrics, though.


How do you resolve a "The parameters (number[]) don't match the method signature for SpreadsheetApp.Range.setValues" error

Question: I am getting this error:

"The parameters (number[]) don't match the method signature for SpreadsheetApp.Range.setValues."

in my Google Apps Script when I try to write an array of values to a sheet.
Below is a shortened (simplified) version of code. The actual code runs through about 10,000 records.
The error is generated in the last line, when the setValues is called.
I know I'm missing something super simple here.
function writeArrayToSheet() {

  var ss = SpreadsheetApp.openById("Spreadsheet_ID");
  var orderSheet = ss.getSheetByName("Sheet_Name");
  var vTable = orderSheet.getRange(1,6,5,11).getValues(); //Raw data
  var vWriteTable = []; //Data that will be written to sheet
  var updateTime = new Date();
  var i = 0;
  var vSeconds = 0;

  while (i < 5 && vTable[i][0] != "") {

    //Logic section that calculated the number of seconds between

    if (vSeconds == 0) {
      vWriteTable.push("");
    } else {
      if (vTable[i][6] < certain logic) {
        vWriteTable.push("Yes");
      } else {
        vWriteTable.push("");
      }
    }
    i = i + 1;
  } // End while

  orderSheet.getRange(1,20,vWriteTable.length,1).setValues(vWriteTable);
} //End Function

This is what vWriteTable looks like when debugging:
Answer: setValues accepts(and getValues() returns):

1 argument of type:
Object[][] a two dimensional array of objects

It does NOT accept a 1 dimensional array. A range is always two dimensional, regardless of the range height or width or both.
If A1:A2 is the range, then corresponding values array would be like:

[[1],[3]]

Similarly, A1:B1 would be

[[1,2]]

A1:B2 would be

[[1,2],[3,4]]

Notice how the two dimension provides direction and that it is always a 2D array, even if the height or width of the range is just 1.
Solution:
Push a 1D array to make the output array 2D.
Snippet:
vWriteTable.push(/*Added []*/["Yes"]);

More information:
For a more detailed explanation of arrays in google sheets, checkout my answer here.
Comment: @user8118328 what  the snippet means is that each time you do a push it has to be as a 2D array. So if the array you are building is 1D you need to add additional square brackets to make it 2D. When applied to the original question, this means you replace the following lines of code as follows: vWriteTable.push(""); --> vWriteTable.push([""]); and vWriteTable.push("Yes"); --> vWriteTable.push(["Yes"]);
Comment: Could someone edit this answer to provide the actual solution? I don't know what to do with the snippet.
Comment: For dynamic values=>var yourVariable=; =>vWriteTable.push([yourVariable]); ( instead of just vWriteTable.push(yourVariable); )
Answer: You can simply way do like this put value in square brackets []:
in your case:
WriteTable.push([""]) or WriteTable.push(["yes"])
Answer: getValues returns object[rows][columns]
1 row object [[1...n]] - this maybe confusing b/c it may not look like 2D but it is 2D object[1 row][n columns]
2 row object [[1...n],[1...n]] - object[2 rows][n columns]
etc [[1...n],...,[1...n]] - etc
If you need to setValues to rectangular range with n rows and m columns, create EXACTLY n by m array 1st, then fill it with your values and send it to the MATCHING range in your spreadsheet. Here is some of my code that might help.
Getting values from 1st m cells in n-th row and pushing them in simple 1D array:
    var arr = [];
    var dataRow = sheet.getRange(n,1,1,m).getValues();
    for (var j=0; j<dataRow.length; j++){
      arr.push(dataRow[0][j]);
    }

to replace them with new values from 1D array arr:
//create 2D array with just 1 row and m columns
    var dataRow = new Array(1);
    dataRow[0] = new Array(arr.length);
//fill it with values
    for(var j=0;j<arr.length;j++){
        dataRow[0][j]=arr[j];
    }
//send it to the spreadsheet
    sheet.getRange(n,1,1,arr.length).setValues(dataRow);


how can i convent code from python 3.11 to 2.7

Question: I have some code in python 3.11 and I want to convert it to python 2.7
I tried running the code I made in 3.11 to 2.7 but it had some errors
this is the code:
import os
from datetime import date
from tkinter import *
import traceback
import time

with open("log.txt", "w") as log:  # logging an error if it happens
    try:
        today = date.today()  # getting date
        d4 = today.strftime("%Y")  # setting d4 only as current year

        def monthfolcreate():  # creating month folders
            newpath = fr'{a}\January'
            if not os.path.exists(newpath):
                os.makedirs(newpath)

            newpath = fr'{a}\February'
            if not os.path.exists(newpath):
                os.makedirs(newpath)

            newpath = fr'{a}\March'
            if not os.path.exists(newpath):
                os.makedirs(newpath)

            newpath = fr'{a}\April '
            if not os.path.exists(newpath):
                os.makedirs(newpath)

            newpath = fr'{a}\May'
            if not os.path.exists(newpath):
                os.makedirs(newpath)

            newpath = fr'{a}\June'
            if not os.path.exists(newpath):
                os.makedirs(newpath)

            newpath = fr'{a}\July'
            if not os.path.exists(newpath):
                os.makedirs(newpath)

            newpath = fr'{a}\August'
            if not os.path.exists(newpath):
                os.makedirs(newpath)

            newpath = fr'{a}\September'
            if not os.path.exists(newpath):
                os.makedirs(newpath)

            newpath = fr'{a}\October'
            if not os.path.exists(newpath):
                os.makedirs(newpath)

            newpath = fr'{a}\November'
            if not os.path.exists(newpath):
                os.makedirs(newpath)

            newpath = fr'{a}\December'
            if not os.path.exists(newpath):
                os.makedirs(newpath)

        def monthcreate():  # creating all date folders
            jan = 0
            feb = 0
            mar = 0
            apr = 0
            may = 0
            jun = 0
            jul = 0
            aug = 0
            sep = 0
            oct = 0
            nov = 0
            dec = 0

            for i in range(31):
                jan = jan + 1
                newpath = fr'{a}\January\{jan}-1-{d4}'
                if not os.path.exists(newpath):
                    os.makedirs(newpath)

            for i in range(28):
                feb = feb + 1
                newpath = fr'{a}\February\{feb}-2-{d4}'
                if not os.path.exists(newpath):
                    os.makedirs(newpath)

            for i in range(31):
                mar = mar + 1
                newpath = fr'{a}\March\{mar}-3-{d4}'
                if not os.path.exists(newpath):
                    os.makedirs(newpath)

            for i in range(30):
                apr = apr + 1
                newpath = fr'{a}\April\{apr}-4-{d4}'
                if not os.path.exists(newpath):
                    os.makedirs(newpath)

            for i in range(31):
                may = may + 1
                newpath = fr'{a}\May\{may}-5-{d4}'
                if not os.path.exists(newpath):
                    os.makedirs(newpath)

            for i in range(30):
                jun = jun + 1
                newpath = fr'{a}\June\{jun}-6-{d4}'
                if not os.path.exists(newpath):
                    os.makedirs(newpath)

            for i in range(31):
                jul = jul + 1
                newpath = fr'{a}\July\{jul}-7-{d4}'
                if not os.path.exists(newpath):
                    os.makedirs(newpath)

            for i in range(31):
                aug = aug + 1
                newpath = fr'{a}\August\{aug}-8-{d4}'
                if not os.path.exists(newpath):
                    os.makedirs(newpath)

            for i in range(30):
                sep = sep + 1
                newpath = fr'{a}\September\{sep}-9-{d4}'
                if not os.path.exists(newpath):
                    os.makedirs(newpath)

            for i in range(31):
                oct = oct + 1
                newpath = fr'{a}\October\{oct}-10-{d4}'
                if not os.path.exists(newpath):
                    os.makedirs(newpath)

            for i in range(30):
                nov = nov + 1
                newpath = fr'{a}\November\{nov}-11-{d4}'
                if not os.path.exists(newpath):
                    os.makedirs(newpath)

            for i in range(31):
                dec = dec + 1
                newpath = fr'{a}\December\{dec}-12-{d4}'
                if not os.path.exists(newpath):
                    os.makedirs(newpath)

        def submit():  # submit button command
            global a
            a = e.get()
            if os.path.exists(path=a):
                w.config(text="Folder already exists cant make one!.")
                window.after(2000,window.update())
                exit()
            monthcreate()
            window.after(1000, window.update())
            monthfolcreate()
            w.config(text="Folders Created.")
            window.after(2000, window.update())
            exit()

        # creating window
        window = Tk()
        window.eval('tk::PlaceWindow . center')
        window.resizable(False, False)
        window.geometry('300x200')
        window.title('Folder creator')
        window.config(bg='#111111')
        p1 = PhotoImage(file='icon.png')
        window.iconphoto(False, p1)

        # text on screen
        w1 = Label(window, text='Insert folder name or directory:')
        w1.place(x=30, y=50)
        w1.config(bg='#111111')
        w1.config(fg='white')
        w1.config(font=('Arial', 13))

        # 2nd text on screen
        w = Label(window, text='')
        w.place(y=500, x=4030)
        w.pack(side=BOTTOM)
        w.config(bg='#111111')
        w.config(fg='white')
        w.config(font=('Arial', 13))

        # submit button
        submit = Button(window, text="Start", command=submit)
        submit.place(y=130, x=120)
        submit.config(bg='#111111')
        submit.config(fg='white')
        submit.config(font=('Arial', 13))

        # entry box
        e = Entry()
        e.place(relx=0.5, rely=0.5, anchor=CENTER)
        e.config(font=('Arial', 20))
        e.config(bg='#111111')
        e.config(fg='white')

        window.mainloop()

    except Exception:
        traceback.print_exc(file=log)

it runs fine on python 3.11 but i need it to run on 2.7 and i dont know what to do to run it this are the errors i get when running it on python 2.7
Comment: Don't. Do not use python2.7 anymore. Use another solution
Comment: Python 2.7 is coming up on _three years_ past its extended support period. There are very few valid reasons to use it in 2022-going-on-2023. Python 3 was first released 14 years ago. Why do you want to do this?
Comment: its for my school and the computers run only 2.7
Comment: @590ms, that's very unfortunate. Nobody should be teaching Python using version 2.7 anymore. In any case, your best bet moving forward is to use Python 2.7 while developing your solution. That way you won't have a translation challenge at the end.
Answer: python 2.7 does not have f strings, you need to use string format instead.
https://docs.python.org/3/tutorial/inputoutput.html#fancier-output-formatting
https://docs.python.org/2.7/library/string.html#custom-string-formatting
e.g.
newpath = fr'{a}\June\{jun}-6-{d4}'

becomes
newpath = '{a}\June\{1}-6-{2}'.format(a, jun, d4)

you could use better variable names though
Comment: That's unlikely to be the only issue...
Comment: @ThePhoton, it's the only error message OP has shared, but the question is "how can I convert this code from Python 3.11 to Python 2.7?" I strongly suspect OP won't be happy until every issue is resolved (which isn't what SO is for). I've voted to close the question as too broad.
Comment: ok then i should not continue this
Comment: @Chris, its' the only issue OP has shared with us.
Comment: that just ouputs  a KeyError: 'a'
Comment: @590ms: each subversion of python came with many many new features of the language. f-string are just one of the numerous new things introduced with version 3.6 for example. And that is just accounting for python3. And you are asking about python2. Which is not just an older version of the language. It is a different language. So, sure, once you'll have corrected f-string error, you'll see another error, then another, then another. We can go back and forth, we telling you how to correct any error, and you telling us what new error you see. Even if we play that game 24/24 with short reaction...
Comment: @590ms ...time, we are very likely to be still playing that game in 2023. Just check release notes of all python version since python3. And line in those releases notes are potential "retrofiting" you'll have to do. And, again, that is just to make your code run with python3.0. Then you'll still have to make it work with python 2.7
Comment: @chrslg ok thx for the advice if there any way i can close this thread?
Comment: @590ms if your code is really small, then it may be shorter, of course (but on the other hand, with libraries you may also end up in dead-end). For closing, no, I don't know. I've never used the question interface, so I don't know if and how you can close a question yourself (I've never encounter a question "closed by asker", so I surmise you can't. I know you can delete it, but it doesn't seem necessary to me — tho, I am quite new around here)
Comment: @590ms, the iteration chrslg is describing is something that you can do yourself. Instead of posting the entire program here and asking how to make it work with Python 2.7, tackle one problem at a time. You have an error message about f-strings. Search the error message, find the solution, alter your code. Now, move on to the next error. Most (all?) of the errors you find are likely to be solvable by searching the error message. If you get a _specific_ problem that you can't find an answer to, feel free to post here. But ask about that specific problem, with as little code as possible.


How to calculate the "unfairness" for repeated random selection?

Question: Assume there are 16 people in a group, and each day 11 people are randomly selected from the group. Over a year, some people will be selected more times than other people.
The question is, assume the person selected most often was selected $M$ times, and the person selected least often was selected $m$ times, what is the distribution (or the expected value) of the quantity $M/m$?
Comment: The expected value is clearly not even defined since there is a positive probability that $m = 0$. Furthermore, $M > 182$ with probability one (trivially).
Comment: Nevertheless, @Cardinal, there *is* a distribution for $(m,M)$ and, by defining "$M/m$" in some suitable way for the cases where $m=0$, one can derive a distribution for $M/m$.  The definition of $M/0$ really does not matter practically because the chance of this occurring is approximately $10^{-184}$.  The *expectation* of this distribution will be sensitive to the value chosen for $M/m$.  One simple way to resolve the problem is to consider a closely related random variable such as $(M+1)/(m+1)$.
Comment: @whuber Or simply $m/M$ which is well-defined and in $[0,1]$.
Comment: @whuber: Yes, I agree. I was simply trying to show a very quick way to answer one of the OP's specific questions. I have found it helpful in my own learning to see simple arguments that elucidate such edge cases. I agree with Elvis that if one's interest lies in ratios, then $m/M$ is a little bit more sensible choice.
Answer: An exact computation could be written but this will be rather tedious... moreover the final result will surely be ugly, involving discrete summations requiring the help of a computer to evaluate... and to be honest I feel lazy!
However, the use of brute force is easy :) Here is a piece of R code. The function f generates a particular value of $M/m$ :
f <- function()
{
  x <- matrix(0, ncol=16,nrow=365)
  for(i in 1:365)
    x[ i, sample(1:16,11) ] <- 1;
  a <- colSums(x);
  return( max(a)/min(a) );
}

Then we compute 10000 such values :
> q <- numeric(10000)
> for(i in 1:length(q)) q[i] <- f()

Using length(unique(q)) we remark that only 559 values were taken. None of this values is Inf (which has a very low probability)...
Here are some quantiles :
> round(quantile(q, seq(0,1,0.1)),3)
   0%   10%   20%   30%   40%   50%   60%   70%   80%   90%  100%
1.049 1.100 1.110 1.119 1.127 1.135 1.143 1.152 1.163 1.179 1.316

And an histogram:
> hist(q, breaks=30, freq=FALSE)

Note that as suggested by cardinal you could be interested in $m/M$ as well:
> round(quantile(1/q, seq(0,1,0.1)),3)
   0%   10%   20%   30%   40%   50%   60%   70%   80%   90%  100%
0.760 0.848 0.860 0.868 0.875 0.881 0.887 0.894 0.901 0.909 0.953

> mean(q)
[1] 0.8796803
> sd(1/q)
[1] 0.02403925

> hist(1/q, breaks=30, freq=FALSE)

Edit I computed $10^5$ values. 842 different values are taken. The histograms look very similar. Here are the quantiles.
> round(quantile(q1, seq(0,1,by=0.05)),3)
   0%    5%   10%   15%   20%   25%   30%   35%   40%   45%   50%
1.041 1.091 1.100 1.105 1.111 1.115 1.120 1.123 1.128 1.131 1.136
  55%   60%   65%   70%   75%   80%   85%   90%   95%  100%
1.140 1.143 1.148 1.153 1.158 1.164 1.171 1.180 1.195 1.322

> round(quantile(1/q1, seq(0,1,by=0.05)),3)
   0%    5%   10%   15%   20%   25%   30%   35%   40%   45%   50%
0.756 0.837 0.847 0.854 0.859 0.864 0.868 0.871 0.875 0.877 0.881
  55%   60%   65%   70%   75%   80%   85%   90%   95%  100%
0.884 0.887 0.890 0.893 0.897 0.900 0.905 0.909 0.916 0.961

The distribution of $m/M$ is well approximated by a Beta distribution with parameters $\alpha = 57.9482$ and $\beta = 21.68629$. See on the following figure the empirical cdf of $m/M$ using $10^5$ simulated values, in black, and the cdf of this Beta distribution, in dotted red. Now I would be curious to see a theoretical approach to the question! (still too lazy and pessimistic to try)


Unable to import git in python

Question: I am facing these issues. Can you help me with the same ?
Why am I seeing this error ? Do I have to add anything in the requirements.txt file ?
>>> import git
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
 import git
File "git\__init__.py", line 29, in <module>
_init_externals()
File "git\__init__.py", line 23, in _init_externals
raise ImportError("'gitdb' could not be found in your PYTHONPATH")
ImportError: 'gitdb' could not be found in your PYTHONPATH

>>> from git import Repo
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
from git import Repo
File "git\__init__.py", line 29, in <module>
_init_externals()
File "git\__init__.py", line 23, in _init_externals
raise ImportError("'gitdb' could not be found in your PYTHONPATH")
ImportError: 'gitdb' could not be found in your PYTHONPATH

Answer: I already had gitdb and smmap installed so I had to reinstall them.
You can reinstall them by running the following command in your terminal:
pip3 install --upgrade --force-reinstall gitdb; pip3 install --upgrade --force-reinstall smmap

Comment: This works! Thanks!
I have both smmap and gitdb installed already, and somehow both need to be installed again (same version). The command I used is: pip3 install --force gitdb smmap.
Answer: I also got the message ImportError: 'gitdb' could not be found in your PYTHONPATH (when trying to use GitPython).BUT I had gitdb already installed!
Thanks to this hint I figured out that gitdb silently failed because it was missing smmap.
So I installed this and it worked.
Comment: Upvote AGAIN.  Ran into this same error during a new Sphinx upgrade - and used this hint.  Thanks AGAIN!
Answer: You need to install gitdb package.
$ sudo easy_install gitdb

Comment: I am using a windows machine
Comment: So you can use only `easy_install gitdb`
Answer: I had the same problem. However, gitdb and smmap were already installed by pip. As I used brew to install python and its dependencies on my mac, when I checked brew doctor command, it said that my /usr/local/sbin directory is not in my PATH. So I added it to my PATH (though it didn't have anything to do with the python) and everything worked out eventually.
Answer: MS Windows Versions of this problem can occur because of the order of Python versions in your system PATH, as it did for me.  I did not realize that when I installed another program, it installed a newer version of Python for its own usage, and it appended my system PATH with the address to the newer version.  I noticed it when I looked at the PATH variable and found two versions of Python being called.  Windows uses the first it finds, and if the first doesn't match what your program expects, it gets confused and can't find the right path to the module.  This is what I did to resolve it:

To check: an easy way to test if this is your problem is to see if the paths separated by semicolons are in the right order.  That can be seen in the System Variables of Windows or by printing your PATH variable in your CMD shell like in this example:
C:> path
PATH=C:\Program Files (x86)\Python37-32\Scripts;C:\Program Files (x86)\Python37-32;C:\Program Files\Python38\Scripts;C:\WINDOWS

Temporary solution:
To see if it is going to fix your computer, change it in your CMD window.  Your variable change will be discarded when the window is closed.  One way to do this test is to copy the paths, move the Python references to the order they are needed, and write it back:
C:> set path = C:\WINDOWS;C:\Program Files (x86)\Python37-32;C:\Program Files\Python38\Scripts;C:\Program Files (x86)\Python37-32\Scripts\
Then run the Python program to see if this was your problem.  Note that this is only an example; do not copy & paste it.  Your path is customized for the programs on your computer.

Permanent solution: If the above test resolves your problem, you must change your System Variables to make the change permanent.  For me that usually requires a reboot afterwards in order to make the variables appear in all new windows.

Unable to import git in python