Is it possible to program web app using python without "any" framework?

Question: I'm worked on PHP previously and want to know python web programming. But everything for me is ambiguous.
Is it possible to program web app using python without "any" framework?
I know frameworks make everything easy for us and even if it is possible program web app without framework , it is not logical for big projects. But my target is just learning because I think start programming with frameworks is not good idea and we should know some information about pure python in web applications. So Imagine I want make very very simple webpage like hello world or small counter or small api. please do not offer me lightweight frameworks like flask. I just want know can pure python create webpages?
Comment: Yes, that's possible.
Comment: it's really just a matter of how much re-inventing the wheel you want to do... Python can listen and respond on tcp ports using the `socket` library, or you could go one step further and use the `http.server` library which breaks out a bit more functionality for you, but you still are just working with the exact `get`, `post`, `delete`, etc. requests.
Comment: If learning is the goal, here is a good 3-hour PyCon workshop on that topic by one of the co-creators of Django, which goes into exactly what makes up a web framework - ["Let's Build A Web Framework"](https://www.youtube.com/watch?v=7kwnjoAJ2HQ)
Comment: This link will answer your question [Python web development with or without frameworks](https://stackoverflow.com/questions/136069/python-web-development-with-or-without-a-framework)
Comment: Yes, you can use good old CGI with the [builtin cgi module](https://docs.python.org/2/library/cgi.html) like we used to do 20 years ago (TBH I used Perl CGI back then but same principles apply).
Answer: Yes, technically, you can create a webpage with "pure python," but you certainly wouldn't want to!  The most beautiful part of programming is the fact that there are millions of others who have worked hard to create "frameworks," such as Flask or Django, that massively simplify the work that is required to make an application.
If your goal is "just learning" then using a framework that you are unfamiliar with is a great way to start.  Learning programming is not about the technical knowledge required to run every aspect of your code, rather it is all about knowing how to ask the right questions for the particular application you are trying to build.
Programmers are lazy.  If there is a shortcut that can be taken in code, you should take it (unless you have a really good reason not to).
Think of this example:
I have a list that was converted to a string:
myStringList = "['foo', 'bar', 'foobar']"

How can I convert this string to a format that my computer can interpret as a list?
I could make a function like this:
def stringToList(node_or_string):
    if isinstance(node_or_string, str):
        node_or_string = parse(node_or_string, mode='eval')
    if isinstance(node_or_string, Expression):
        node_or_string = node_or_string.body
    def _convert_num(node):
        if isinstance(node, Constant):
            if isinstance(node.value, (int, float, complex)):
                return node.value
        elif isinstance(node, Num):
            return node.n
        raise ValueError('malformed node or string: ' + repr(node))
    def _convert_signed_num(node):
        if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
            operand = _convert_num(node.operand)
            if isinstance(node.op, UAdd):
                return + operand
            else:
                return - operand
        return _convert_num(node)
    def _convert(node):
        if isinstance(node, Constant):
            return node.value
        elif isinstance(node, (Str, Bytes)):
            return node.s
        elif isinstance(node, Num):
            return node.n
        elif isinstance(node, Tuple):
            return tuple(map(_convert, node.elts))
        elif isinstance(node, List):
            return list(map(_convert, node.elts))
        elif isinstance(node, Set):
            return set(map(_convert, node.elts))
        elif isinstance(node, Dict):
            return dict(zip(map(_convert, node.keys),
                            map(_convert, node.values)))
        elif isinstance(node, NameConstant):
            return node.value
        elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
            left = _convert_signed_num(node.left)
            right = _convert_num(node.right)
            if isinstance(left, (int, float)) and isinstance(right, complex):
                if isinstance(node.op, Add):
                    return left + right
                else:
                    return left - right
        return _convert_signed_num(node)
    return _convert(node_or_string)

And call it like this:
myList = stringToList(myStringList)

print(myStringList[0] # [
print(myList[0]) # foo

Or I could simply use the wonderful ast package in the default python library and achieve the same results:
import ast

myList = ast.literal_eval(myStringList)

print(myList[0]) # foo

All credit for the stringToList function goes to the creators of the ast package, as I merely copied it from source code.
To add an example of a "good reason" to create your own package/framework, lets say I need to use the eval function for whatever reason.  As we all know, eval is dangerous and, generally speaking, shouldn't be used.  If I really need to use it, and there aren't any alternatives (cough cough, literal_eval), the only solution would be to create my own version of the eval function, to avoid having exploitable code.
Comment: better yet, you could not convert your objects to `str` and call that serialization! +1
Comment: Did you mean programm without framework is so hard that we couldn't make even hello world page without framework easily??? Can a intermediate python programmer build a very simple page but he doesn't? or it is advanced subject?
Comment: @AliMarasizadeh sorry, I don't understand your question.
Comment: sorry for my bad english :'( I want to know create hello world page with pure python on web is hard? is it professional case?   I hope that you understood my question.


ESP8266 with Serial AT commands

Question: I am trying to communicate with my ESP8266-07 through Arduino Nano Serial. I am using AT commands to reset, connect wifi, connect TCP server and so on. I have got one functional script, so i know that ESP8266 is wired correctly. I am using 3.3V to 5V logic converter and so on... This is the older functional script:
void esp_connect() {
  Serial.println("AT+RST");
  delay(2);
  esp_timefuse = millis();
  while(Serial.find("ready") == false) {
  if(esp_timefuse - millis() >= 5000)
    esp_connect();
  }

  Serial.println("AT+CWMODE=3");
  delay(2);
  esp_timefuse = millis();
  while(Serial.find("OK") == false) {
    if(esp_timefuse - millis() >= 2000)
      esp_connect();
  }

  Serial.println("AT+CWJAP=\"WiFi 7-pekiel\",\"43664366\"");
  delay(2);
  esp_timefuse = millis();
  while(Serial.find("OK") == false) {
    if(esp_timefuse - millis() >= 2000)
      esp_connect();
  }

  Serial.println("AT+CIPMUX=1");
  delay(2);
  esp_timefuse = millis();
  while(Serial.find("OK") == false) {
    if(esp_timefuse - millis() >= 2000)
      esp_connect();
  }

  Serial.println("AT+CIPSTART=0,\"TCP\",\"10.10.10.6\",3600");
  delay(2);
  esp_timefuse = millis();
  while(Serial.find("OK") == false) {
    if(esp_timefuse - millis() >= 2000)
      esp_connect();
  }
}

But I am not satisfied with it. I am trying to do it best. So i wrote this script:
void esp_connect() {
  Serial.println("AT+RST");
  Serial.flush();
  Serial.setTimeout(5000);
  if(Serial.find("ready"));
  else esp_connect();

  Serial.println("AT+CWMODE=3");
  Serial.flush();
  Serial.setTimeout(2000);
  if(Serial.find("OK"));
  else esp_connect();

  Serial.println("AT+CWJAP=\"WiFi 7-pekiel\",\"43664366\"");
  Serial.flush();
  if(Serial.find("OK"));
  else esp_connect();

  Serial.println("AT+CIPMUX=1");
  Serial.flush();
  if(Serial.find("OK"));
  else esp_connect();

  Serial.println("AT+CIPSTART=0,\"TCP\",\"10.10.10.6\",3600");
  Serial.flush();
  if(Serial.find("OK"));
  else esp_connect();
}

When I am testing this new script through Serial monitor everything works. I am simulating ESP8266 so I just type "OK" and "OK" just like ESP8266. But when I connect it to ESP8266 nothing works. Where is the Mistake in my script? Is my usage of Serial.find() correct?
Answer: Your if/else statements are not correct at all. e.g.
  if(Serial.find("ready"));
  else esp_connect();

Firstly the if condition shouldn't have a semicolon ; at the end and you aren't really testing if/else, just if so it should be in the form
  if(!Serial.find("ready")) {
    esp_connect();
  }

  if(!Serial.find("OK")) {
    esp_connect();
  }

Notice the exclamation mark ! this is logical NOT - so the code in the brackets only gets executed when the statement is FALSE.
Answer: I found that code is working perfectly and the mistake was too short timeout for connect to wifi. Two second was too short time duration for ESP8266. Quite a dumb mistake...

ESP8266 with Serial AT commands


Using Resolution theorem proving with Z3

Question: I am new to Z3 but have some prior experience using Prolog.
I have managed to solve the following "puzzle", i.e. to prove that the girl is a witch using Prolog, but am at a loss how to implement it in Z3 (in C++ or Python):
https://www.netfunny.com/rhf/jokes/90q4/burnher.html
Do I need to declare Function() for assertions like
BURNS(x) /\ WOMAN(x) and  WOMAN(GIRL)
What about implications of the sort \forall x, ISMADEOFWOOD(x)   =>  BURNS(x)?
Any tips are appreciated
Answer: It should be pointed out that SMT solvers (i.e., Z3) aren't usually good at reasoning with quantifiers in general, but this particular case is easy enough that it can handle without a sweat. (It's easy because all you have are uninterpreted sorts and booleans; there are no integers, reals, datatypes etc., to complicate the logic.) Also, there are some modeling differences when you use an SMT solver compared to Prolog's deduction strategy, so the modeling will be a bit different.
The crucial point is that Prolog uses the so-called closed-world-assumption viewpoint. That is, if it cannot show an implication, it'll decide that it isn't implied. An SMT solver does not do that: It will prove implications; but if you query a variable that isn't properly constrained (i.e., if it can be both True or False according to the assertions), then it's free to pick any interpretation. So, the modeling has to take that into account.
What does that mean for the current problem? We have to prove that the statements imply the girl is a witch. If they don't, we don't know whether she is or not. To do so, we assert the negation of the conclusion we want and check if the resulting system is unsatisfiable. If that's the case, then we can conclude our conclusion must be valid. If the result is satisfiable, then we have a counter-example model that we can investigate further. In this case, it'll mean there is insufficient evidence that the girl is a witch. (Note that adding the negation of the conclusion we want to prove is very typical of resolution proofs, and we're following the same strategy here.)
Given all this, here's how I would go about modeling it using the Python API, you should be able to translate this to C++ (or any other language with proper bindings) with relative ease. The clauses almost translate literally:
from z3 import *

Thing = DeclareSort('Thing')
GIRL  = Const('GIRL', Thing)
DUCK  = Const('DUCK', Thing)

BURNS        = Function('BURNS',        Thing,        BoolSort())
FLOATS       = Function('FLOATS',       Thing,        BoolSort())
WOMAN        = Function('WOMAN',        Thing,        BoolSort())
WITCH        = Function('WITCH',        Thing,        BoolSort())
SAMEWEIGHT   = Function('SAMEWEIGHT',   Thing, Thing, BoolSort())
ISMADEOFWOOD = Function('ISMADEOFWOOD', Thing,        BoolSort())

s = Solver()
x = Const('x', Thing)
y = Const('y', Thing)

s.add(ForAll([x], Implies(And(BURNS(x), WOMAN(x)), WITCH(x))))
s.add(WOMAN(GIRL))
s.add(ForAll([x], Implies(ISMADEOFWOOD(x), BURNS(x))))
s.add(ForAll([x], Implies(FLOATS(x), ISMADEOFWOOD(x))))
s.add(FLOATS(DUCK))
s.add(ForAll([x, y], Implies(And(FLOATS(x), SAMEWEIGHT(x, y)), FLOATS(y))))
s.add(SAMEWEIGHT(DUCK, GIRL))

# To prove the girl is a witch, we assert the negation,
# and check if it is unsatisfiable.
s.add(Not(WITCH(GIRL)))

res = s.check()

if res == sat:
    print("Nope, it doesn't follow that she's a witch!")
elif res == unsat:
    print("Yes, she is a witch!")
else:
    print("Hmm, solver said: ", res)

When I run this, I get:
Yes, she is a witch!

Too bad for her!
You can experiment by commenting out some of the assertions, and you'll see that z3 will say the system is sat, i.e., it cannot conclude the girl is a witch. You can then look at the model itself in detail to find out what the assignments are.
You can read through https://ericpony.github.io/z3py-tutorial/advanced-examples.htm to see how to use basic Python API for uninterpreted sorts, quantifiers, and basic modeling. If you've specific questions, feel free to ask further..
Comment: Thanks for the elaborate explanation! Everything from your solution works. I've appended a couple more questions to the original post. Maybe I should post those to SoF separately instead?
Comment: Stack-overflow works the best if questions are self-contained and address just one issue. Please ask them separately, so others will also get a chance to see it and answer too.
Comment: here we go: [link](https://stackoverflow.com/questions/62725916/z3-whats-a-more-convenient-and-efficient-method-for-defining-class-hierarchies)
I'd really like to see your input on the other question as well.


How to change default Xaml TextBox fontsize

Question: In my file.xaml, how can I set the TextBlock default size, so that I don't have to include that attribute in the TextBlock element?
<UserControl.Resources>

</UserControl.Resources>

<Grid>
    <StackPanel>
        <TextBlock Text="{Binding HelloWorld}" />
    </StackPanel>
</Grid>

Answer: Place this instead of your comment at UserControl.Resources


Erro ao abrir/criar base no firebird

Question: Estou com um problema com o Firebird. Fiz a instalação do Delphi e Firebird, mas quando tento abrir a base ele dá erro. Tentando abrir pelo ibexpert dá o seguinte erro
<code>unsuccessful execution caused by an unavailable resource. unavailable database
</code>
Estou usando a versão 2.5 do Firebird, mas já testei na 1.5 e 3.0. Além disso o serviço do Firebird está em execução no gerenciador de tarefas.
Comment: Em conformidade com o comentário da @Melissa o link a seguir da uma sugestão que parece solucionar o problema:
https://rairo.wordpress.com/2011/01/05/firebirdibexpert-ibexpert-unsuccessful-execution-caused-by-an-unavailable-resource/
Comment: Essa base está correta? Ela já era usada? Se já era usada, em qual versão do Firebird você usava?
Comment: Está tentando conectar local? Se for isso, no IBExpert coloque Server: Remote / Server Name: 127.0.0.1
Comment: Bom Dia. Você por acaso não tem o Interbase Instalado também?
Answer: Para resolver a mensagem "ibexpert unsuccessful execution caused by an unavailable resource." faça assim:

Verifique se o servidor do firebird está ativo.
Verifique se a porta 3050 está liberada no firewall do windows ou qualquer bloqueador ou Firewall que você tenha.
No ibexpert na hora de escolher o tipo de Servidor coloque REMOTE e Server name coloque o IP local da maquina "127.0.0.1"
Conecte no banco de dados.

Erro ao abrir/criar base no firebird


How to combine a String with a List in Python?

Question: I am new to Python and i want to know how to combine a String with all the elements of a List and then save Output in a .txt File. But the window just open and close immediately because the code is wrong. This is my code:
List = [1, 2, 3, 4, 5]

String = input("Please enter a name: ")
Output = String + List
print(Output)

f= open("Text.txt","w+")
f.write(Output + "\n")
f.close()

I am expecting to see this results:
Please enter a name: Username
Username1 Username2 Username3 Username4 Username5

And in the Text File like this:
Username1
Username2
Username3
Username4
Username5

How am i supposed to do this? If the question is not clear please let me know. My first language is not English so is hard for me to explain. Thanks for your time :)
Comment: I suggest you read some of the PEP8 style guide in order to write more readable code.
https://www.python.org/dev/peps/pep-0008/
Comment: Welcome to SO. Unfortunately this isn't a discussion forum or tutorial. Please take the time to read [ask] and the other links found on that page.  Invest some time with [the Tutorial](https://docs.python.org/3/tutorial/index.html) practicing the examples. It will give you an idea of the tools Python offers to help you solve your problem.
Answer: I reckon you can use a list comprehension:
List = [1, 2, 3, 4, 5]

String = input("Please enter a name: ")

Output = [String + str(x) for x in List]

print(Output)

Output:
['Username1', 'Username2', 'Username3', 'Username4', 'Username5']

Comment: Yucky variable naming especially for someone who is just learning the language. I suggest an edit to name them something more reasonable.
Comment: @ChadVanDeHey Yeha, i know that but i change the name of the variables just to make this Question easier to understand because as i said its hard for me to explain because i don't speak English very well. In my real code i have used: Chars - List | Username - String | Password - Output | Which is think is good for me. Thanks for the suggestion anyway :)
Comment: Then you have another for loop which then writes each of those entries into a new line on the text file
Comment: @ChadVanDeHey I agree, but direct that to OP in his question.
Comment: @JacobG. Hm... I don't know if i am doing anything wrong but this is not working. I get an error after i type a name in the "String". Do you know what is going on?
Comment: @MarioAgolli What *error* are you getting?  It works perfectly fine on my end.
Comment: @JacobG. I get this for the 3rd command in Ben10 code: TypeError: unsupported operand type(s) for +: 'int' and 'str'. And when i run this in the Terminal after i give my input it just close and dont give me the output.
Comment: @MarioAgolli Why aren't you using the code posted above?  Can you post the line that you get the error on?
Comment: @JacobG. I am so sorry that i am taking your time but i have tried your code too and the Terminal just close after i give my input. I am not getting an error now for some reason but it just dont give me the output... When it give me the error before the terminal closed immediately so i culdnt copy it :(
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169468/discussion-between-jacob-g-and-mario-agolli).
Answer: Following Jacob G. entry your code should look like this:
List = [1, 2, 3, 4, 5]
# input() only works for Python 3.x . Use raw_input() if using python 2.x
InputName = input("Please enter a name: ")
Usernames = [InputName + str(entry) for entry in List]
print(Usernames)

file= open("Text.txt","w+")
for username in Usernames:
   file.write(username)
file.close()

Comment: @Ben10 It turns out OP was using Python 2.7 and had to use `raw_input` instead.
Comment: Thanks for trying to help again i really appreciate it but i have fixed the error now. The problem was that i was using Python 2.7 where you need to use raw_input and your code was for -V 3.x so i just installed the latest version of Python now and its working perfectly. Thanks a lot for helping me to get started :)
Comment: Aghh... I am sorry but both your code and Jacob G. code is not working. I don't know if i am doing anything wrong but after i give my input to the "InputName" the Terminal just close and the Text.txt file don't get created. I tried to type the code one by one in the Python IDLE and i get this error after i type the 2nd command: NameError: name 'username' is not defined.
Comment: And when i run the 3rd command i get this error: TypeError: unsupported operand type(s) for +: 'int' and 'str'
Comment: Ok for the first one - username cannot be found, have you put made sure that the line `file.write(username)` is in the for loop `for username in Usernames:`


Why are my plots coming 1 below the other inspite of using the plotting function?

Question: I want to plot 2 figures side by side but for some reason they are coming 1 below the other. I've written the plotting code inside a function.
def team_comp(x,y,d,e):
a=[x,y]
mat_new1 = mat[mat['team1'].isin(a) & mat['team2'].isin(a)][['id', 'season', 'city', 'date', 'team1', 'team2', 'toss_winner',
   'toss_decision', 'result', 'dl_applied', 'winner', 'win_by_runs',
   'win_by_wickets', 'player_of_match']]
b=[d,e]
mat_new2 = mat[mat['team1'].isin(b) & mat['team2'].isin(b)][['id', 'season', 'city', 'date', 'team1', 'team2', 'toss_winner',
   'toss_decision', 'result', 'dl_applied', 'winner', 'win_by_runs',
   'win_by_wickets', 'player_of_match']]
fig=plt.figure(figsize=(10,6))
plt.subplot(1,2,1)
sns.countplot(x='winner', data=mat_new1)
plt.yticks(np.arange(0,20,1))

fig=plt.figure(figsize=(10,6))
plt.subplot(1,2,2)
sns.countplot(x='winner', data=mat_new2)
plt.yticks(np.arange(0,20,1))

I later called the function like this
team_comp('DCAP','RR','MI','CSK')

Comment: The matplotlib documentation is full of examples of SUBPLOTS. https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html?highlight=subplots#matplotlib.pyplot.subplots please, check that first.
Answer: import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

df = pd.DataFrame({"A": ["a", "b", "c", "a"]})
df2 = pd.DataFrame({"B": ["a", "b", "b", "b"]})

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(10,6))
sns.countplot(x = 'A' , data = df , ax = ax1 )
sns.countplot(x = 'B' , data = df2 , ax = ax2)
fig.tight_layout()
plt.show()


Saving output of confusionMatrix as a .csv table

Question: I have a following code resulting in a table-like output
 lvs <- c("normal", "abnormal")
 truth <- factor(rep(lvs, times = c(86, 258)),
                 levels = rev(lvs))
 pred <- factor(
                c(
                  rep(lvs, times = c(54, 32)),
                  rep(lvs, times = c(27, 231))),
                levels = rev(lvs))

 xtab <- table(pred, truth)

 library(caret)
 confusionMatrix(xtab)

 confusionMatrix(pred, truth)
 confusionMatrix(xtab, prevalence = 0.25)

I would like to export the below part of the output as a .csv table
               Accuracy : 0.8285
                 95% CI : (0.7844, 0.8668)
    No Information Rate : 0.75
    P-Value [Acc > NIR] : 0.0003097

                  Kappa : 0.5336
 Mcnemar's Test P-Value : 0.6025370

            Sensitivity : 0.8953
            Specificity : 0.6279
         Pos Pred Value : 0.8783
         Neg Pred Value : 0.6667
             Prevalence : 0.7500
         Detection Rate : 0.6715
   Detection Prevalence : 0.7645
      Balanced Accuracy : 0.7616

Attempt to write it as a .csv table results in the error message:
write.csv(confusionMatrix(xtab),file="file.csv")
Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) :
cannot coerce class ""confusionMatrix"" to a data.frame

Doing the whole work manually, for obvious reasons, is impractical and prone to human errors.
Any suggestions on how to export it as a .csv?
Comment: Is the thing you want to write in the form "key : value" ? `write.csv` is expecting a data.frame according to the error so you will have to massage your result into something it can take.
Comment: Just to clarify, you will have to take the result of `confusionMatrix` and put the data you require from it, into a data.frame.
Comment: @steveb yes, I see now. mroto in the response below outlined it very clearly.
Answer: Using caret package
results <- confusionMatrix(pred, truth)

as.table(results) gives
         Reference
Prediction  X1  X0
        X1  36  29
        X0 218 727

as.matrix(results,what="overall") gives
Accuracy       7.554455e-01
Kappa          1.372895e-01
AccuracyLower  7.277208e-01
AccuracyUpper  7.816725e-01
AccuracyNull   7.485149e-01
AccuracyPValue 3.203599e-01
McnemarPValue  5.608817e-33

and
    as.matrix(results, what = "classes") gives
Sensitivity          0.8953488
Specificity          0.6279070
Pos Pred Value       0.8783270
Neg Pred Value       0.6666667
Precision            0.8783270
Recall               0.8953488
F1                   0.8867562
Prevalence           0.7500000
Detection Rate       0.6715116
Detection Prevalence 0.7645349
Balanced Accuracy    0.7616279

Using these and write.csv command you can get the entire confusionMatrix info
Answer: Ok, so if you inspect the output of confusionMatrix(xtab, prevalence = 0.25) , it's a list:
cm <- confusionMatrix(pred, truth)
str(cm)

    List of 5
 $ positive: chr "abnormal"
 $ table   : 'table' int [1:2, 1:2] 231 27 32 54
  ..- attr(*, "dimnames")=List of 2
  .. ..$ Prediction: chr [1:2] "abnormal" "normal"
  .. ..$ Reference : chr [1:2] "abnormal" "normal"
 $ overall : Named num [1:7] 0.828 0.534 0.784 0.867 0.75 ...
  ..- attr(*, "names")= chr [1:7] "Accuracy" "Kappa" "AccuracyLower" "AccuracyUpper" ...
 $ byClass : Named num [1:8] 0.895 0.628 0.878 0.667 0.75 ...
  ..- attr(*, "names")= chr [1:8] "Sensitivity" "Specificity" "Pos Pred Value" "Neg Pred Value" ...
 $ dots    : list()
 - attr(*, "class")= chr "confusionMatrix"

From here on you select the appropriate objects that you want to create a csv from and make a data.frame that will have a column for each variable. In your case, this will be:
tocsv <- data.frame(cbind(t(cm$overall),t(cm$byClass)))

# You can then use
write.csv(tocsv,file="file.csv")

Comment: By default `byClass` and `overall` are named numerical vectors, which couldn't be cbinded together in their current form. If you transpose them, you create a character vector of the names beside the values. As for rounding them, probably yes, but it is generally good practice to ask new question if you have one, instead of cramming them in comments.
Comment: thank you, this is very close. In fact, I changed your code slightly to get what I want: `tocsv<-as.data.frame(t(data.frame(cbind(t(cm$byClass),t(cm$overall)))))` But, if I may ask you, why did you have transpose in the first place to begin with? Also, is there away to round the numeric values before we get to the `tocsv` stage? I know afterwards I can name the column, round it, and then replace it but I was wondering if there is a more efficient way on an initial stage.
Comment: Also I noticed that the code alters the original row `95% CI : (0.7844, 0.8668)` and instead displays these two rows: `AccuracyLower        0.7844134380` and `AccuracyUpper        0.8667985207`. Is there a way to keep the original way `95% CI : (0.7844, 0.8668)`?
Answer: I found that capture.output works best for me.
It simply copies your output as a .csv file
(you can also do it as .txt)
capture.output(
confusionMatrix(xtab, prevalence = 0.25),
 file = "F:/Home Office/result.csv")

Answer: The absolute easiest solution is to simply write out using readr::write_rds. You can export and import all while keeping the confusionMatrix structure intact.
Answer: If A is a caret::confusionMatrix object, then:
broom::tidy(A) %>% writexl::write_xlsx("mymatrix.xlsx")

optionally replace writexl with write.csv().
To also include the table on a separate sheet:
broom::tidy(A) %>% list(as.data.frame(A$table)) %>% writexl::write_xlsx("mymatrix.xlsx")


Template suggestion doesn't work with a custom menu link (custom route)

Question: In a module I have created a custom link by creating a custom route inside the mymodule.routing.file.yml and the mymodule.links.menu.yml file.
In my theme.theme file I have defined a hook_page_alter to add a template suggestion. With the debug mode and in the html code of the custom page, I see the proposed template suggestions.
<code><!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
* page--mycustomtemplate.html.twig
x page.html.twig
</code>
I have build a new template with this name 'page--mycustomtemplate.html.twig'. After clearing the cache, the new template isn't called, and the default page template is always actived.
Did I forget something?
Comment: Where you placed the template?
Answer: I'm guessing you put the template in your module folder and not in a theme?
You need to register the template with something like this in your .module file:
<code>/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  $theme['page__mycustomtemplate'] = [
    'template' => 'page--mycustomtemplate',
  ];

    return $theme;
}
</code>
Comment: Hi Leigh ! I tried to use your code in my custom module without success. The template is placed in the theme and in the module templates directory... Also I add ''base hook' => 'page' in your code without success...
Comment: In my controler, if I add this line : '#theme' => 'page__mycustomtemplate', the template is called from my theme directory. It's a possible solution for the moment. But, in the debug html code, the default page.html.tpl is always mentionned and my custom template don't appears in the template suggestions...


WebBrowser/Navegador em Java

Question: Como eu coloco uma espécie de um 'WebBrowser[.NET]' em um projeto em Java?
Sei que há motores de renderização livres como o Gecko, o qual é utilizado no Firefox. Porém não sei nem por onde começar, mesmo pegando um motor livre e pronto.
Queria uma luz de algum de vocês que saiba fazer isso. Procurei por vários tutoriais por aí de como fazer isso, mas nenhum resolveu meu problema!
Comment: http://stackoverflow.com/questions/48249/is-there-a-way-to-embed-a-browser-in-java
Comment: Swing, SWT, JavaFX?
Comment: Queria, se possivel, em java swing!
Answer: Nickolas, não sei se é isso que você precisa, mas me parece que sim.
O JavaFX fornece um componente chamado WebView  , que com a ajuda de WebEngine  pode ser usado para carregar páginas da Web junto com a construção do DOM e executar o JavaScript necessário.
Para aplicações Swing ele fornece outro componente chamado JFXPanel  que pode ser usado para incorporar componentes do JavaFX em aplicações Swing e por sua vez o JFXPanel é adicionado ao JFrame ou outros recipientes Swing.
Esse exemplo ai embaixo retirado do site http://www.javabeat.net/embedding-html-into-java-swing-applications/ pode ser exatamente o que você precisa.

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebView;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SwingHtmlDemo {
  public static void main(String [] args){

    SwingUtilities.invokeLater(new Runnable() {
    @Override
      public void run() {
        ApplicationFrame mainFrame = new ApplicationFrame();
        mainFrame.setVisible(true);
      }
    });

  }

}

/**
* Main window used to display some HTML content.
*/
class ApplicationFrame extends JFrame{

  JFXPanel javafxPanel;
  WebView webComponent;
  JPanel mainPanel;

  JTextField urlField;
  JButton goButton;

  public ApplicationFrame(){

    javafxPanel = new JFXPanel();

    initSwingComponents();

    loadJavaFXScene();
  }

  /**
  * Instantiate the Swing compoents to be used
  */
  private void initSwingComponents(){
    mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(javafxPanel, BorderLayout.CENTER);

    JPanel urlPanel = new JPanel(new FlowLayout());
    urlField = new JTextField();
    urlField.setColumns(50);
    urlPanel.add(urlField);
    goButton = new JButton("Go");

    /**
     * Handling the loading of new URL, when the user
     * enters the URL and clicks on Go button.
     */
    goButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        Platform.runLater(new Runnable() {
          @Override
          public void run() {
            String url = urlField.getText();
            if ( url != null && url.length() > 0){
                webComponent.getEngine().load(url);
            }
          }
        });

      }
    });

    urlPanel.add(goButton);
    mainPanel.add(urlPanel, BorderLayout.NORTH);

    this.add(mainPanel);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(700,600);
  }

  /**
  * Instantiate the JavaFX Components in
  * the JavaFX Application Thread.
  */
  private void loadJavaFXScene(){
    Platform.runLater(new Runnable() {
      @Override
      public void run() {

        BorderPane borderPane = new BorderPane();
        webComponent = new WebView();

        webComponent.getEngine().load("http://google.com/");

        borderPane.setCenter(webComponent);
        Scene scene = new Scene(borderPane,450,450);
        javafxPanel.setScene(scene);

      }
    });
  }
}

Comment: @NickolasCarlos Em swing "puro" não sei lhe dizer e até pesquisei para saber, mas pelo que via  solução é este JFXPanel mesmo, e coo pôde ver no código ele é 100% compatível com swing e de facil implementação...tente usar, quem sabe supre as suas necessidades numa boa.
Comment: E em swing, tem algum?
Answer: Isso não responde a pergunta, é uma resposta adicional para quem procura algo que use javascript mas como muita gente vai encontrar isso no Google está procurando uma forma de automatizar por linha de comando um navegador completo, tipo WebKit, é interessante considerar o PhantomJS.
O PhamtomJS tem versão para Windows, Linux e Windows, e, nas situações aonde é necessário mais do que simples web scrapping, ele é muito bom. Permite literalmente emular um navegador completo, tirar print screen e outras coisas.
O código abaixo, por exemplo, acessa o SOPT e tira um screenshot e salva na pasta local
// $ phantomjs nomedoarquivo.js
var page = require('webpage').create();
page.open('http://pt.stackoverflow.com/', function() {
  page.render('sopt.png');
  phantom.exit();
});

WebBrowser/Navegador em Java


How to communicate using iframe between 2 angular apps ?

Question: I have two different angular apps. I have to open a view of 'app_2' using iframe in 'app_1'. I also need to post some data  from 'app_1' to 'app_2'.
How to achieve this in angularJS?
Thanks in advance. #SOS
Comment: why you are rendering these two app in two different iframe? What you are going to achieve by doing this?
Answer: I would use consider using postMessage...
In Angular terms this would mean that one app would send messages and the other one would be listening to messages.
So on the App that sits within the iframe you can make a factory that does the following:
<code>/**
 * App that sits within iframe:
 *
 * Inject this factory into your controller and call
 * iFrame.messageParentIframe({hello: 'world'}) to send messages
 * to the parent iFrame
 */
angular
  .module('app')
  .factory('iFrameMessenger', function($window) {
    return {
      messageParentIframe: function(message) {
        $window.parent.postMessage(message, '*');
      }
    };
  });
</code>
On the parent iFrame your code should look something like this:
<code>/**
 * App that is on parent iframe:
 *
 * Just using a controller for the sake of simplicity,
 * but you could also use a Factory that only receives
 * messages from iFrames and handle them according to each
 * action, etc. You can get creative here on how you want
 * to handle it.
 */
angular
  .module('app')
  .controller('AppCtrl', function($window) {
    $window.addEventListener('message', function() {
        // handle messages received from iframe
    });
  });
</code>
Comment: I wanted something like that... Thanks a lot @sergiocruz :)
Comment: Great example. I think you should call removeEventListener() from the $destroy event in AppCtrl just to make sure nothing is leaked.
Comment: What about having the other away around (parent sending a message to child iFrame), so we have a complete example of a discussion between the two?
Comment: how to call iFrame.messageParentIframe({hello: 'world'})from the app that sits within iframe:? what is iFrame here?


Installing Zend Server via Puppet, on RHEL and Ubuntu?

Question: I'm learning Puppet by example and writing some modules to manage our current RHEL and Ubuntu servers. My first serious attempt is a Zend Server module.
Since Puppet has a Yumrepo, but no Aptrepo resource how would you structure a module to add the repo and install the packages in a distro independent way? People who use the module shouldn't have to care which distro the server runs.
Another thing. I'd like to have Puppet set the ZS admin password after installation, but can't find where it's set. Any idea?
Answer: Something like:
class usefulclass {
    if $operatingsystem == "RHEL" {
        repo { ...
            before => Package["zend"] }
    } else {
        file { "sources.list"... //or however you choose to manage sources.list
            before => Package["zend"] }
    }
}

Don't have a RHEL box handy, but just run facter operatingsystem to find out what the return value to look for is.
Comment: Thanks for this! I'm still wet behind the ears w/r/t Puppet, and trying to Puppetize libpam-google-authenticator for both our CentOS and Ubuntu servers. I was going to try to define the `yumrepo{}` blocks and set a `$require` array to require them in the CentOS/RHEL conditional, and set `$require = []` in the Debian/Ubuntu conditional, but this feels much more graceful!
Comment: So you'd suggest handling the operatingsystem switch in the modules instead of the manifests? Sounds like a good idea since it would make the modules more plug-and-play.
Comment: Indeed, that's how we do it.
Answer: I'm only beginning to checkout Puppet myself, but I did look at the file: /usr/local/zend/bin/gui_passwd.sh which changes that password (it's there in case you forget the original password).
At the bottom of the script, it puts the MD5'd password into the file: /usr/local/zend/gui/application/data/zend-server-user.ini, though it has to edit the file, with 'sed'.


Hibernate não fecha conexões/sessões no BD

Question: Estou com um problemão usando o Hibernate.
A cada vez que chamo um método que realiza uma consulta ou atualização no banco de dados, o hibernate abre uma sessão no banco e depois não fecha.
Já tentei de TUDO, mas realmente a cada vez que é chamado o em.getTransaction.begin(); ele cria a sessão no bd Oracle e não fecha mais.
Abaixo segue detalhes do meu código (persistence.xml,GenericDAO etc.)
persistence:
<persistence version="2.0"
             xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

    <persistence-unit name="FilaTrello" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>integration.wcc.model.Chamado</class>

        <properties>
            <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@//10.ip.aqui/xxxint.xxx.com.br"/>
            <property name="javax.persistence.jdbc.user" value="x_SUPORTE"/>
            <property name="javax.persistence.jdbc.password" value="x_SUPORTE"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9iDialect"/>
            <property name="hibernate.connection.shutdown" value="true"/>

            <property name="hibernate.synonyms" value="true"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="false"/>
          </properties>

    </persistence-unit>
</persistence>

GenericDAO:
package integration.wcc.dao;

import javax.persistence.*;
import javax.persistence.criteria.CriteriaQuery;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
abstract class GenericDAO<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("FilaTrello");
    private EntityManager em = emf.createEntityManager();;

    private Class<T> entityClass;

    public void beginTransaction() {
            em.clear();
            em.getTransaction().begin();

    }

    public void commit() {
        em.getTransaction().commit();
    }

    public void rollback() {
        em.getTransaction().rollback();
    }

    public void closeTransaction() {
       em.close();
    }

    public void commitAndCloseTransaction() {
        commit();
        closeTransaction();
    }

    public void flush() {
        em.flush();
    }

    public void joinTransaction() {
        em = emf.createEntityManager();
        em.joinTransaction();
    }

    public GenericDAO(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public void save(T entity) {
        em.persist(entity);

    }

    public void delete(Object id, Class<T> classe) {
        T entityToBeRemoved = em.getReference(classe, id);

        em.remove(entityToBeRemoved);
    }

    public T update(T entity) {
        return em.merge(entity);
    }

    public T find(int entityID) {
        return em.find(entityClass, entityID);
    }

    public T findL(Long entityID) {
        return em.find(entityClass, entityID);
    }

    public T findReferenceOnly(int entityID) {
        return em.getReference(entityClass, entityID);
    }

    // Using the unchecked because JPA does not have a
    // em.getCriteriaBuilder().createQuery()<T> method
    @SuppressWarnings({"unchecked", "rawtypes"})
    public List<T> findAll() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return em.createQuery(cq).getResultList();
    }

    // Using the unchecked because JPA does not have a
    // query.getSingleResult()<T> method
    @SuppressWarnings("unchecked")
    protected T findOneResult(String namedQuery, Map<String, Object> parameters) {
        T result = null;

        try {
            Query query = em.createNamedQuery(namedQuery);

            // Method that will populate parameters if they are passed not null and empty
            if (parameters != null && !parameters.isEmpty()) {
                populateQueryParameters(query, parameters);
            }

            result = (T) query.getSingleResult();

        } catch (NoResultException e) {
            System.out.println("No result found for named query: " + namedQuery);
        } catch (Exception e) {
            System.out.println("Error while running query: " + e.getMessage());
            e.printStackTrace();
        }

        return result;
    }

    @SuppressWarnings("unchecked")
    protected List<T> findListResult(String namedQuery, Map<String, Object> parameters) {
        List<T> result = null;

        try {
            Query query = em.createNamedQuery(namedQuery);

            // Method that will populate parameters if they are passed not null and empty
            if (parameters != null && !parameters.isEmpty()) {
                populateQueryParameters(query, parameters);
            }

            //result = (T) query.getSingleResult();
            result = (List<T>) query.getResultList();

        } catch (NoResultException e) {
            System.out.println("No result found for named query: " + namedQuery);
        } catch (Exception e) {
            System.out.println("Error while running query: " + e.getMessage());
            e.printStackTrace();
        }

        return result;
    }

    private void populateQueryParameters(Query query, Map<String, Object> parameters) {
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            query.setParameter(entry.getKey(), entry.getValue());
        }
    }
}

DAO de Acesso:
public class FilaChamadoDAO extends GenericDAO<FilaChamado> {

    private static final long serialVersionUID = 1L;

    public FilaChamadoDAO() {
        super(FilaChamado.class);
    }

public List<FilaChamado> findTicketsByFila(int idFila,String listType) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("filaNumber", idFila);
        parameters.put("listParam", listType);

        return super.findListResult(FilaChamado.FIND_TICKETS_FILA_BY_FILA, parameters);
    }

Ai eu tenho uma classe facade para cada Model meu, que faz a interface de acesso ao DAO:
 public class FilaChamadoFacade {

        private FilaChamadoDAO FilaChamadoDAO = new FilaChamadoDAO();

        public List<FilaChamado> listAll() {
            FilaChamadoDAO.beginTransaction();
            List<FilaChamado> result = FilaChamadoDAO.findAll();
            FilaChamadoDAO.closeTransaction();
            return result;
        }

public List<FilaChamado> findTicketsByFila(int idFila,String listaDestino) {
        List<FilaChamado> result = null;
        try {
            FilaChamadoDAO.beginTransaction();
            result = FilaChamadoDAO.findTicketsByFila(idFila, listaDestino);
            FilaChamadoDAO.flush();
        } catch (HibernateException e) {
            if (FilaChamadoDAO != null) {
                FilaChamadoDAO.rollback();
            }
            e.printStackTrace();
        } finally {
            FilaChamadoDAO.closeTransaction();

        }
        return result;
    }

Quando eu chamo o método ListAll() ou alguma namedQuery, não consigo de forma alguma fechar essas conexões.
Chamo as transações em minha main:
public class TestNamedQuery {
    public static void main(String[] args) {

        TrelloUser trelloU = new TrelloUser();
        TrelloUserFacade facade2 = new TrelloUserFacade();
        List<TrelloUser> trelloUsers1 = new ArrayList<TrelloUser>();
        trelloUsers1 = facade2.listAll();

        for (TrelloUser trelloUser : trelloUsers1) {
            if(trelloUser.getUserToken() != null) {
                System.out.println("Selectss do usuario: "+trelloUser.getUserName());
                ChamadoCard cards = new ChamadoCard();
                cards.InsereChamado(trelloUser);
            }
        }

    }
}

Como podem ver, na minha classe de facade cada vez que inicio uma transaction logo em seguida eu a fecho, mas isso não acontece no Oracle, onde são criadas uma sessão para cada beginTransaction.
Answer: Depois de muitas tentativas, encontrei uma publicação dizendo que devo "commitr" ou "rollback" sempre que chamo o método beginTransaction () para o meu Entity Manager.
Então eu mudei meu código na classe'GenericDA.java`:
public void closeTransaction() {
        em.getTransaction().commit();
        em.close();
    }

Eu ainda estou tentando entender por que o Hibernate me obriga a COMMITAR uma transação, mesmo em uma declaração de consulta, e eu acho que posso ganhar uma ótima performance sem fazê-lo.
Mas essa mudança funcionou muito bem para mim
Answer:
Eu ainda estou tentando entender por que o Hibernate me obriga a COMMITAR uma transação

Select é uma DML data manipulation language, usando Select Into tu pode alterar tabelas, não sei exatamente se o select into possui equivalente em JPA mas em SQL faz sentido.
http://royalarun.blogspot.com.br/2014/01/why-select-is-dml-statement-in-sql.html
Usando containers como spring-data ou EJB(java EE) tu pode delegar ao framework o controle da transação, eliminando todo esse boilerplate.
https://dzone.com/articles/how-does-spring-transactional


How to write custom validation for columns in row edit plugin in EXTJS

Question: I am new to EXTJS. I am using RowEditing plugin in grid panel to edit a row.
When user enters a value, I want to check if the entered value exists between a certain range. Example: 1 and 100. This value range differs for different columns in the row. How to write this custom validation?
This is my code. I want to write custom validation for Sampling interval and Latency interval.
<code>deployAnalyticsGridView = Ext.create(
                    'paginggrid.view', {
                        store : THIS.GridStore,
                        region : 'center',
                        title : '--------',
                        selType : 'checkboxmodel',
                        multiSelect : true,
                        enableSearch : true,
                        searchColumns : ["Name", "Sampling Interval", "Latency  Interval","Threshold"],
                        defaultColumnSelection : 2,
                        // grid columns
                        columns : [{
                                    id : 'name',
                                    text : "Name",
                                    dataIndex : 'hostName',
                                    flex : 1

                                }, {
                                    id : 'SamplingInterval',
                                    text : " Sampling Interval",
                                    dataIndex : 'SamplingInterval',
                                    flex : 1,
                                      editor: {
                                            xtype: 'numberfield',
                                            allowBlank: false,
                                            flex : 1
                                        }
                                }, {
                                    id : 'LatencyInterval',
                                    text : "Latency Interval",
                                    dataIndex : 'LatencyInterval',
                                    flex : 1,
                                      editor: {
                                            xtype: 'numberfield',
                                            allowBlank: false,
                                            flex : 1
                                        }
                                }, {
                                    id : 'LatencyThreshold',
                                    text : "Latency Threshold",
                                dataIndex :'LatencyThreshold',
                                    flex : 1,
                                    editor: {
                                        xtype: 'numberfield',
                                        allowBlank: false,
                                        flex : 1
                                    }
                                }
                        ],
                         plugins: [                                Ext.create('Ext.grid.plugin.RowEditing', {
                                       clicksToEdit: 2
                                   })],
                        actionButtons : [this.Action1 , this.sAction2]
                    });
</code>
Answer: You just need to properly configure editor for your field. You can use code like this:
<code>        {
            text: "Some Number",
            width:120,
            dataIndex: 'num',
            editor : {
                xtype: 'numberfield',
                allowBlank:false,
                validator: function(value) {
                    return (value > 5 && value < 100) || 'Number must be > 5 and < 100';
                }
            }
        },
</code>
Fully working example here: http://jsfiddle.net/guyfawkes/q3TnT/
Comment: Another question . when I click my row for editing the cells  shrinks in size . how to maintain my  width  of the cell constant  when it is clicked for editing
Comment: Can you show screenshot? I dont see it neither in Firefox or Chrome.


Weird Behavior With Heaps and Negative Numbers

Question: I have an algorithm that creates two heaps, minHeap and maxHeap. The only difference between the two is that maxHeap reverses the sign of minHeap, a simple hack to use Python's heapq data structure as a max heap. Here's my code for creating the heaps (the heap key is basically the number of workers in a dictionary for a given day of the week):
<code>for day in self.weekDict:
    if day != 'Saturday' and len(self.weekDict[day]) != 0: #saturdays and holidays not part of optimization
        heapq.heappush(minHeap, (len(self.weekDict[day]), day))
        heapq.heappush(maxHeap, (-len(self.weekDict[day]), day))
</code>
The minHeap works just as expected, but the max heap gives me odd behavior when there are more than one of the same key. See below:
<code>[(-8, 'Thursday'), (-7, 'Monday'), (-5, 'Friday'), (-7, 'Wednesday'), (-7, 'Tuesday')]
</code>
Why are the last two days out of order? Is it because only the first day is guaranteed to be the minimum, and once I pop the first day off the heap will automatically adjust itself?
Answer: A heap is not a sorted list.  A heap is a binary tree which happens to be stored as a list.  The elements of a heap have the following property:
a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all k in a
See the docs for a fuller explanation and a nice picture to help follow the structure: http://docs.python.org/2/library/heapq.html#theory
Answer: Heaps are not sorted lists.  They are lists from which you can quickly pull the first element, and also maintain the structure so that you can continue to quickly pull the next first element.  When you look at the heap as a list, the elements will not be fully sorted.


PHP OOP: Is it possible to pass parameters to a class __destruct?

Question: If needed, parameters can be passed to a class via it's constructor.
class Test {

  public function __construct($echo) {
    echo $echo;
  }

}

$test = new Test('hello'); // Echos "hello"

Is there any way of passing parameters to the __destruct?
class Test {

  public function __construct($echo) {
    echo $echo;
  }

  public function __destruct($string) { // Is this possible?
    // Do something with this string
  }

}

Answer: No, Destructors have only one signature
void __destruct ( void )

Manual
Comment: Thanks, I couldn't seem to find that anywhere.
Answer: It's not possible.
But you can use a instance field like this:
class Test {
  var $value;
  public function __construct($echo) {
    this->value = $echo;
  }
  public function __destruct() {
    echo $this->value;
  }
}


Why might one *not* want to use a capo?

Question: Apparently some guitarists use a capo in certain circumstances, while some others use one never or rarely.
This question is for those who use it reluctantly or never.  Why?  Why are some people reluctant to use a capo?
Comment: You use a capo to accommodate a vocalist while still being able to play the same chords.
Comment: @WayneConrad -- these answers aren't biased against capos; they are written by people who don't like to use capos. Everyone knows that capos are used by some players (but certainly not all players of folk or Americana choose to use capos, either). If you have something to add, please write your answer, but observe that the question is not "are capos a good thing", but rather more like "why do some choose not to use capos".
Comment: Or to have open strings at different notes without retuning. Or to play the same open chords with different voicing. There are many different reasons.
Comment: I cannot write an answer because the question is protected now, but I feel that all the answers are biased against capos. The reason might be the classical training of the authors. However, in my band I regularly use a capo for rhythm guitar to accomodate our singer. Sometimes even in high frets like 7th. I could easily transpose the chords without capo, but I like the sound of open chords on high frets for some songs. And especially when you are playing fast songs, every barred chord that you can circumvent is helpful.
Comment: @foreyez - That's worth writing an answer.
Comment: @Ian - If you like I'll put what you wrote into a community answer.
Comment: The answers _are_ biased against capos.  Capos are commonly used in American folk music, both informally and on stage, for all the reasons @Ian gives.
Comment: @aparente001 That's a good idea.
Answer: The number one problem of capos is they usually throw off the tuning a bit and it's a pain to fix the tuning with the capo in place.
They also change the action - sometimes in good ways, sometimes in bad.
The main reason a lot of guitarists rarely or never use capos is probably because capos are not widely useful. They only help in fairly specific situations. When you want or need to play open chords and want or need those chords to be different from the open chords available with standard tuning, you either have to use a capo or retune your guitar. Personally I play and write a lot of guitar music that doesn't use open chords. It's not that I'm avoiding open chords, it's just that I don't find them to be particularly useful or interesting.
That said, I did write a song a few months ago that called for a capo. But that's pretty rare for me. It's not about having reasons to not use a capo as much as it is about not having any reason to use one.
Comment: @Tim The capo interferes with the re-tuning though, because it is holding down the strings, so the change in tension behind the capo is not directly communicated to the vibrating part of the string. So have have to slack it off and re-clamp it, or other ways to persuade the string to register the tuning change. It's definitely more fiddly than without a capo.
Comment: @blueskiwi - that's the problem with a lot of capos - their tension is over the top. I ocasionally use a G7th capo, which seems to alleviate that problem - so much so that it doesn't untune it in the first place. We could use the same argument about a barring finger - which can still put a chord out of tune - but we learn to temper pressure.
Comment: Can't see why tuning is a pain *with* a capo in place - yes, re-tuning is often the order of the day - and re-re-tuning after, but 'a pain'?
Comment: @Tim I have a G7th and still have tuning trouble with it. It's definitely the best capo I've ever used, but that doesn't make it perfect.
Answer: Well, I'm one of those, and the reason is just not being used to it (and laziness).
For a long time, I haven't had a capo at all. Then I got one, but it's quite clumsy to use and it tends to disassemble itself, so it would probably take 30 sec to put it on the guitar and tighten it up. (My grandfather handmade that capo years ago, in the time when our country was deep in the Communism era, and you couldn't get even basic stuff in stores back then, let alone something as highly specialized as a capo!) So it's more of a family relic than a capo, and I don't even try to use it (30 sec is just too much).
Combine that with the fact that I'm a classical guitarist, and the classical guitar doesn't make any use of capo whatsoever (don't ask me why, it just doesn't)... and you probably see how it comes that I don't even try to put on a capo when the other people decide that it would be great to play a song in B flat minor. It's just easier to grit my teeth, recite "B flat E flat A flat D flat G flat"... and play. It worked 1000 times before, it will work one time more.
So... not that I have anything against capos, I just can do without and I got too much used to it. (Let me add that I just don't meet situations where a capo would be necessary — I either play classical guitar that uses no capo ever, or some songs with other people, and then there's no reason to.)
P. S.: I just tried playing with the capo. It truly did take 30 sec to put on, and I found that it messes up my fretboard orientation quite badly. I just see the higher positions as if the capo wasn't there. So I maybe put a capo on the third fret and play in "E minor". I tell to myself "Now I want a high E". And that's on the 12th fret, so I hit that. Unfortunately the high E is not much usable as a tonic in G minor.
Comment: @Ian: Please read the whole post. The capo in question was handmade, sort of a closable U shape. You need to first insert a screw with a pad into the U, close the U around the neck and tighten the screw. Also I really don't blame the capo. I just explain that having this kind of capo leads to me not using it.
Comment: *It truly did take 30 sec to put on* - What kind of capo takes 30s to put on? I got two, one is spring loaded and the other is a clamp and both take a few seconds. Apparently your playing style doesn't lend itself to playing with a capo, which is fine. But don't blame the capo for that.
Comment: It's still a bad argument to make when virtually every capo you can buy takes a second or two to put on.
Answer: When I first started playing out, I had to switch between guitars almost every song, and we tried to keep the show moving, so I didn't have time to retune and didn't have money to buy multiple capos.
Also, I already had internalized the "learn three voicings of every chord" mantra by the time I started playing out, so it wasn't a big deal in terms of being able to play in any given key. Because I was often playing lead, I needed to be able to switch between single-note lead lines and rhythm/chord work instantly, so cutting off access to parts of the neck and/or sticking to 0-position "cowboy chords" was not a good solution.
At this point, capos are a millstone, and I only use them if I'm jamming with other people and I'm tuned down a half step.
So my motivations not to use a capo were:

rhythm of the performance as a whole/intersong transition speed
retuning speed
money
proficiency was already there
Comment: Also, I used to run a guitar store, so I saw a lot of repairs, especially of street musicians' guitars. The heavy capo users had MASSIVE premature fret wear at their favorite capo frets. Some of them would have a second capo in place to account for the fact that a lower-down-the-neck fret was so divoted that it was now little more than a nut/string guide, and the second capo forced the next available intact fret to be the new nut. I realize this makes no sense, but this is what I saw.
Answer: I think you question has a skewed assumption in it.  I wouldn't say that the lack of use is reluctance.  It's training.  Classical guitarists are trained to not need it.  We use out index finger as a capo when needed.
Comment: True! I've just started messing (I won't say playing!) with a Spyder capo. Dare say that could facilitate drop D with no trouble. Might even work as such with everything except bottom string capoed on fret 2? Re-tunung on the fly is sometimes a necessity - and those who don't rely on tuners are the best!
Comment: @Tim Not quite.  Partial capos have been around for a very long time.  Every new user is under the misapprehension that it'll "let them play in  without trouble", because marketing for every partial capo says that, and they all find pretty quickly that this isn't true.  If you only want drone strings, then OK; but the distinctive tones from altered tunings are far more about what they make available (or unavailable) with fretted playing, and that is fundamentally unchanged with a capo.
Comment: Most capoists (capoers?) seem to rely on their capos to permit an easy change of key. But unsuccessfully when the key needs dropping..!
Comment: Funny, a drop D capo would be quite an anomaly.  And I've seen classical guitarist drop tune in the middle of a song.  Key twisting in real time is a technique.
Answer: I don't ever play with a capo; that is not to say that I haven't played with a capo, just not in the last 30 years or so. My first capo was a piece of utter garbage, and that probably didn't help to raise the value of capos in my estimation. I have had better capos since then, but still I don't use them.
There is nothing inherently wrong with capos or with using a capo; a capo is just a tool. I don't use capos because I don't need them. Unlike some others, I don't think that it is "lazy" to use a capo (although, I did think this when I was a younger player). There are certainly valid reasons to use a capo, but for me and the way I play a capo causes more problems than it solves.
Capos can be helpful for playing in unfamiliar keys, but I don't have any problems playing in any key without a capo. Capos are very helpful for playing cowboy chord voicings in positions higher on the neck, but I don't really use those big Mel Bay voicings anyway. Capos can provide open string notes that aren't usually available (and this is the only reason I would think about using one).
Capos do get in my way, by cutting off my access to the frets below the capo. Frankly, having a capo on the neck just feels awkward to me. I do use open strings in my playing fairly often, and if I took the time to develop some capo technique I might be able to extend my open-string technique. But there is so much to work on, and so little time. Alternate tunings also offer many open string opportunities, but I don't use those either; it seems like there is barely enough time for me to work on playing in standard tuning.
So, I don't use a capo because it has almost nothing to offer for me as a player. That doesn't mean that other players don't derive benefits from using a capo, and I actually think that there is potential to use a capo to great effect; maybe one day I'll make the time to work on this.
Answer: I'm of the impression a lot of guitar purists think using a capo is cheating. I use one occasionally ( mainly to avoid first positon Bb chording) so I guess in fact I'm cheating when when I use it. I know some folks like the way open strings ring out in first position and avoid using a capo for that reason.
Comment: 'Open strings in the first position'? How's that?
Comment: @Tim- I asked the same question to a much more experienced player than I many years ago and this was his answer. I had never noticed until he mentioned it, but open strings seem to sustain or ring out longer when playing without a capo. Or perhaps it's all in our head, either way, its one of the reasons I'm aware of that some folks avoid using a capo.
Comment: @skinnypeacock — Yes, capo makes the whole guitar sound a bit more muffled and mellow. However, in keys with lots of flats you can't use any open strings anyway, so you may as well as use that capo.
Answer: Here are my reasons:

I keep losing them. I have two that I bought and they might be in some drawer or under my bed or something. I don't even have the motivation to go and find them. But for over a decade that I've been playing guitar, I keep losing capos. It's just the way it's always been and I've accepted it.
They're hard to put on. That spring clamp is a pain to squeeze. This might be a bit of laziness, but still, it makes me not want to do the "work".
It's not a part of the guitar. This is in relation to 1. but because it's not a part of the guitar, when my guitar is thrown around somewhere in my room I don't feel like BOTH getting my guitar AND getting the capo. I'll just get the guitar.
I like to experiment with alternative tunings. Especially open tunings where I can use the open strings as drones as I play fingerstyle guitar alot. Capos keep the same tuning, just make the pitch higher. Also for alternative tuning all I need is my phone + a tuning app when I retune. I don't need to go "find the capo".
I feel like using a capo is cheating. If you want higher pitches you can play chords in higher octaves. Without a capo, you're forced to practice important techniques such as CAGED to find alternative versions of chords so you get better at understanding the entirety of the fretboard. If you just use a capo then you're inclined to stick to playing open position chords.

That said, sometimes I like playing the same song in a higher pitch in a quick way, so that's why I keep buying capos (and losing them).

Why might one *not* want to use a capo?


Sending mail results in "Sender address rejected: Domain not found"

Question: The setup: WHM/CPanel CentOS 5 server running Exim and Courier for mail services, and BIND for domain name services.
I recently moved servers. The old server was running a HIGHLY similar configuration, and all accounts were ported via WHM. However, the server is unable to send, and sometimes receive email.
Errors I am seeing (when I do get an error mail back) state:
450 4.1.8 : Sender address rejected: Domain not found
Edit for clarity: this is the error response from remote mail servers. Numerous independent mail servers come back with the same error.
(Email address is merely one valid example)
My first instinct of course was to check the domain records. However, k-t.org appears to have a valid record (including an MX record), even after running it through domain checks on a completely different server elsewhere and online. Note that the issue appears to happen with all the domains hosted on the server, not just k-t.org
I have also ensured that a PTR was created.
My Googling has only lead me to people who had fairly basic DNS mistakes, but either I'm blind/dumb (possible, DNS is not my strong suite), or it's something that is a bit more archaic. I've run out of ideas, and I can't seem to find anything that could explain why servers are unable to resolve the domains. There doesn't seem to be anything missing or incorrect.
Comment: What is the name of your server? If you have it generically named or not a mappable name, then this could be some of the problems.
Comment: It is named server.sorrowind.net which has an A record in the sorrowind.net complete DNS record. I should add that sorrowind.net is also the home of the nameservers (ns1/ns2).
Answer: It's not a DNS issue.  Your exim hasn't been configured to receive mail for that k-t.org  domain.
Take a look at:
http://www.exim.org/exim-html-3.20/doc/html/spec_43.html
I'm not familiar with cPanel, so I don't know if that's something you would configure through cPanel.
Update:
OK, it's a different issue: I just did an SMTP transaction against k-t.org, sending to firstname.lastname@example.com (Subject: Test message), which was accepted.
Since I'm able to retrieve DNS records for the MX and the A for the MTA, it's time to look at the remote server.  Do they have stale DNS records?
Comment: I'm not sure you understand the issue. My exim service isn't receiving the mail. My server is sending the mail, and the remote server is returning with that error message. Exim is most certainly configured to receive mail for k-t.org (along with every other domain), as this is part of how CPanel works with Exim.
Comment: I've updated my response.  The next step is to check for stale DNS.
Comment: I have no idea if they have stale records. This issue occurs for probably 90% of all mail servers on the internet, not just a single one (GMail is an example of an exception to the rule). I wouldn't know how to even check if their records are stale. It's been well over 24 hours since the last major DNS change occurred. Thanks for walking through this.
Comment: Hmm.  So, from where I'm sitting, WHOIS and DNS look correct. TTL is 4 hours, so 24 hours is more than enough time.  Were the TTLs different before the last DNS change?
Comment: No, they've been the same for many, many days.


help with LibSVM input data

Question: I am using the LibSVM tool for my support vector classification implementation:-
The first line in my input data file looks as so:-
+1 15752:47 6279:45 475:40 5231:30 515:29 7529:28 11623:24 274:24 15431:21 7342:20 4819:20 7598:18 8853:17 11134:16 501:16 911:15 4656:15 5875:14 10725:13 7334:13 13762:13 8295:12 9314:12 317:12 10641:12 2690:12 8771:12 4698:11 11519:10 10069:9 10019:8 1120:8 15017:8 254:8 7900:8 5395:8 486:8 1763:8 11183:7 9163:7 9219:7 1827:7 11901:7 4068:6 15592:6 9925:6 3464:5 8408:5 15348:5 8432:5 10064:5 6319:4 5729:4 8334:4 11817:4 6238:4 4521:4 11761:4 328:4 15876:4 6494:4 280:4 14628:4 5514:4 6383:4 9149:4 2456:4 6741:4 482:4 2773:4 10873:3 8715:3 8802:3 11478:3 11848:3 12269:3 10592:3 12911:3 11051:3 10798:3 8412:3 232:3 7654:3 1210:3 502:3 12687:3 14459:2 2725:2 9851:2 5799:2 16046:2 3612:2 1440:2 8503:2 245:2 9780:2 322:2 11902:2 8977:2 14949:2 5710:2 6423:2 9896:2 5507:2 10646:2 9932:2 14894:2 3997:2 13429:2 9845:2 8547:2 2720:2 861:2 2830:2 5703:2 6994:2 13973:2 3086:2 262:2 7793:2 208:2 3221:2 13229:2 13350:2 372:2 10384:2 3970:2 13506:2 9720:2 8981:2 9296:1 10276:1 15098:1 6631:1 383:1 6510:1 13304:1 9646:1 8233:1 1080:1 8537:1 12129:1 10711:1 14569:1 2969:1 1215:1 12435:1 7689:1 12626:1 14609:1 13474:1 4488:1 103:1 621:1 12430:1 617:1 514:1 11673:1 215:1 8817:1 10968:1 4717:1 1807:1 5737:1 3156:1 14320:1 13457:1 12411:1 9596:1 15028:1 10531:1 4301:1 4799:1 6013:1 7619:1 6717:1 9344:1 1817:1 15868:1 11307:1 9632:1 6945:1 9916:1 11899:1 883:1 11696:1 14503:1 316:1 4012:1 9994:1 8501:1 1847:1 12534:1 14966:1 11800:1 8093:1 13403:1 7309:1 5957:1 6538:1 2535:1 7042:1 13792:1 15001:1 4894:1 4921:1 13739:1 15875:1 15802:1 14253:1 10376:1 974:1 1882:1 2397:1 8105:1 4725:1 7707:1 7506:1 9749:1 8640:1 12566:1

The name of my input data file is --> a1a
I tried to run the program on my windows command prompt as
svm-train a1a

I get the following error
Wrong input format at line 1

Could somebody help me out here? I can't seem to figure out what's wrong.
Thanks.
Answer: The feature numbers (14253, 10376, etc) have to be listed in increasing order. Once you do that, svm-train will take that data. So, for example, your file needs to begin:
+1 103:1 208:2 215:1 232:3 245:2 254:8 262:2 274:24 280:4 316:1 317:12 322:2 328:4 372:2 383:1 475:40 482:4 486:8 501:16 502:3 514:1 515:29 617:1 621:1 861:2 883:1 911:15 974:1 1080:1 1120:8 1210:3 1215:1 1440:2 1763:8 1807:1 1817:1 1827:7 1847:1 1882:1 2397:1 2456:4 2535:1 2690:12 2720:2 2725:2 2773:4 2830:2 2969:1 3086:2 3156:1 3221:2 3464:5 3612:2 3970:2 3997:2 4012:1 4068:6 4301:1 4488:1 4521:4 4656:15 4698:11 4717:1 4725:1 4799:1 4819:20 4894:1 4921:1 5231:30 5395:8 5507:2 5514:4 5703:2 5710:2 5729:4 5737:1 5799:2 5875:14 5957:1 6013:1 6238:4 6279:45 6319:4 6383:4 6423:2 6494:4 6510:1 6538:1 6631:1 6717:1 6741:4 6945:1 6994:2 7042:1 7309:1 7334:13 7342:20 7506:1 7529:28 7598:18 7619:1 7654:3 7689:1 7707:1 7793:2 7900:8 8093:1 8105:1 8233:1 8295:12 8334:4 8408:5 8412:3 8432:5 8501:1 8503:2 8537:1 8547:2 8640:1 8715:3 8771:12 8802:3 8817:1 8853:17 8977:2 8981:2 9149:4 9163:7 9219:7 9296:1 9314:12 9344:1 9596:1 9632:1 9646:1 9720:2 9749:1 9780:2 9845:2 9851:2 9896:2 9916:1 9925:6 9932:2 9994:1 10019:8 10064:5 10069:9 10276:1 10376:1 10384:2 10531:1 10592:3 10641:12 10646:2 10711:1 10725:13 10798:3 10873:3 10968:1 11051:3 11134:16 11183:7 11307:1 11478:3 11519:10 11623:24 11673:1 11696:1 11761:4 11800:1 11817:4 11848:3 11899:1 11901:7 11902:2 12129:1 12269:3 12411:1 12430:1 12435:1 12534:1 12566:1 12626:1 12687:3 12911:3 13229:2 13304:1 13350:2 13403:1 13429:2 13457:1 13474:1 13506:2 13739:1 13762:13 13792:1 13973:2 14253:1 14320:1 14459:2 14503:1 14569:1 14609:1 14628:4 14894:2 14949:2 14966:1 15001:1 15017:8 15028:1 15098:1 15348:5 15431:21 15592:6 15752:47 15802:1 15868:1 15875:1 15876:4 16046:2

help with LibSVM input data


Remove entire line from csv if matches a string from within a txt file

Question: I have a csv formatted like:
Username,Email,Fn,Ln,BusUnit,Department,Manager
firstname.lastname@example.com,email@example.com,USER1,Ops,Whse,"""MGR1"""
firstname.lastname@example.com,firstname.lastname@example.com,USER2,Proc,Acct,"""MGR2""

I have a txt file formatted like:
email@example.com
firstname.lastname@example.com

I would like to remove all lines in the CSV unless they match on any of the emails in the txt file.
This is clearly incorrect, but it's what I have so far
$users = import-csv .\user.csv
$unresolved = gc .\unresolved.txt

get-content $users |? {$_ -match $unsresolved} |export-csv export.csv -notype

Answer: What's $lms? Why is get-content there on the last line? How about...
$users = import-csv .\user.csv
$unresolved = gc .\unresolved.txt

$users |? {$_.Email -notin $unresolved} |export-csv export.csv -notype

Comment: Sorry, the $lms thing was a typo i forgot to change when i posted it, thanks for the reply!


Low Maximum execution time

Question: I was installing drupal commons on xampp server i got this error, PHP Max Execution Time 30 Your PHP execution time is too low, please set it greater than or equal to 120 seconds. How do i adjust the php execution time so that i can proceed with the installation?
Comment: Adding to @Smalution comment, you should restart your server once you done changes in php.ini
Comment: make change in php.ini file. Search max_execution_time and set to 120
Answer: Follow  below steps and change that file.

Go to your XAMPP installation Folder and edit - ..\xampp\php\php.ini file.
Use the FIND function of your editor an look for "max_execution_time"
in that line you will see the value attributed to "max_execution_time"
change it to max_execution_time=120
Save the php.ini file.
Restart the XAMPP Server
Proceed with Drupal Commons installation.

Low Maximum execution time


Erro de ao fazer comando aggregate com $geoNear do MongoDB

Question: Eu possuo uma collection chamada location com os seguintes dados:
{
    _id: ObjectId("5a900f4af1b7fd855010c0cf"),
    car_id: ObjectId("5a85c26a35fdcf1098c23480"),
    location: {
        type:"Point",
        coordinates:[-54.585186,-25.447471]
    }
}

E estou tentando fazer um comando aggregate no mongoshell da seguinte forma:
db.location.aggregate([{
  $geoNear: {
    near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
    distanceField: "dist.calculated",
    includeLocs: "dist.location",
    spherical: true,
    maxDistance: 10000
  }
}])

Mas sempre recebo esta mensagem de erro:
assert: command failed: {
        "ok" : 0,
        "errmsg" : "geoNear command failed: { ok: 0.0, errmsg: \"error processing query: ns=taxxer.location limit=100Tree: GEONEAR  field=location.location.coordinates maxdist=10000 isNearSphere=1\nSort: {}\nProj: { $...\", code: 2, codeName: \"BadValue\" }",
        "code" : 16604,
        "codeName" : "Location16604"
} : aggregate failed

Não consigo descobrir o que estou fazendo de errado.
Answer: Resolvi o problema ao trocar o nome da minha collection onde estão as location para outro.
Aparentemente a collection não pode ter o mesmo nome do atributo, como no erro:
field=location.location.coordinates

Ao trocar o nome para outra coisa, por exemplo, carlocation, o comando já funciona.


which is the best way to build the tree view control using string collection

Question: I am trying to prepare the tree view control from folowing strings.
    "US|New York|D.M.Street"
    "US|New York|ShoppingMall"
    "INDIA|Dehli|G.M. Road"
    "INDIA|Mumbai|Harbour Street"
    "US|Washington|WhiteHouse"
    "INDIA|Dehli|Rajpath"
    "INDIA|Mumbai|CST"

I want to populate the tree view from this collection in C#. in following manner
Country
|
US => NewYork   ==========>D.M.Street
|      |        ==========>ShoppingMall
       |
|      Washinton==========>WhiteHouse
|
INDIA=>Dehli    ==========>G.M. Road
      |         ==========>Rajpath
      |
      Mumbai    ==========>CST
                ==========>Harbour Street

how i can prepare this ? usning collection or else way?
Comment: Is matching "Newyork"and "New York" into one node actually part of the solution you are seeking?
Answer: Here's how I would approach this:
Create a class and a collection to hold a nested hierarchy of elements (this can be expanded later if more detail is needed).
public class Element
{
    public Element(string Name)
    {
        this.Name = Name;
    }
    public string Name { get; set; }

    public ElementCollection Children = new ElementCollection();

    // This method is used to add the specified child name if it does not currently
    // exist, or return the existing one if it does
    public Element AddOrFetchChild(string sName)
    {
        Element oChild;
        if (this.Children.ContainsKey(sName))
        {
            oChild = this.Children[sName];
        }
        else
        {
            oChild = new Element(sName);
            this.Children.Add(sName, oChild);
        }
        return oChild;
    }

}

public class ElementCollection : System.Collections.Generic.Dictionary<string, Element>
{

}

Then parse your data into the collection (note that this will support any level of nesting in your record structure without a need to modify the code):
        string[] asLines;

        // ToDo: Add code here to populate the collection of lines to process

        // Create a base element that makes popuplation of the elements easier
        Element BaseElement = new Element("");

        // Cycle through each of the lines
        foreach (string sLine in asLines())
        {
            // Get the components out of the line
            string[] asElements = sLine.Split("|");

            // Starting with the base element
            Element oParentElement = BaseElement;

            // Cycle through each of the elements that were found, adding the current value to the parent's
            // collection of children, then using the new or found item as the parent for the next item in the list
            for (int nI = 0; nI < asElements.Length; nI++)
            {
                oParentElement = oParentElement.AddOrFetchChild(asElements[nI]);
            }
        }

        // Finally, add the nodes to the tree recursively
        AddNodesToTree(BaseElement.Children, this.treeView1.Nodes);

and this is the recursive method used to add the items to the tree
    ///
    /// A recursive method to add all of the records to the specified collection of nodes
    ///
    /// <param name="cRecords"></param>
    /// <param name="cNodes"></param>
    private void AddNodesToTree(ElementCollection cRecords, TreeNodeCollection cNodes)
    {
        foreach (Element oRecord in cRecords.Values)
        {
            TreeNode oNode = new TreeNode();
            oNode.Text = oRecord.Name;
            oNode.Tag = oRecord;
            cNodes.Add(oNode);
            // Now add the node's children if any
            if (oRecord.Children.Count != 0)
            {
                AddNodesToTree(oRecord.Children, oNode.Nodes);
            }
        }

    }

Comment: working perfect for me . i adde this with telerik controls also.
Answer: Given a GetData() function that returns IEnumerable<string> with all of the string data, and assuming you want a jumble of LINQ:
  var nodes = GetData().Select(data => data.Split('|')).GroupBy(x => x[0]).Select(
    country => new TreeNode(country.Key, country.GroupBy(x => x[1]).Select(
      city => new TreeNode(city.Key, city.Select(
        place => new TreeNode(place[2]))
        .ToArray()))
      .ToArray()))
    .ToArray();

  treeView1.Nodes.AddRange(nodes);

Note that this does not account for the inconsistent spellings of "New York" and "Mumbai" in your sample data, which I have corrected in the sample.
Comment: Thanks Jay, this is helpful. have you any idea about the same in Telerik tree view control ?
Comment: @RedSwan I don't know the specifics of the Telerik control, but you can follow the same pattern if their nodes have the same type of constructor: `ctor(string text, )`, and if the collection of child nodes need not be an array, you can omit the `.ToArray()` calls.


How can I alter the inline entity fields on a node edit form?

Question: I want to hide some fields of product reference on node edit. My purpose is to unset or set access to false for colors or price field of line item included in node as inline entity from in a content type. I am using hook as
<code>$form_state){
dsm($entity_form);
unset($entity_form['field_product_colors']); // remove "colors" field from inline entity form
 }
</code>
but hook is not called at this screen when user edit a product on node edit i have shared a node edit screen where product is edited by click on edit link and then update some thing but dont want colors and price to be shown there
Answer: Actually documentation of module in readme file the hook was written and i was using that hook but only problem was the custom module name. if your custom module name is two parts like custom_websitename then this hook did not work in my case, so after one day i changed module name to single word and hook worked.. I am sharing code incase someone need to update lineitemform in node edit for drupal commerce.
<code>function customruba_inline_entity_form_entity_form_alter(&$entity_form,   $form_state){
$entity_form['commerce_price']['#access']=false;
$entity_form['field_commerce_saleprice_on_sale']['#access']=false;
$entity_form['field_commerce_saleprice']['#access']=false;
$entity_form['status']['#access']=false;
}
</code>
this worked for me to hide some information on inline entity form


Issue with C# get and set properties for a List Collection

Question: I need a seperate class where I want to add to some Lists anytime I set a new value. Using _name.Add(value) within the set method doesn't work.
I tried the following
public class XMLInformation
{
    public String BusType
    {
        get
        {
            return SubBusType.LastOrDefault();
        }
        set
        {
            SubBusType.Add(value);
        }
    }
    public List<string> SubBusType { get; set; }

}
I use it like this:
        public STARC.GlobalVariables.XMLInformation XMLInformation = new STARC.GlobalVariables.XMLInformation();
        XMLInformation.BusType = "Test";

now i get an error message (sorry error is partly in geeman)
ISSUE
What am I doing wrong?
Comment: `public List SubBusType { get; set; } = new List();`
Comment: Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it)
Comment: what does the exception mean in English? if it is object reference not set to null exception, you have to first initialize the list
Answer: It can solve your issue. List is not initialized and you are using it. so initialize it first and then use.
public class XMLInformation
{
    public String BusType
    {
        get
        {
            return SubBusType == null ? null: SubBusType.LastOrDefault();
        }
        set
        {
            if (SubBusType == null)
                SubBusType = new List<string>();
            SubBusType.Add(value);
        }
    }
    public List<string> SubBusType { get; set; }
}

Or
public class XMLInformation
{
    public String BusType
    {
        get
        {
            return SubBusType.LastOrDefault();
        }
        set
        {
            SubBusType.Add(value);
        }
    }
            public List<string> SubBusType { get; set; } = new List<string>();
}

Answer: You have to Initialize the SubBusType object because at starting it will be null.
You can do either by creating in the constructor like below
 public XMLInformation()
        {
            SubBusType = new List<string>();
        }

or initiate on declaring the SubType itself like below.
public List<string> SubBusType { get; set; } = new List<string>();


Evaluating a single code block in two data frames in R

Question: I have two data frames
d1 = data.frame(a=1:4,b=2:5)
d2 = data.frame(a=0:3,b=3:6)

and I would like to evaluate the same block of code, for example
  c<-exp(a)
  d<-b^2

within each data frame. At the moment I have to duplicate the code block as follows:
d1t = within(d1, {
  c<-exp(a)
  d<-b^2
})
d2t = within(d2, {
  c<-exp(a)
  d<-b^2
})

which makes my code prone to errors if I make changes to one of the code blocks (they should be the same).
I am not so familiar with environments in R, but I think it should be possible to use them to solve this problem nicely. How can I do it?
Answer: This is the perfect situation to write the repeated code blocks into a function:
     MyFun <- function(df) {
        out = within(df, {
           c<-exp(a)
           d<-b^2
        })
        return(out)
      }

Will do it as long as the variable names are the same across datasets.
To run the code just do:
    d1t <- MyFun(d1)
    d2t <- MyFun(d2)

Should work.
Answer: We could place the dataframe objects in a list.  We search for the names of the objects with the pattern ^d\\d+ ie. 'd' followed by numbers in the global environment.  If there are multiple objects (in this case, 2 objects i.e. 'd1' and 'd2'), we can get the values using mget in a list.
 lst <- mget(ls(pattern='^d\\d+'))

Now, we loop through the list with lapply and create new variables 'c' and 'd' using transform.
 lst1 <- lapply(lst, transform, c=exp(a), d= b^2)

It is better to keep the 'data.frames' within the list.  But, if we need to update the original datasets or create new objects i.e. 'd1t' and 'd2t' (not recommended), we can change the names of the list elements with setNames and use list2env to create objects in the global environment.
 list2env(setNames(lst1, paste0(names(lst1), 't')), envir=.GlobalEnv)
 d1t
 #  a b         c  d
 #1 1 2  2.718282  4
 #2 2 3  7.389056  9
 #3 3 4 20.085537 16
 #4 4 5 54.598150 25

 d2t
 #  a b         c  d
 #1 0 3  1.000000  9
 #2 1 4  2.718282 16
 #3 2 5  7.389056 25
 #4 3 6 20.085537 36

Comment: @js86 Anyway, I think you need a `function`, but if you have multiple datasets, you have to run the function several times...
Comment: @ShawnMehan It gives only the object names i.e. 'd1' and 'd2'.  To get the values, we need `get` or `mget`
Comment: Thanks, your original comment was actually more useful. I only have two data frames, constructed separately (so combining them into a list is unnecessary). But I have a very long code block, which includes function definitions. So `f=function(x)within(x,{x<-exp(a);d<-b^2}); d1t<-f(d1)` works best.
Comment: @js86 Thanks for the comment.  Yes, this is useful when you have multiple datasets.
Comment: @akrun Yep, agreed that's what mget will do, but do we need the value? I ran lapply(lst, transform, DOG=CAT) on two data frames found with ls(pattern...) and it found them and ran lapply with a positive result. The first param in lapply is simply looking for object names, no?
Comment: @ShawnMehan It is creating a new dataset instead of updating the original. For example `lst1 <- ls(pattern='^d\\d+$'); lapply(lst1, transform,DOG='CAT')
#[[1]]
  X_data DOG
1     d1 CAT`.  Here you can see that `d1` is a character string which is shown as the first column