text:
Q: Limit on symbol table? I've been looking into some corner cases for loading python (2.7 on osx) files as configuration files. I wanted to see what the behavior was if I circularly ran execfile. I expected a out of memory error or a lot of swapping to occur, but I was rather surprised when I got a different result.
I setup a test scenario as follows:
'd' python script with:
#!/usr/bin/python
x = 0
execfile("d1")

'd1' python script with:
#!/usr/bin/python
x += 1
print "x = %d" % x
execfile("d2")

'd2' python script with:
#!/usr/bin/python
x += 1
print "x = %d" % x
execfile("d1")

The result:
$ ./d
x = 1
x = 2
x = 3
... removed for brevity ...
x = 997
x = 998
x = 999
Traceback (most recent call last):
  File "./d", line 5, in <module>
    execfile("d1")
  File "d1", line 5, in <module>
    execfile("d2")
  File "d2", line 5, in <module>
    execfile("d1")
... removed for brevity ...
  File "d1", line 5, in <module>
    execfile("d2")
  File "d2", line 5, in <module>
    execfile("d1")
  File "d1", line 5, in <module>
    execfile("d2")
KeyError: 'unknown symbol table entry'

I was just curious if there was someone who could explain what is happening here? Why does it stop after executing execfile ~1000 times?

A: From the Python source code, Objects/dictobject.c:

/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
 * that may occur (originally dicts supported only string keys, and exceptions
 * weren't possible).  So, while the original intent was that a NULL return
 * meant the key wasn't present, in reality it can mean that, or that an error
 * (suppressed) occurred while computing the key's hash, or that some error
 * (suppressed) occurred when comparing keys in the dict's internal probe
 * sequence.  A nasty example of the latter is when a Python-coded comparison
 * function hits a stack-depth error, which can cause this to return NULL
 * even if the key is present.
 */

So, PyDict_GetItem() does not always report errors correctly.  Interesting... so in the following code in Python/symtable.c,
v = PyDict_GetItem(st->st_blocks, k);
if (v) {
    assert(PySTEntry_Check(v));
    Py_INCREF(v);
}
else {
    PyErr_SetString(PyExc_KeyError,
                    "unknown symbol table entry");
}

Any error that occurs when looking up a symbol (including out-of-memory errors) will be turned into a KeyError.  This is probably a bug.

redpajama_set_name: RedPajamaStackExchange


text:
Q: print dictionary keys and values in one column in tcl I am new learner of tcl scripting language. I am using TCL version 8.5. I read text file through tcl script and count similar words frequency. I used for loop and dictionary to count similar words and their frequency but output of the program print like this: alpha 4 beta 2 gamma 1 delta 1
But I want to print it in one column each key, value pair of dictionary or we could say each key, value pair print line by line in output. Following is my script in tcl and its output at the end.
set f [open input.txt]
set text [read $f]
foreach word [split $text] {
    dict incr words $word
}
 puts $words

Output of the above script:
alpha 4 beta 2 gamma 1 delta 1

A: You would do:
dict for {key value} $words {
    puts "$key $value"
}

When reading the dict documentation, take care about which subcommands require a dictionaryVariable (like dict incr) and which require a dictionaryValue (like dict for)

For nice formatting, as suggested by Donal, here's a very terse method:
set maxWid [tcl::mathfunc::max {*}[lmap w [dict keys $words] {string length $w}]]
dict for {word count} $words {puts [format "%-*s = %s" $maxWid $word $count]}

Or, look at the source code for the parray command for further inspiration:
parray tcl_platform  ;# to load the proc
info body parray


text:
Q: ReactiveCocoa - observing isFirstResponder property and UITextField with clearsOnBeginEditing set to YES I am new to ReactiveCocoa, but I think it's very nice and outstanding technique for reducing code complexity. I just started experiencing with the framework, and not everything is clear for me at the moment, so excuse me if my problem can be solved in some obvious way.
In my app I have login view controller with simple form contains two text fields (username and password) and a button. I would like the button to be disabled if any of two text fields is empty. So, I wrote this code:
RAC(self.loginButton, enabled) =
[RACSignal combineLatest:@[self.userTextField.rac_textSignal,
                           self.passwordTextField.rac_textSignal]
                  reduce:^(NSString *username,
                           NSString *password) {
                      BOOL valid = (username.length > 0 && password.length > 0);
                      return @(valid);
                  }];

It's very simple and it's working. The problem is that one of my text fields (the password field) has secureTextEntry and clearsOnBeginEditing properties set to YES. I will try to explain unwanted behavior that I am experiencing with this configuration:
Let's assume that both username and password fields are NOT empty. In this case the button is enabled. When user taps on password field, it becomes first responder (keyboard appears and user can enter his password), but because of clearsOnBeginEditing being set to YES for that field, the previously entered password is cleared from the text field. That's way password field is now empty. The problem is that signal is not being sent, so the button remains enabled, despite the password field is empty.
My first idea to solve this issue (well, more like workaround solution) was to observe isFirstResponder property on password field beside observing text changes. That's way the block that checks if button should be enabled would be called when password field becomes first responder. I don't know if this solution works, because I have no idea how to implement it using ReactiveCocoa. I have looking for creating a signal for isFirstResponder property changes, but without a luck. It might be not the best approach in order to solve this issue, but nothing comes to my mind at this point.
Then, the question is: how to observe isFirstResponder property with ReactiveCocoa?
And more general question: how to observe text field's text changes when clearsOnBeginEditing is set to YES?
UPDATE:
I found out that I can create signal for UIControlEventEditingDidBegin event that should give me substitution of observing isFirstResponder property changes:
[self.passwordTextField rac_signalForControlEvents:UIControlEventEditingDidBegin]

Unfortunately this does not solve the issue. Now I understand that field is cleared AFTER it becomes first responder, and clearing field automatically after it becomes first responder does not send signal for text changes. That's way when validation block is executed it still thinks that password field is not empty, and the button remains enabled despite password field was cleared and it's empty.

A: Unfortunately the -rac_textSignal only listens for UIControlEventEditingChanged. If  UIControlEventEditingDidBegin were added, you'd be all set.
I suppose you could patch this into it and submit a pull request?
- (RACSignal *)rac_textSignal {
    @weakify(self);
    return [[[[[RACSignal
        defer:^{
            @strongify(self);
            return [RACSignal return:self];
        }]
        concat:[self rac_signalForControlEvents:UIControlEventEditingChanged|UIControlEventEditingDidBegin]]
        map:^(UITextField *x) {
            return x.text;
        }]
        takeUntil:self.rac_willDeallocSignal]
        setNameWithFormat:@"%@ -rac_textSignal", [self rac_description]];
}


text:
Q: Execute shell script on cygwin from Python I want to execute a shell script, on cygwin from Python. The shell script is creating a file as an output.
I tried
import os
import subprocess

os.chdir(r"C:\\cygwin64\\bin\\ ")
cmd = ["bash", "-c", 'cd /<path for the script>; ./test.sh']
subprocess.call(cmd)

A: This works:
import os, subprocess
os.chdir(r"C:\cygwin64\bin")
cmd = ["bash", "-c", "cd $HOME; pwd; exit"]
ret = subprocess.call(cmd)


text:
Q: cannot resolve method getText() I'm new to Android developing and I'm trying to create a TODO list similar to an online tutorial I'm following.
Everything but "todoText.setText(todoList.get(position).getText());" compiles correctly.
With that line, I get the following error message: "cannot resolve method getText()."
This is part of a class responsible for displaying each list row in a TODO checklist:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.activity_main, parent, false);
    TextView todoText = (TextView) rowView.findViewById(R.id.todoText);
    todoText.setText(todoList.get(position).getText());
    return rowView;
}

I have no idea how to fix this. Any help would be greatly appreciated. Thank you.

A: Hard to say without seeing todoList declaration, but chances are that todoList is a List of Strings (or something else but a TextView). If that's the case, you may just need to do.-
todoText.setText(todoList.get(position));

A: I have no idea about the contents of your todoList but you can do a workaround if the content is not a String by using .toString()
Try to change the code into -
todoText.setText(todoList.get(position).toString());

hope it works.


text:
Q: How to compare two fields in JSON with jsonpath matchers I have following json:
{
   "currentVersion": "1.0.0",
   "lastVersion": "1.0.0"
}

How to check that currentVersion equals lastVersion with jsonpath if this is possible at all?
I have tried:
this.mockMvc.perform(get("/api/versions/current"))
                .andExpect(jsonPath("$.lastVersion").value(jsonPath("$.currentVersion")));

But it compares value of lastVersion field with instance of Matcher.


text:
Q: If $\sum_{n=1}^\infty E(X_n-X_{n-1})^2/b_n^2 < \infty$, then $X_n/b_n \rightarrow 0$ a.s. This is Durrett Exercise 5.4.9.

I'm trying to show that if $X_n$ is a martingale, and $b_m \uparrow \infty$, $\sum_{n=1}^\infty E(X_n-X_{n-1})^2/b_n^2 < \infty$, then $X_n/b_n \rightarrow 0$ a.s..

If $X_n \in L^2$, I can show that this reduces to Durrett Exercise 5.4.8, which I have solved, since the above also gives us that the the sum of $\sum_{n=1}^\infty E\left(\frac{X_n}{b_n}-\frac{X_{n-1}}{b_{n-1}}\right)^2<\infty$, and then I can use orthogonality of martingale increments, and $L^p$ convergence theorem to conclude that it converges in almost surely and in $L^2$, although I'm not sure that I can show it converges to 0.
But, in this case, I am stuck and unable to proceed

A: Hints: Since $b_n \uparrow \infty$ we may assume without loss of generality that $b_n>1$ for all $n \geq 1$.

Let's first assume additionally that $(X_n)_{n \in \mathbb{N}}$ is square integrable and $X_0 = 0$.

*

*Set $$Y_n := \sum_{i=1}^n \frac{X_i-X_{i-1}}{b_i}.$$ Show that $(Y_n)_{n \in \mathbb{N}}$ is a squre-integrable martingale with $$\mathbb{E}(Y_n^2) = \sum_{i=1}^n \frac{\mathbb{E}((X_i-X_{i-1})^2)}{b_i^2}.$$

*It follows from Step 1 and the assumptions on $(X_n)_{n \in \mathbb{N}}$ that $(Y_n)_{n \in \mathbb{N}}$ is an $L^2$-bounded martingale. The martingale convergence thorem yields that $Y_n$ converges almost surely, i.e. $$\sum_{i=1}^{\infty} \frac{X_i-X_{i-1}}{b_i}$$ converges with probability $1$.

*Apply Kronecker's lemma to deduce that $$\lim_{n \to \infty} \frac{X_n}{b_n} = 0 \quad \text{a.s.}$$

For the general case: Define $\tilde{X}_n := X_n-X_0$.

*

*Check that $\sum_n \mathbb{E}((X_n-X_{n-1})^2)/b_n^2 < \infty$ implies $\sum_n \mathbb{E}((\tilde{X}_n-\tilde{X}_{n-1})^2)/b_n^2 < \infty$.

*Deduce from $\mathbb{E}((\tilde{X}_n-\tilde{X}_{n-1})^2)< \infty$, $n \in \mathbb{N}$, and $\tilde{X}_0 =0 \in L^2(\mathbb{P})$ that $\tilde{X}_n \in L^2(\mathbb{P})$ for all $n \geq 1$.

*Apply the first part of this answer to $\tilde{X}_n$.


text:
Q: ODBC and DB2 stored procedures from C#: Routine not found I seem have come across a short coming with ODBC and DB2 when running stored procedures. It seems that it is not possible to return  data from a stored procedure, and I have a prexisting query that I need to use. Has anyone got around this particular issue?
Thanks in advance
Update
The code that I am calling is as follows (assuming that the connection is already opened):
string BaseSQL = "CALL B6009822.O#04666803.PUT";

OdbcCommand command = new OdbcCommand(BaseSQL, myConnection);
command.CommandType = CommandType.StoredProcedure;

command.Parameters.Add("@Owner", OdbcType.VarChar).Value = "MH";

int rows = command.ExecuteNonQuery();

myConnection.Close();

I get the following error ..
ERROR [HY000] [IBM][System i Access ODBC Driver][DB2 for i5/OS]SQL0440 - Routine PUT in O#04666803 not found with specified parameters.

It seems to be objecting to the catalog/library and procedure name. Any idea on what I need to do to get the procedure called ?
Second Update - real example
string BaseSQL = "{ CALL B6009822.O#04666803.PUT(?,?,?,?,?,?,?,?,?) }";

OdbcCommand command = myConnection.CreateCommand();
command.CommandText = BaseSQL;

//OdbcCommand command = new OdbcCommand(BaseSQL, myConnection);
command.CommandType = CommandType.StoredProcedure;

/*
@Param1 VarChar(4), @Param2 dec(8,0),
@Param3 dec(4,0), @Param4 dec(8,0),
@Param5 VarChar(60), @Param6 dec(9,2),
@Param7 dec(9,0), @Param8 dec(9,2),
@Param9 VarChar(10))
 */

command.Parameters.Add("@Param1", OdbcType.VarChar, 4).Value = "MH";
command.Parameters.Add("@Param2", OdbcType.Decimal, 8).Value = 20110217;
command.Parameters.Add("@Param3", OdbcType.Decimal, 4).Value = 1;
command.Parameters.Add("@Param4", OdbcType.Decimal, 8).Value = 178377;
command.Parameters.Add("@Param5", OdbcType.VarChar, 60).Value = "Description";
command.Parameters.Add("@Param6", OdbcType.Decimal, 9).Value = 0;
command.Parameters.Add("@Param7", OdbcType.Decimal, 9).Value = 45;
command.Parameters.Add("@Param8", OdbcType.Decimal, 9).Value = 0;
command.Parameters.Add("@Param9", OdbcType.VarChar, 10).Value = "*CREATE";

int rows = command.ExecuteNonQuery();

myConnection.Close();

A: Have you tried the CALL syntax?
http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db29.doc.odbc/db2z_odbcspcall.htm
EDIT: Just in case my comment above is correct:
From this resource, have you tried:
string BaseSQL = "CALL B6009822.O#04666803.PUT (?)";

Important: Unlike ODBC, DB2 ODBC does
  not support literals as procedure
  arguments. You must use parameter
  markers to specify a procedure
  parameter.

A: First of all I  had to make the library (or whatever the proper term is) visible in the "System i Navigator". It seems that there is an issue with stored procedures that return results, so I had to call it as a SELECT, as shown below ...
"SELECT PUT('{4}',{1},1,{0},'{2}',0,{3},0,'{5}') as A from LIBRARY.EARNER where EAR = '{4}'"

Not sure if this helps anyone else other than me though!

A: For any DB2 n00bs like myself hitting this page searching for answers to "SQL0440 - Routine [YourRoutine] in [*N | LIBRARY] not found with specified parameters"...
For me, my problem was where I had defined the constant for the stored procedure name, like so:
    // Database Constants
    public const string DB_PROC_GET_MYPROC = @"LIBRARY.MYPROC";

How I should have declared it was:
    // Database Constants
    public const string DB_PROC_GET_MYPROC = @"LIBRARY.MYPROC(@stateCode, @productCode, @tranType)";

...with the parameters included.
I've spent so long with Entity Framework, I have all but forgotten direct database connection basics in c#.
Hope this saves someone some time.


text:
Q: How to correct the parse error for the below code Html code is:

    <input type="input" ng-model="title" />

Javascript code:
var app = angular.module('app', []);

app.controller("myController", function ($scope) {
    $scope.title = "binding";
    $scope.spell = function(ele){
        console.log("me "+ele);
    }
});

app.directive("jmFind", function () {
    return {
        replace: true,
        restrict: 'C',
        transclue: true,
        scope: {
            title1: "=",
            title2: "&"
        },
        template: "
<button ng-click={{title2}}>{{title1}}</button>
"
    };
});

I am trying to understand "&" usage in Angularjs custom directive. I have followed few examples but missing on proper syntax to call the spell function.
JSFiddle Link: http://jsfiddle.net/k03ozLts/

A: Invoke AngularJS expressions bound with expression (&) binding:
app.directive("jmFind", function () {
    return {
        scope: {
            title1: "=",
            title2: "&"
        },
        ̶t̶e̶m̶p̶l̶a̶t̶e̶:̶ ̶"̶<̶d̶i̶v̶>̶<̶b̶u̶t̶t̶o̶n̶ ̶n̶g̶-̶c̶l̶i̶c̶k̶=̶{̶{̶t̶i̶t̶l̶e̶2̶}̶}̶>̶{̶{̶t̶i̶t̶l̶e̶1̶}̶}̶<̶/̶b̶u̶t̶t̶o̶n̶>̶<̶/̶d̶i̶v̶>̶"̶
        template: "
<button ng-click='title2()'>{{title1}}</button>
"
    };
});


text:
Q: Inserting more than one data field in a sorted data structure What is the best data structure to use when you need to insert more than 1 (like 10) data fields in a node and have the nodes to be stored in the ascending order of their key?

A: In general, inserts element need 3 steps:

*

*locate where to insert

*insert it

*adjust data structure if needs

If the inserting elements have regularity(like all elements equals, It will save 1. locate where to insert time in linked list), but time complexity still O(n).
If the inserting elements have no regularity, it random enough. There is no difference between inserting one and insert batch.
So in one word, there is no special data structure for batch inserting. but you can improve Constant Time Complexity in some special conditions.
PS: common sorted data structure is balanced binary tree, spends O(logn) time complexity when updating


text:
Q: How to git clone with username and password in gitlab? I am using gitlab . I want to write a .bat file which contains all the steps so that I can automate all the process , which are as follows:

*

*open cmd.exe /k

*git init

*git clone https://username:password@gitlab.com/board.git  ////// not working

*git status

The 3rd point that is git clone https.... is not working in gitBash anymore. I tried using git clone SSH ... and it  is working which asked for the passphrase and after logging in it was about to clone the repo. As I want to automate the process by providing the login credentials by-default , how can it be achieved using SSH. Thank you.

A: You will need to use access token. Gitlab doesn't allow to use password directly.
git clone https://<username>:<token>@gitlab.com/group/project.git

To create a Gitlab access token:

*

*Click your avatar at the top right corner, select Edit profile

*On the left panel, select Access Tokens

*Input the Token name and Expiration date (if any)

*Check the read_repository checkbox

*Click Create personal access token

*Remember to save the access token, it appears only once

A: Adding username before gitlab worked for me. It will ask password afterwards.
git clone https://user@gitlab.com/project.git

A:
While generating keys I did give a passphrase.

Simplest solution would be to generate key without passphrase and use it.
Git clone over https should work but url from your example looks wrong. Go to your project page, choose Clone -> HTTPS url which should look like
https://gitlab.com/<username or groupname>/<projectname>.git
Let's say it is your user's private project and your user would be Julie, then url with credentials would be
https://user:password@gitlab.com/julie/board.git
Test url manually before you start writing your script.
So going to your script example don't init anything just do for https clone:
git clone https://user:password@gitlab.com/julie/board.git
cd board
git status

or if you create ssh key without passphrase and set it on GitLab:
git clone git@gitlab.com:gitlab.com/julie/board.git
cd board
git status


text:
Q: All data in a row. Move observations under each other I have the following data:
data <- list(list(eventId = 8, subEventName = "Simple pass", tags = list(
  list(id = 1801)), playerId = 122671, positions = list(list(
    y = 50, x = 50), list(y = 53, x = 35)), matchId = 2057954,
  eventName = "Pass", teamId = 16521, matchPeriod = "1H", eventSec = 1.656214,
  subEventId = 85, id = 258612104), list(eventId = 8, subEventName = "High pass",
                                         tags = list(list(id = 1801)), playerId = 139393, positions = list(
                                           list(y = 53, x = 35), list(y = 19, x = 75)), matchId = 2057954,
                                         eventName = "Pass", teamId = 16521, matchPeriod = "1H", eventSec = 4.487814,
                                         subEventId = 83, id = 258612106))

I want to create a data frame out of this list. I use unlist(data), which creates a row with repeated variables.
> unlist(data)
      eventId  subEventName       tags.id      playerId   positions.y   positions.x   positions.y
          "8" "Simple pass"        "1801"      "122671"          "50"          "50"          "53"
  positions.x       matchId     eventName        teamId   matchPeriod      eventSec    subEventId
         "35"     "2057954"        "Pass"       "16521"          "1H"    "1.656214"          "85"
           id       eventId  subEventName       tags.id      playerId   positions.y   positions.x
  "258612104"           "8"   "High pass"        "1801"      "139393"          "53"          "35"
  positions.y   positions.x       matchId     eventName        teamId   matchPeriod      eventSec
         "19"          "75"     "2057954"        "Pass"       "16521"          "1H"    "4.487814"
   subEventId            id
         "83"   "258612106"

Each observation starts with the eventId variable. So, basically I have to split the data into dataframes starting with eventId, and then moving those dataframes one under the other. I.e. having two observations in this case. Do you have any idea?  thanks in advance

A: Try tibblify--
library(tibblify)

tibblify(data)
## A tibble: 2 x 12
#  eventId subEventName               tags playerId          positions matchId eventName teamId matchPeriod eventSec subEventId        id
#    <dbl> <chr>        <list<tbl_df[,1]>>    <dbl> <list<tbl_df[,2]>>   <dbl> <chr>      <dbl> <chr>          <dbl>      <dbl>     <dbl>
#1       8 Simple pass             [1 x 1]   122671            [2 x 2] 2057954 Pass       16521 1H              1.66         85 258612104
#2       8 High pass               [1 x 1]   139393            [2 x 2] 2057954 Pass       16521 1H              4.49         83 258612106

A: You can use rbindlist from data.table :
result <- data.table::rbindlist(data)
result

#   eventId subEventName      tags playerId positions matchId eventName teamId matchPeriod eventSec subEventId       id
#1:       8  Simple pass <list[1]>   122671 <list[2]> 2057954      Pass  16521          1H     1.66         85 2.59e+08
#2:       8  Simple pass <list[1]>   122671 <list[2]> 2057954      Pass  16521          1H     1.66         85 2.59e+08
#3:       8    High pass <list[1]>   139393 <list[2]> 2057954      Pass  16521          1H     4.49         83 2.59e+08
#4:       8    High pass <list[1]>   139393 <list[2]> 2057954      Pass  16521          1H     4.49         83 2.59e+08

A: Does this help solve your problem?
df <- data.frame(matrix(unlist(data), nrow=length(data), byrow=T))


text:
Q: Cannot read property 'map' of undefined on useState value I'm new to react, I'm getting this error constantly and after google some I can't find the reason why the useState value can't be read as array :( ... this the error I'm getting: 'TypeError: team.map is not a function'
    import React, { useEffect, useState } from "react";

    const SportTeams = () => {
      const [team, setTeam] = useState([]);

      useEffect(() => {
        const getSports = async () => {
          const response = await fetch("https://www.thesportsdb.com/api/v1/json/1/all_sports.php");
          const data = await response.json();
          setTeam(data);
          console.log(data);
        }
        getSports();
      }, []);

      return (

            {team.map((sport, index) => {
              return <li key={`${sport.strSport}-${index}`}>{sport.strSport}

            })}

      );
    };
    export default SportTeams;

A: Just update setTeam like following, your error will be resolved.
setTeam(data.sports);

A: It is because you are setting the team state with the data without checking if its undefined. If the data is undefined your state team become undefined as well. So make sure to check the data.
    import React, { useEffect, useState } from "react";

        const SportTeams = () => {
          const [team, setTeam] = useState([]);

          useEffect(() => {
            const getSports = async () => {
              const response = await fetch("https://www.thesportsdb.com/api/v1/json/1/all_sports.php");
              if (response) {
                const data = await response.json();
                if (data) {
                  setTeam(data);
                }
              }
              console.log(data);
            }
            getSports();
          }, []);

          return (

                {team.map((sport, index) => {
                  return <li key={`${sport.strSport}-${index}`}>{sport.strSport}

                })}

          );
        };
        export default SportTeams;

There might also be the chance that your response is not what you expected and the actual data might be inside your response. In that case you need check what your response first then proceed to set the data.

A: As I said in my comment. the value you are setting to teams isn't an array.

const data = await response.json();
setTeam(data.sports);


text:
Q: How to use listing, tikz and tikzmark packages together to annotate source code listing? I'd like to annotate code listing something like this:

Below is what I've attempted so far. I am a little worried about having to use raisebox so that the arrow tip doesn't point to the base of the line. How can I avoid this hardcoding? I would also appreciate any advice on improvements so that it's easier to handle a few varieties of annotations as seen in the screenshot.
It would be nice, to get the desired results, if I can just specify the following:

*

*the distance between the end of source line and the arrow tip

*the length of the horizontal line and the length of the vertical line
of the arrow (and whether the vertical line goes upwards or downwards)

*and the position of the text node (whether right or left of the vertical line and vertical alignment of text node with the top or bottom.
\documentclass[twoside, openright, 10pt]{book}
\usepackage{listings}
\usepackage{tikz}
\usetikzlibrary{arrows.meta, tikzmark}

\begin{document}

\chapter{TiKz}

\begin{lstlisting}[caption={[MeetKarel]{MeetKarel}}, label={lst:meet_karel}, escapechar=ß]
import stanford.karel.Karel;
public class MeetKarel extends Karel {
        public void run() {
                move();
                move();
                move();
                ß\tikzmark{b}ßpickBeeper();ß\raisebox{2.6pt}{\tikzmark{a}}ß
                turnLeft();
                move();
                move();
                turnLeft();
                turnLeft();
                turnLeft();ß\raisebox{2.6pt}{\tikzmark{c}}ß
                move();
                putBeeper();
                move();
        }
}
\end{lstlisting}
\begin{tikzpicture}[remember picture,overlay]
\draw([shift={(12ex,10ex)}] pic cs:a) ++ (0.05, 0) % shift just a little to the right
  % set inner and outer to 0 so that text is alighed with the beginning of the vertical line
  node[inner sep=0,outer sep=0, fill=yellow!80!black,text width=5cm, anchor= north west]
  {Shifted a little above so that the arrow head points to the middle of the line.};
\draw[thin, gray, arrows = {-Stealth[inset=0pt, angle=45:7pt]}]
  ([shift={(12ex,10ex)}] pic cs:a) --
  ([shift={(12ex,0ex)}] pic cs:a) --
  ([shift={(0ex,0ex)}] pic cs:a);
\draw([shift={(12ex,-10ex)}] pic cs:c) ++ (0.05, -0.05) % shift just a little to the right and down
  % set inner and outer to 0 so that text is alighed with the beginning of the vertical line
  node[inner sep=0,outer sep=0, fill=yellow!80!black,text width=5cm, anchor= south west]
  {I want to align base line of this text to the `c` node nicely. };
\draw[thin, gray, arrows = {-Stealth[inset=0pt, angle=45:7pt]}]
  ([shift={(12ex,-10ex)}] pic cs:c) --
  ([shift={(12ex,0ex)}] pic cs:c) --
  ([shift={(0ex,0ex)}] pic cs:c);
\end{tikzpicture}
\end{document}

Result:

A: Here's a slightly simplified version of your code.

*

*By using the tikzmark special listings library then you don't need to specify tikzmarks in your code, they are all provided for you.

*The arrows start at (0.5,.5ex) away from the corresponding tikzmarks.  The .5ex is half the height of an x, and looks a good vertical height to me.

*The lines and nodes are drawn together and the -| path construction is used to make the line bend nicely.

*A little bit is added to the outer xsep of the label nodes to move them away from the joining line.  Other ways of achieving the same effect do seem to cause issues with the arrow placement.

All of this contrives to make the code much shorter.  Various numbers could be hard-coded into a style to make it even more simple and a bit more flexible.
\documentclass[twoside, openright, 10pt]{book}
%\url{https://tex.stackexchange.com/q/657375/86}
\usepackage{listings}
\usepackage{tikz}
\usetikzlibrary{
  arrows.meta,
  tikzmark,
  calc,
  positioning
}
\usetikzmarklibrary{listings}

\begin{document}

\chapter{Ti\emph{k}Z}

\begin{lstlisting}[
  caption={[MeetKarel]{MeetKarel}},
  label={lst:meet_karel},
  name=karel,
  escapechar=ß
]
import stanford.karel.Karel;
public class MeetKarel extends Karel {
        public void run() {
                move();
                move();
                move();
                pickBeeper();
                turnLeft();
                move();
                move();
                turnLeft();
                turnLeft();
                turnLeft();
                move();
                putBeeper();
                move();
        }
}
\end{lstlisting}

\begin{tikzpicture}[
  remember picture,
  overlay,
  annotation/.style={
    inner sep=0pt,
    outer sep=0pt,
    outer xsep=1mm,
    fill=yellow!80!black,
    text width=5cm
  },
  >={Stealth[inset=0pt, angle=45:7pt]}
]
\draw[<-] (pic cs:line-karel-7-end)  ++(.5,.5ex) -| ++(2,1.5)
node[annotation, below right]
{Shifted a little above so that the arrow head points to the middle of the line.};

\draw[<-] (pic cs:line-karel-13-end) ++(0.5,.5ex) -| ++(2,-1)
node[annotation, above right]
{I want to align base line of this text to the `c` node nicely. };
\end{tikzpicture}
\end{document}


text:
Q: How to get number of matching colums count in the same table as another column? I have a table like below.
    +----+----------+---------+--------+----------+---------+---------------------+
    | id | box_name | diIndex | diMode | diStatus | status  | last_updated        |
    +----+----------+---------+--------+----------+---------+---------------------+
    |  7 | boxa     |       0 |      0 |        0 |    1    | 2017-03-02 10:49:35 |
    |  8 | boxa     |       1 |      0 |        1 |    0    | 2017-03-02 10:49:35 |
    |  9 | boxa     |       2 |      0 |        0 |    1    | 2017-03-02 10:49:36 |
    | 10 | boxa     |       3 |      0 |        0 |    1    | 2017-03-02 10:49:36 |
    | 11 | boxa     |       4 |      0 |        0 |    0    | 2017-03-02 10:49:36 |
    | 12 | boxa     |       5 |      0 |        0 |    2    | 2017-03-02 10:49:36 |
    | 13 | boxa     |       6 |      0 |        0 |    2    | 2017-03-02 10:49:36 |
    | 14 | boxa     |       7 |      0 |        0 |    3    | 2017-03-02 10:49:36 |
    +----+----------+---------+--------+----------+---------+---------------------+

Now I want to add a new column in the table which will get me the total number of each matching record of status column like below.
+----+----------+---------+--------+----------+---------+---------------+---------------------+
| id | box_name | diIndex | diMode | diStatus | status  | status count  | last_updated        |
+----+----------+---------+--------+----------+---------+---------------+---------------------+
|  7 | boxa     |       0 |      0 |        0 |    1    |       3       | 2017-03-02 10:49:35 |
|  8 | boxa     |       1 |      0 |        1 |    0    |       2       | 2017-03-02 10:49:35 |
|  9 | boxa     |       2 |      0 |        0 |    1    |       3       | 2017-03-02 10:49:36 |
| 10 | boxa     |       3 |      0 |        0 |    1    |       3       | 2017-03-02 10:49:36 |
| 11 | boxa     |       4 |      0 |        0 |    0    |       2       | 2017-03-02 10:49:36 |
| 12 | boxa     |       5 |      0 |        0 |    2    |       2       | 2017-03-02 10:49:36 |
| 13 | boxa     |       6 |      0 |        0 |    2    |       2       | 2017-03-02 10:49:36 |
| 14 | boxa     |       7 |      0 |        0 |    3    |       1       | 2017-03-02 10:49:36 |
+----+----------+---------+--------+----------+---------++--------------+---------------------+

Here you can see that for status value 1 there are 3 records so value for status_count for columns having status as 1 will be 3 and so on..
How can I achieve this?

A: With window functions, this would be almost trivial to add as a column in a query:
COUNT(*) OVER (PARTITION BY status) AS status_count

Since MySQL hasn't implemented them (you'll have to wait, they may be in the next version), you'll need something more complex now. It can be done with a derived table - to calculate these counts - and then join to the base table:
SELECT
    t.id, t.box_name, t.diIndex, t.diMode, t.diStatus, t.status,
    g.status_count, t.last_updated
FROM
    tableX AS t
  JOIN
    ( SELECT status, COUNT(*) AS status_count
      FROM tableX
      GROUP BY status
    ) AS g
  ON
    t.status = g.status ;


text:
Q: How can I correct my war application (Tomcat 8)? I made a Web Java Application, on JDK 1.8, with the next libraries:
 - Hibernate 4.3.x
 - bootstrap 1.0.10
 - commons codec 1.10
 - commons logging 1.2
 - poi 3.12-20150511
 - poi ooxml 3.12-20150511
 - poi ooxml-schemas 3.12-20150511
 - xmlbeans 2.6.0
 - gson 2.3.1
 - bson4jackson 2.7.0
 - jackson annotations 2.7.3
 - jackson core 2.7.3
 - jackson databind 2.7.3
 - jongo 1.3.0
 - mongo java driver 3.2.2
 - postgresql 9.4.1208jre6
 - primefaces 6.0
 - commons fileupload 1.3.1
 - commons io 2.4

I developed my application on Netbeans 8.0 and finally I generated a war file. After I downloaded and installed Tomcat 8 in my computer (with Windows 8.1 to 64 bits) to 32 bits, and when I mount my war file on Tomcat, and I accessed to http://localhost:8080/MyApplication the page respond with HTTP STATUS 404 message.
As I don't know what is the file with the specific exception, I show all the files of the log folder:
catalina.2017-03-20.log
20-Mar-2017 19:31:57.589 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Server version:        Apache Tomcat/8.5.12
20-Mar-2017 19:31:57.616 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:          Mar 8 2017 17:41:47 UTC
20-Mar-2017 19:31:57.637 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Server number:         8.5.12.0
20-Mar-2017 19:31:57.660 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:               Windows 8.1
20-Mar-2017 19:31:57.661 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:            6.3
20-Mar-2017 19:31:57.662 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:          x86
20-Mar-2017 19:31:57.662 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home:             C:\Program Files (x86)\Java\jre1.8.0_101
20-Mar-2017 19:31:57.663 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version:           1.8.0_101-b13
20-Mar-2017 19:31:57.663 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor:            Oracle Corporation
20-Mar-2017 19:31:57.663 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE:         C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5
20-Mar-2017 19:31:57.664 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME:         C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5
20-Mar-2017 19:31:57.665 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5
20-Mar-2017 19:31:57.665 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5
20-Mar-2017 19:31:57.666 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\temp
20-Mar-2017 19:31:57.666 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
20-Mar-2017 19:31:57.666 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\conf\logging.properties
20-Mar-2017 19:31:57.667 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: exit
20-Mar-2017 19:31:57.667 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Xms128m
20-Mar-2017 19:31:57.667 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Xmx256m
20-Mar-2017 19:31:57.667 INFORMACIÓN [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent La biblioteca nativa de Apache Tomcat basada en ARP que permite un rendimiento óptimo en entornos de desarrollo no ha sido hallada en java.library.path: C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\TXE Components\TCS\;C:\Program Files\Intel\TXE Components\TCS\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\nodejs\;C:\Program Files\MongoDB\Server\3.2\bin;C:\Program Files\PostgreSQL\9.3\bin;C:\tas-8.3-1\multiserver\enhydra\bin; C:\Program Files\PostgreSQL\9.3\bin;C:\Python27;C:\Python27\Scripts;C:\Program Files (x86)\Skype\Phone\;;.
20-Mar-2017 19:31:58.005 INFORMACIÓN [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8081"]
20-Mar-2017 19:31:58.593 INFORMACIÓN [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
20-Mar-2017 19:31:58.599 INFORMACIÓN [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
20-Mar-2017 19:31:58.605 INFORMACIÓN [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
20-Mar-2017 19:31:58.606 INFORMACIÓN [main] org.apache.catalina.startup.Catalina.load Initialization processed in 2024 ms
20-Mar-2017 19:31:58.680 INFORMACIÓN [main] org.apache.catalina.core.StandardService.startInternal Arrancando servicio Catalina
20-Mar-2017 19:31:58.680 INFORMACIÓN [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.12
20-Mar-2017 19:31:58.761 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Despliegue del archivo C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\MyApplication.war de la aplicación web
20-Mar-2017 19:32:15.612 GRAVE [localhost-startStop-1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:
 org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/MyApplication]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: El mapeo de filtro especifica un nombre desconocido de filtro PrimeFaces FileUpload Filter
    at org.apache.catalina.core.StandardContext.validateFilterMap(StandardContext.java:2987)
    at org.apache.catalina.core.StandardContext.addFilterMap(StandardContext.java:2950)
    at org.apache.catalina.startup.ContextConfig.configureContext(ContextConfig.java:1275)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1190)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:775)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:299)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:94)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5114)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 10 more

20-Mar-2017 19:32:15.615 GRAVE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Error durante el despliegue del archivo C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\MyApplication.war de la aplicación web
 java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/MyApplication]]
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:756)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

20-Mar-2017 19:32:15.621 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\MyApplication.war has finished in 16.856 ms
20-Mar-2017 19:32:15.625 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\docs de la aplicación web
20-Mar-2017 19:32:15.899 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\docs has finished in 274 ms
20-Mar-2017 19:32:15.900 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\examples de la aplicación web
20-Mar-2017 19:32:16.762 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\examples has finished in 862 ms
20-Mar-2017 19:32:16.762 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\host-manager de la aplicación web
20-Mar-2017 19:32:16.833 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\host-manager has finished in 71 ms
20-Mar-2017 19:32:16.834 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\manager de la aplicación web
20-Mar-2017 19:32:16.954 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\manager has finished in 120 ms
20-Mar-2017 19:32:16.955 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\ROOT de la aplicación web
20-Mar-2017 19:32:16.999 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\ROOT has finished in 44 ms
20-Mar-2017 19:32:17.008 INFORMACIÓN [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler [http-nio-8081]
20-Mar-2017 19:32:17.047 INFORMACIÓN [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler [ajp-nio-8009]
20-Mar-2017 19:32:17.054 INFORMACIÓN [main] org.apache.catalina.startup.Catalina.start Server startup in 18447 ms

commons-daemon.2017-03-20.log
[2017-03-20 19:31:55] [info]  [ 1908] Commons Daemon procrun (1.0.15.0 32-bit) started
[2017-03-20 19:31:55] [info]  [ 1908] Running 'Tomcat8' Service...
[2017-03-20 19:31:55] [info]  [ 4584] Starting service...
[2017-03-20 19:31:57] [info]  [ 4584] Service started in 1292 ms.

host-manager.2017-03-20.log
[is empty]

localhost.2017-03-20.log
20-Mar-2017 19:32:16.740 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log ContextListener: contextInitialized()
20-Mar-2017 19:32:16.741 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log SessionListener: contextInitialized()

localhost_access_log.2017-03-20.txt
0:0:0:0:0:0:0:1 - - [20/Mar/2017:19:32:27 -0500] "GET /MyApplication/ HTTP/1.1" 404 994
0:0:0:0:0:0:0:1 - - [20/Mar/2017:19:32:29 -0500] "GET /MyApplication/ HTTP/1.1" 404 994
0:0:0:0:0:0:0:1 - - [20/Mar/2017:19:32:29 -0500] "GET /favicon.ico HTTP/1.1" 200 21630
0:0:0:0:0:0:0:1 - - [20/Mar/2017:19:32:30 -0500] "GET /MyApplication/ HTTP/1.1" 404 994
0:0:0:0:0:0:0:1 - - [20/Mar/2017:19:32:30 -0500] "GET /favicon.ico HTTP/1.1" 200 21630

manager.2017-03-20.log
[Is empty]

tomcat8-stderr.2017-03-20.log
2017-03-20 19:31:55 Commons Daemon procrun stderr initialized
20-Mar-2017 19:31:57.589 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Server version:        Apache Tomcat/8.5.12
20-Mar-2017 19:31:57.616 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:          Mar 8 2017 17:41:47 UTC
20-Mar-2017 19:31:57.637 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Server number:         8.5.12.0
20-Mar-2017 19:31:57.660 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:               Windows 8.1
20-Mar-2017 19:31:57.661 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:            6.3
20-Mar-2017 19:31:57.662 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:          x86
20-Mar-2017 19:31:57.662 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home:             C:\Program Files (x86)\Java\jre1.8.0_101
20-Mar-2017 19:31:57.663 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version:           1.8.0_101-b13
20-Mar-2017 19:31:57.663 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor:            Oracle Corporation
20-Mar-2017 19:31:57.663 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE:         C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5
20-Mar-2017 19:31:57.664 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME:         C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5
20-Mar-2017 19:31:57.665 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5
20-Mar-2017 19:31:57.665 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5
20-Mar-2017 19:31:57.666 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\temp
20-Mar-2017 19:31:57.666 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
20-Mar-2017 19:31:57.666 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\conf\logging.properties
20-Mar-2017 19:31:57.667 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: exit
20-Mar-2017 19:31:57.667 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Xms128m
20-Mar-2017 19:31:57.667 INFORMACIÓN [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Xmx256m
20-Mar-2017 19:31:57.667 INFORMACIÓN [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent La biblioteca nativa de Apache Tomcat basada en ARP que permite un rendimiento óptimo en entornos de desarrollo no ha sido hallada en java.library.path: C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\TXE Components\TCS\;C:\Program Files\Intel\TXE Components\TCS\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\nodejs\;C:\Program Files\MongoDB\Server\3.2\bin;C:\Program Files\PostgreSQL\9.3\bin;C:\tas-8.3-1\multiserver\enhydra\bin; C:\Program Files\PostgreSQL\9.3\bin;C:\Python27;C:\Python27\Scripts;C:\Program Files (x86)\Skype\Phone\;;.
20-Mar-2017 19:31:58.005 INFORMACIÓN [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8081"]
20-Mar-2017 19:31:58.593 INFORMACIÓN [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
20-Mar-2017 19:31:58.599 INFORMACIÓN [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
20-Mar-2017 19:31:58.605 INFORMACIÓN [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
20-Mar-2017 19:31:58.606 INFORMACIÓN [main] org.apache.catalina.startup.Catalina.load Initialization processed in 2024 ms
20-Mar-2017 19:31:58.680 INFORMACIÓN [main] org.apache.catalina.core.StandardService.startInternal Arrancando servicio Catalina
20-Mar-2017 19:31:58.680 INFORMACIÓN [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.12
20-Mar-2017 19:31:58.761 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Despliegue del archivo C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\MyApplication.war de la aplicación web
20-Mar-2017 19:32:15.612 GRAVE [localhost-startStop-1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:
 org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/MyApplication]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: El mapeo de filtro especifica un nombre desconocido de filtro PrimeFaces FileUpload Filter
    at org.apache.catalina.core.StandardContext.validateFilterMap(StandardContext.java:2987)
    at org.apache.catalina.core.StandardContext.addFilterMap(StandardContext.java:2950)
    at org.apache.catalina.startup.ContextConfig.configureContext(ContextConfig.java:1275)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1190)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:775)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:299)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:94)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5114)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 10 more

20-Mar-2017 19:32:15.615 GRAVE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Error durante el despliegue del archivo C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\MyApplication.war de la aplicación web
 java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/MyApplication]]
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:756)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

20-Mar-2017 19:32:15.621 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\MyApplication.war has finished in 16.856 ms
20-Mar-2017 19:32:15.625 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\docs de la aplicación web
20-Mar-2017 19:32:15.899 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\docs has finished in 274 ms
20-Mar-2017 19:32:15.900 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\examples de la aplicación web
20-Mar-2017 19:32:16.762 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\examples has finished in 862 ms
20-Mar-2017 19:32:16.762 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\host-manager de la aplicación web
20-Mar-2017 19:32:16.833 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\host-manager has finished in 71 ms
20-Mar-2017 19:32:16.834 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\manager de la aplicación web
20-Mar-2017 19:32:16.954 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\manager has finished in 120 ms
20-Mar-2017 19:32:16.955 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\ROOT de la aplicación web
20-Mar-2017 19:32:16.999 INFORMACIÓN [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.5\webapps\ROOT has finished in 44 ms
20-Mar-2017 19:32:17.008 INFORMACIÓN [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler [http-nio-8081]
20-Mar-2017 19:32:17.047 INFORMACIÓN [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler [ajp-nio-8009]
20-Mar-2017 19:32:17.054 INFORMACIÓN [main] org.apache.catalina.startup.Catalina.start Server startup in 18447 ms

tomcat8-stdout.2017-03-20.log
2017-03-20 19:31:55 Commons Daemon procrun stdout initialized

And the web.xml of my application is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>primefaces.THEME</param-name>
        <param-value>bootstrap</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <context-param>
        <param-name>facelets.LIBRARIES</param-name>
        <param-value>/WEB-INF/tsp.taglib.xml</param-value>
    </context-param>

    <context-param>
        <param-name>primefaces.FONT_AWESOME</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
        <param-value>true</param-value>
    </context-param>

    <mime-mapping>
        <extension>ttf</extension>
        <mime-type>application/x-font-ttf</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>woff</extension>
        <mime-type>application/x-font-woff</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>woff2</extension>
        <mime-type>application/x-font-woff2</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>eot</extension>
        <mime-type>application/x-font-eot</mime-type>
    </mime-mapping>
    <filter-mapping>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            -1
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

Could you help me to understand and solve the error?
Thank you very much!!


text:
Q: How to reset all components in Vue.js I'm trying to restart my component when the route changes:
  beforeRouteUpdate (to, from, next) {
    Object.assign(this.$data, this.$options.data())
      console.log(to.query);
      next();
    }

but it doesn't work; it only prints the console.log. I've also tried this.$options.data.call(this) and apply.

A: In order to force Vue to re-render same component upon route query change, it is possible to assign a key to the <router-view it mount's into and push router to the page with the same route name or path.
Example:
Mounting point:
<router-view
  :key="$route.fullPath"
/>

Component navigation, assuming route name is blog
<router-link :to={ name: 'blog', query: { count: 10 } }>Link to the same route</router-link>

This is assuming that you want to reset data of page component while navigating to the same page component with different data.
If component that you want to reset is not the route component, it is possible to reset it's data with watch option, while saving original data.
Example:
data () {
  return {
    initialData: {
      //  some initial data
    },
    data: {}
  }
},
watch: {
  '$route.fullPath': {
    immediate: true, // Immediate option to call watch handler on first mount
    handler () {
      this.resetData()
    }
  }
},
methods: {
  resetData () {
    this.data = Object.assign({}, this.initialData)
  },
},

Note, that any $route options can be watched and additional conditions added to handler via next and previous arguments.

A: Try
          this.$router.reload()


text:
Q: Android run time permission error I am developing an application that required to access contacts in phone. this method is executed inside a thread. But when app start for the first time it crashes and says android.permission.READ_CONTACTS or  android.permission.READ_CONTACTS required as error. as soon as press on OK in on error pop up dialog box. it restart it self asking for permission and works fine.
here's the code inside fragment on onCreateView method to check whether permission already has been granted.
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS)
                == PackageManager.PERMISSION_GRANTED) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    getContacts();
                }
            };
            Thread thread = new Thread(r);
            thread.start();
        }else{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
                    Toast.makeText(getActivity(),"Read contacts permission is required to function app correctly",Toast.LENGTH_LONG)
                            .show();
                }
                requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS);
            }
        }

here's the onRequestPermissionsResult method.
 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case REQUEST_READ_CONTACTS :
                Runnable r = new Runnable() {
                    @Override
                    public void run() {
                        getContacts();
                    }
                };
                Thread thread = new Thread(r);
                thread.start();
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

here's the code for get contact method.
public void getContacts() {
        ContentResolver cr = getActivity().getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cur != null) {
            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    String imgPath = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
                    if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                        Cursor ncur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                        if (ncur != null) {
                            while (ncur.moveToNext()) {
                                String phoneNumber = ncur.getString(ncur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                String reDefinedPhoneNumber = "";
                                if (phoneNumber.contains("-")) {
                                    String[] split = phoneNumber.split("-");

                                    for (String k : split) {
                                        reDefinedPhoneNumber = reDefinedPhoneNumber.concat(k);
                                    }
                                } else if (phoneNumber.contains(" ")) {
                                    String[] split = phoneNumber.split(" ");
                                    for (String k : split) {
                                        reDefinedPhoneNumber = reDefinedPhoneNumber.concat(k);
                                    }
                                } else {
                                    reDefinedPhoneNumber = phoneNumber;
                                }
                                Contact contact = new Contact();
                                contact.setId(contact.getId());
                                contact.setName(name);
                                contact.setNumber(reDefinedPhoneNumber);
                                contact.setImgPath(imgPath);
                                contacts.add(contact);
                            }
                            ncur.close();
                        }
                    }
                }
            }
            cur.close();
        }
    }

Here's AndroidManifest.xml code.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shan.chathuranga.smsscheduler">

    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />

</manifest>

what am I doing wrong. works fine in below marshmallow.


text:
Q: Most PowerApps users getting error "you don't have permission to view this data" I am a beginner in powerapps. I am trying to create app which can be used by employees of my organization and all are having Office 365 accounts. I have shared app with all user but only 3 users (including myself) are able to work on apps and other users are getting below error on first screen of my app.
Error occurred when user open app:

you don't have permission to view this data. server response : The HTTP request is unauthorized with client authentication scheme "Anonymous".The authentication  header received from server was 'browser error in powerApps

A: I had this problem trying to access MS Outlook and MS Teams.  The error is extremely misleading.  The problem was NOT that some administrator had disabled access in certain situations.   The problem was resolved by going to the windows "Credential Manager" and deleting all the old credentials, forcing the MS apps to log you in again, and that then allows me to access those systems.
No idea if this is your situation or not, but anyone receiving this error should first try deleting all the old credentials for that service.

A: This typically means that your users do not have access to a Data Source used by the PowerApp.
When you click File/Share and enter a person/groups name, you will see on the right hand side something to the effect of:
Here are all the data sources your users will need permission to.
Heed this. Otherwise issues like this will ensue.

A: Whenever I encounter this problem, I just go to the SharePoint site, explore the site permissions from the setting, and add the user to the pre-created SharePoint site members group.


text:
Q: How join annotate value of QuerySet and property field of Model to one logic in Django? I have this situation. I calculate a diameter in two ways: annotate of QuerySet and property in Model.
class CircleQuerySet(models.QuerySet):
    def annotate_diameter(self):
        return self.annotate(diameter=models.F('radius')*2)

class Circle(models.Model):
    radius = models.DecimalField(max_digits=11, decimal_places=2)

    objects = CircleQuerySet.as_manager()

    @property
    def diameter(self):
        return self.radius * 2

How can I join this two ways to one? Is it exists?

A: You can add a setter for the diameter property so that you do not get errors when trying to add an annotation of the same name
@property
def diameter(self):
    return self.radius * 2

@diameter.setter
def diameter(self, value):
    return

As for only having the calculation in one place, it is not possible because the annotation is a database instruction and you still need the property for objects that are not retrieved from the database. You could add the annotation to every query by overriding the get_queryset method of the manager so that even .get() will return an object with the annotation.


text:
Q: Save encoded data in java to a file using php (java , php) I want to send files data from Java to PHP and then the php saves the data to a file .
here's my code :
the java code :
 byte[] data=...
 str = new String(data,"ISO-8859-1"); //convert data to String .
// send(str);

and here's the php script:
$data = // get the data from java .
fwrite($fr1,$data);

the problem is that this script work only with text files and not for image files and Zip files .
how can I solve that ?

A: Can you please make it clear?..do you want to read the image or zip file...or want to send them.
in my opinion, Send the path of the image and zip file which you to be read in PHP that would be better approach. There won't be any chance of degrading the quality of the image or problem in extracting the zip file etc.
Below links may help you:
http://blog.joa-ebert.com/2006/05/01/save-bytearray-to-file-with-php/
Saving a bytearray with php received from Flex Air app


text:
Q: (Beginner) Rstudio Desktop Unauthorized http 401 In order to test the code from a bitbucket repository that uses R, I downloaded R and RStudio desktop. When I run devtools::install_bitbucket("spinosae/plunify-ml"), I get an unauthorized http 401 error. How do I resolve this?
(Solved it by creating an account on bitbucket and modifying parts of the installation instructions.)

A: You need to specify auth_user and password as noted in the documentation for ?devtools::install_bitbucket.


text:
Q: Migrating an ASP.NET app to Java I'm trying to migrate a small ASP.NET MVC 2 app to Java on Tomcat 6.  I know the basics of JSPs and servlets.  I don't know any MVC Java web framework.  So I'm trying to determine how to proceed in a way that will keep the migration effort to a minimum.  I know I'll have to rewrite the app in Java but how do I map ASP.NET concepts to Java world?  What Java web framework should I choose given my lack of experience and my deadline of 4 weeks from now?  What's the most agile way to go about this?  Note that I can't use Grails or JRuby or anything like that.  This port must be done using standard Java web frameworks.  I also won't have admin access on the production Tomcat server that this will eventually deployed to.
Are there any migration guide that would be useful? Among other things, I need to understand how best to rewrite the security [current using ASP.NET profiles] and database access [currently using LINQ].

A: Why "This port must be done using standard Java web frameworks"? Is it your boss' requirement?
If really so then it looks like you have not much choice. Strictly speaking a "standard" framework is the one supported by Oracle. Below is what I found on oracle site:  http://download.oracle.com/javaee/6/tutorial/doc/bnadp.html
It looks like currently only JSF is mentioned and thus recommended. I recall more technologies were recommended before?

*

*The Java EE 6 Tutorial Part II The
Web Tier Part II

*

*Chapter 3, Getting Started with Web Applications

*Chapter 4, JavaServer Faces Technology

*Chapter 5, Introduction to Facelets

*Chapter 6, Expression Language

*Chapter 7, Using JavaServer Faces Technology in Web Pages

*Chapter 8, Using Converters, Listeners, and Validators

*Chapter 9, Developing with JavaServer Faces Technology

*Chapter 10, Java Servlet Technology

A: As far as I know, Scooter framework is a rapid web application development framework which just requires developers to know basic JSP/Servlet and MVC concepts. Since your deadline is only 4 weeks away, you can try it. It comes with many examples. See the Hello World example and Blog example. The downside is it may not support LINQ. It does support Oracle, MySQL and PostgreSQL.


text:
Q: Transferring MySQL Workbench to Server I am trying to move my database model from mysql workbench to mysql server. I am using the reverse engineer sql create script but when importing it gives me an error. I have tried to google the problem but no luck to my situation.
-- -----------------------------------------------------
-- Table `MapLibrary`.`Books`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `MapLibrary`.`Books` ;

CREATE TABLE IF NOT EXISTS `MapLibrary`.`Books` (
  `ISBN` VARCHAR(13) NOT NULL,
  `date_of_publication` INT NULL,
  `book_title` VARCHAR(45) NULL,
  PRIMARY KEY (`ISBN`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `MapLibrary`.`Genre`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `MapLibrary`.`Genre` ;

CREATE TABLE IF NOT EXISTS `MapLibrary`.`Genre` (
  `genre_code` INT NOT NULL,
  `genre_name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`genre_code`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `MapLibrary`.`Books_By_Genre`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `MapLibrary`.`Books_By_Genre` ;

CREATE TABLE IF NOT EXISTS `MapLibrary`.`Books_By_Genre` (
  `genre_code` INT NOT NULL,
  `ISBN` VARCHAR(13) NOT NULL,
  PRIMARY KEY (`genre_code`, `ISBN`),
  INDEX `Books_idx` (`ISBN` ASC),
  CONSTRAINT `Books`
    FOREIGN KEY (`ISBN`)
    REFERENCES `MapLibrary`.`Books` (`ISBN`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `Genre`
    FOREIGN KEY (`genre_code`)
    REFERENCES `MapLibrary`.`Genre` (`genre_code`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

ERROR:
ERROR 1022 (23000) at line 89: Can't write; duplicate key in table 'books_by_genre'

Operation failed with exitcode 1

A: The problem is that the ISBN is NOT a unique identifier on its own in the referenced tables.
I assume, that the Books table is your base table and the three referenced tables are M:N link tables. If this is true, then your foreign keys are pointing in the wrong direction. (Try to drag the connection in the other direction?)


text:
Q: hadoop2.2.0 installation on linux ( NameNode not starting ) I am trying to run a single node hadoop cluster on my machine with the following config:
inux livingstream 3.2.0-29-generic #46-Ubuntu SMP Fri Jul 27 17:03:23 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux

I am able to format the namenode without any problems however when I try and start the namenode using :
hadoop-daemon.sh start namenode

I get the following errors :
ishan@livingstream:/usr/local/hadoop$ hadoop-daemon.sh start namenode
Warning: $HADOOP_HOME is deprecated.

mkdir: cannot create directory `/var/log/hadoop/ishan': Permission denied
chown: cannot access `/var/log/hadoop/ishan': No such file or directory
mkdir: cannot create directory `/var/run/hadoop': Permission denied
starting namenode, logging to /var/log/hadoop/ishan/hadoop-ishan-namenode-livingstream.out
/usr/sbin/hadoop-daemon.sh: line 138: /var/run/hadoop/hadoop-ishan-namenode.pid: No such file or directory
/usr/sbin/hadoop-daemon.sh: line 137: /var/log/hadoop/ishan/hadoop-ishan-namenode-livingstream.out: No such file or directory
head: cannot open `/var/log/hadoop/ishan/hadoop-ishan-namenode-livingstream.out' for reading: No such file or directory
/usr/sbin/hadoop-daemon.sh: line 147: /var/log/hadoop/ishan/hadoop-ishan-namenode-livingstream.out: No such file or directory
/usr/sbin/hadoop-daemon.sh: line 148: /var/log/hadoop/ishan/hadoop-ishan-namenode-livingstream.out: No such file or directory

I did not create a separate user "hduser" for hadoop installation. I am using my exsisting username. May be that is why I am facing the problem.
Can someone please help me with this .
Exactly what permissions do I need to alter to get this working ?
UPDATE
After fiddling around and getting around the permission problems I have moved on to new stupidity of errors posted here : hadoop Nanenode wont start
I will forever keep you guys in mind if you can nudge me in the right direction so that I can start some real work on this.


text:
Q: How to make the RecyclerView's ItemTouchHelper work on only part of the list(drag & drop) I use RecyclerView's ItemTouchHelper to change the order(drag & drop),And I want to move only a part of the list.
I don't want to move after a certain index. How can I handle it with one RecyclerView?
If I explain a little more about what I want to make,
The active items are sorted up and the non-active items are sorted down. And only the activated items will shift the order.
Right now, when I drag an active item, it goes down to the area of the non-active item, but I want to prevent it from going down. How can I do it?
UPDATE
open class SimpleItemTouchHelperCallback(private val mAdapter: ItemTouchHelperAdapter) :
    ItemTouchHelper.Callback() {

    private var isLongPressDrag = true

    fun setLongPressDragEnable(isLongPressDrag: Boolean) {
        this.isLongPressDrag = isLongPressDrag
    }

    override fun isLongPressDragEnabled() = isLongPressDrag

    override fun getMovementFlags(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder
    ): Int {
        val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
        val swipeFlags = 0
        return makeMovementFlags(dragFlags, swipeFlags)
    }

    override fun onMove(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        return mAdapter.onItemMove(viewHolder.adapterPosition, target.adapterPosition)
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, i: Int) {
        mAdapter.onItemDismiss(viewHolder.adapterPosition)
    }

}

A: Use ItemTouchHelper.SimpleCallback and override getDragDirs and onMove methods:
ItemTouchHelper.SimpleCallback(
        UP or DOWN,
        0
) {
    override fun getDragDirs(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
        val selectedPosition = viewHolder.adapterPosition
        val isActive: Boolean = // retrieve your model from list and check its active state
        return if (isActive) super.getDragDirs(recyclerView, viewHolder) else 0
    }
    override fun onMove(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder,
            target: RecyclerView.ViewHolder,
    ): Boolean {
        val toPosition = target.adapterPosition
        val isActiveTarget: Boolean = // retrieve your target model from list and check its active state
        if (!isActiveTarget) return false
        val fromPosition = viewHolder.adapterPosition
        moveItem(fromPosition, toPosition)
        return true
    }
}

Returning 0 on getDragDirs prevents inactive item selection, while returning false on onMove prevents item movement while dragging.


text:
Q: Getting GraphicDeviceManager from another class I've been searching for a way to use the GraphicDeviceManager in other classes that don't inherit from Microsoft.Xna.Framework.Game
I'm using the Game State Management example.
I've got a class called "FirstLevel" which is essentialy GamePlayScreen from the example, I'm trying to get that class to use the GraphicsDeviceManager to do code such as the following;
        this.graphics.PreferredBackBufferWidth = 1920;
        this.graphics.PreferredBackBufferHeight = 1080;

But it has no idea what "graphics" actually is.
What are my options in terms of getting a hold of a GraphicsDeviceManager and using it in the FirstLevel class?
I can't inherit from Microsoft.Xna.Framework.Game because my class is already inheriting from GameScreen.
I heard somwhere that you can use the DrawableGameComponent class to access a GraphicsDeviceManager, such as the class "ScreenManager" which inherits from this class.
I cant pass Microsoft.Xna.Framework.Game into the constructor of firstLevel because other classes that call it need to get the GraphicsDeviceManager to pass into it.
Any help guys?
Thanks.

A: The usual is passing to your GameScreen constructor the game instance as a Game parameter.
A GraphicDeviceManager is used to initializate graphics, inside a game you should use the GraphicsDevice instance provided by the game instance.
public class GameScreen {

    public Game Game;
    public GameScreen(Game game) {
        this.Game = game;
    }

    public void Update()
    {
       Game.GraphicsDevice....
    }
}


text:
Q: Force page refresh and jump to a #section It seems that I must be missing something completely elementary. What I'm trying to achieve looks like quite a common case, and so it makes me wonder why there is no straightforward way.
The problem is that I would like to refresh the current page from JavaScript and simultaneously land on a #section. If I do simply:
document.location.href = document.location.href + "#section";

all browsers I tested just scroll to that #section (no reload). It makes sense in a way. Just for completeness, if I do
document.location.assign(document.location.href + "#section");

it does the same thing (not surprisingly; it boils down internally to the same function for sure). Finally, the document object seems to have also the document.reload() function which takes an optional boolean argument specifying whether I want to force the reload, but obviously, it does not allow to specify the #section. The only way I could find (using these methods) was the following combination:
document.location.assign(document.location.href + "#section");
document.location.reload();

But it is not ideal, because as you have probably guessed, it scrolls and then reloads which causes the browser to actually scroll three times in the end.
I know that there are ways around it: server side redirect or adding some unique random query string parameter, but it seems strange that there is no simple way.

A: That is the "hash" value of the location object.  You need to set it like this...
location.hash = "#section";

If that does not work consistently, you might want to consider using a scrollToElement function...
function scrollToElement(elem) {
    if(typeof elem == 'string') elem = document.getElementById(elemId);
    var top = 0;

    if(elem) {
        if(elem.offsetParent) {
            top = elem.offsetTop;

            while(elem = elem.offsetParent) {
                top += elem.offsetTop;
            }
        }

        window.scrollTo(0, top);
    }

}

If you absolutely need a page reload (not sure why you ever would), try opening a window in itself...
window.open(location.href + '#section', '_top');

Or try replace...
location.replace(location.href + '#section');

A: There is a much much simpler solution:
if (document.location.href.match(/[?]/))
  document.location.href = document.location.href + '&fake_param=' + Math.random() + '#section'  ;
else
  document.location.href = document.location.href + '?fake_param=' + Math.random() + '#section'  ;


text:
Q: Slot machine TimeLine animation not working I am trying to develop a slot machine reel application. I have a custom reel pane which adds children vertically. When a spin button is clicked children have to move and when the last child reaches a boundary it has to shift its position above the first child. What I did is shown below.
public class ReelPane extends Pane {

    Timeline timeline = new Timeline();

    @Override
    protected void layoutChildren() {

        List<Node> managed = getChildren();
        double y = 0;
        for (Node node : managed) {
            node.setLayoutX(0);
            node.setLayoutY(y);
            y += node.getBoundsInLocal().getHeight();
        }
    }

    public void spin() {
        List<Node> managed = getChildren();
        double dy = 4;
        for (Node node : managed) {
            timeline.getKeyFrames().addAll(new KeyFrame(Duration.millis(2000),new KeyValue(node.layoutYProperty(),node.getLayoutY()+dy)));

            if(node.getLayoutY()>=600){
                node.setLayoutY(-50);
            }

        }
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.play();
    }
}

fxml file
<?import javafx.scene.control.Button?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.Pane?>
<?import sample.ReelPane?>
<Pane stylesheets="@css/slot.css"
      xmlns:fx="http://javafx.com/fxml/1"
      xmlns="http://javafx.com/javafx"
      fx:controller="sample.Controller">
    <ReelPane fx:id="reel" styleClass="container">

        <ImageView fitHeight="100" fitWidth="100">
            <Image url="/sample/resources/apple.png"/>
        </ImageView>

        <ImageView fitHeight="100" fitWidth="100">
            <Image url="/sample/resources/diamond.png"/>
        </ImageView>

        <ImageView fitHeight="100" fitWidth="100">
            <Image url="/sample/resources/glass.png"/>
        </ImageView>

        <ImageView fitHeight="100" fitWidth="100">
            <Image url="/sample/resources/grape.png"/>
        </ImageView>

        <ImageView fitHeight="100" fitWidth="100">
            <Image url="/sample/resources/star.png"/>
        </ImageView>
    </ReelPane>

    <Button fx:id="spin" text="SPIN"/>
</Pane>

controller
package sample;

import javafx.fxml.FXML;
import javafx.scene.control.Button;

public class Controller {

    @FXML
    ReelPane reel;
    @FXML
    Button spin;

    public void initialize() {
        spin.setOnAction(event -> reel.spin());
    }
}

main
package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application  {

    @Override
    public void start(Stage primaryStage) throws Exception {
         Parent root =
       FXMLLoader.load(getClass().getResource("resources/fxml/slot.fxml"));
        primaryStage.setScene(new Scene(root, 400, 900));
        primaryStage.show();

}
    public static void main(String[] args) {
        launch(args);
    }
}

But the children are not moving when button is clicked.Can someone tell what went wrong?

A: All of the KeyFrames of your Timeline are scheduled at the same time. Furthermore the if statement is executed before you even start the animation.
Imho it's easier to put all the elements in a VBox and simply repeatedly change translateY repeatedly from a negative value equal to the element height to 0 and move the last element to the front at the end of the cycle. You may want to apply a clip to the parent of the VBox though to hide anything exceeding the bounds of a single element.
@Override
public void start(Stage primaryStage) throws Exception {
    VBox pane = new VBox();
    Pane parent = new Pane(pane);
    parent.setPrefSize(50, 50);
    parent.setMinSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
    parent.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
    Timeline timeline = new Timeline(new KeyFrame(Duration.ZERO, new KeyValue(pane.translateYProperty(), -50d)),
            new KeyFrame(Duration.seconds(2), evt -> {
                pane.getChildren().get(pane.getChildren().size() - 1).toBack();
            }, new KeyValue(pane.translateYProperty(), 0d)));
    timeline.setCycleCount(Animation.INDEFINITE);
    for (int i = 0; i < 6; i++) {
        Rectangle rect = new Rectangle(50, 50, Color.RED.interpolate(Color.BLACK, i / 6d));
        pane.getChildren().add(rect);
    }
    parent.setClip(new Rectangle(50, 50));
    timeline.play();
    Scene scene = new Scene(new StackPane(parent), 200, 200);
    primaryStage.setScene(scene);
    primaryStage.show();
}

A: A much simpler tool for the needed animation is PauseTransition.
If you do not want to specify the layout in the fxml you can override layoutChildren() as you did but you'll need to disable automatic layout (layoutChildren()) so the animation can change positions:
import java.util.List;
import javafx.animation.PauseTransition;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
import javafx.util.Duration;

public class ReelPane extends Pane {

    private List<Node> managed;
    private double dy, numberOfCchildren;
    private boolean isAnimating = false;
    private static final double PAUSE = 1;

    @Override
    protected void layoutChildren() {

        if(isAnimating) return;
        managed = getChildren();
        numberOfCchildren = managed.size();
        double y = 0;
        for (Node node : managed) {
            node.setLayoutX(0);
            node.setLayoutY(y);
            dy = Math.max(dy, node.getBoundsInLocal().getHeight()); //dy stores the highest
            y += dy;
        }
    }
    public void spin() {

        isAnimating = true;
        PauseTransition pause = new PauseTransition(Duration.seconds(PAUSE));
        pause.setOnFinished(event ->{
            for (Node node : managed) {

                if(node.getLayoutY()>= (numberOfCchildren -1) * dy){
                    node.setLayoutY(-dy);
                }
                node.setLayoutY(node.getLayoutY() +dy);
            }
            pause.play();
        });

        pause.play();
    }
}

Consider disabling the button while spinning:
import javafx.fxml.FXML;
import javafx.scene.control.Button;

public class Controller {

    @FXML
    ReelPane reel;
    @FXML
    Button spin;

    public void initialize() {

        spin.setOnAction(event -> {
            reel.spin();
            spin.setDisable(true);
        });
    }
}

To make the code mre here is the slot.fxml using publicly available resources:
<?import javafx.scene.control.Button?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.Pane?>
<?import fx_tests.ReelPane?>

<Pane
      xmlns:fx="http://javafx.com/fxml/1"
      xmlns="http://javafx.com/javafx"
      fx:controller="fx_tests.sample.Controller">

    <ReelPane fx:id="reel">

        <ImageView fitHeight="100" fitWidth="100">
            <Image url="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/128x128/Box_Green.png"/>
        </ImageView>

       <ImageView fitHeight="100" fitWidth="100" >
            <Image url="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/128x128/Box_Red.png"/>
        </ImageView>

        <ImageView fitHeight="100" fitWidth="100">
            <Image url="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/128x128/Box_Yellow.png"/>
        </ImageView>

        <ImageView fitHeight="100" fitWidth="100" >
           <Image url="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/128x128/Box_Blue.png"/>
        </ImageView>

        <ImageView fitHeight="100" fitWidth="100">
            <Image url="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/128x128/Box_Orange.png"/>
        </ImageView>

    </ReelPane>

    <Button fx:id="spin" text="SPIN" layoutX="20." layoutY="550.0" />

</Pane>

A test application:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application  {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root =
        FXMLLoader.load(getClass().getResource("slot.fxml"));
        primaryStage.setScene(new Scene(root, 200, 600));
        primaryStage.show();

}
    public static void main(String[] args) {
        launch(args);
    }
}


text:
Q: How do I add an XML attribute using DataContract I have a simple class I'm serializing.
 [DataContract(Name = "Test", Namespace = "")]
 public class Test
 {
    [DataMember(Order = 0, Name = "Text")]
    public string Text { get; set; }

    public Test() {}
 }

This kicks out the following XML:
<Test>
   <Text>Text here</Text>
</Test>

What I want is:
<Test>
   <Text type="MyType">Text here</Text>
</Test>

How do I add attributes the the XML elements?
Thanks in advance.

A: Not exactly an answer, but you can try to implement IXmlSerializable to fully control output xml format.

A: You can't add attributes to a DataContract. You either have to use a class that Implements ISerializable or use the .Net XmlSerializer.

A: I was able to achieve this by declaring an XElement which has attributes defined in it. Ex:
public XElement Text { get; set;}

A: Add the type attribute with [XMLAttribute] and the element value with [XmlText].
public class Test
{
    public text Text;

    public Test()
    {
        Text = new text();
    }

    [DataContract(Name = "Test", Namespace = "")]
    public class text
    {
        [XmlText]
        public string Text { get; set; }
        [XmlAttribute]
        public string type { get; set; }
    }
}


text:
Q: Загрузка Счетов и Актов в 1С из файлов, сгенерированных в PHP Имеется: 1С Предприятие 8.2 + Бухгалтерия 2.0
Нужно каким-нибудь образом загружать в 1Ску счета и акты.
В 1С не бум бум, но знаю, что наш бухгалтер все платежки из Сбербанк Бизнес-он-лайн выгружает в текстовый файл, который потом использует в 1С (через кнопку "Загрузить выписку").
Наверное как-то можно и счета и акты загружать в 1С через файл?
Скажите в какую сторону копать? Где искать решение? Сгенерировать нужные txt, excel, csv файлы я смогу на стороне php, важно найти решения загрузки их в 1С.

A: "Загрузить выписку" = Обработка на языке 1С, которая читает файлик, выгруженный из клиент-банка и создает соответствующий документ(-ы) в базе.
Поэтому, копать нужно в сторону 1С-ника, который напишет обработку для создания Актов/Счетов из файла с данными, который предоставите ему вы.
Второй вариант: смотреть на шлюз интеграции с 1С<->1С:Битрикс (CommerceML - суть XML с синтаксисом на русском), но "из-коробки" у Битрикса обработки расчитаны на 1С:Управление торговлей, а не Бухгалтерию.
Третий вариант: поискать готовые обработки загрузки на Инфостарте.
В любом случае, придется либо самому вникать в код обработок и быть готовым его править, либо искать 1С-ника.


text:
Q: Python Tuple Class Memory Why does the use of tuple instead of list in objects below increase memory usage?
from pympler.asizeof import asizeof

class myClass(object):
    __slots__ = ('l')
    def __init__(self, m):
        self.l = m

m = range(10)
ob = [myClass(m) for i in xrange(100000)]

print asizeof(ob)
for o in ob:
    o.l = tuple(o.l)
print asizeof(ob)

The first has size  64697936
The second has size 200697784

A: In your original code, every myClass instance points to the same list.
>>> ob[0].l.append('foo')
>>> ob[1].l
['foo']

In other words: you compared the memory usage of one list to that of 100,000 tuples. Compare it to 100,000 lists instead:
for o in ob:
    o.l = list(o.l)

with these results:
6424936
27224856

The original:
6424936
20024784


text:
Q: How can I create a folder dynamically during replication? While doing replication I received the following error message in Replication monitor → Agents

Access to the path 'D:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\repldata\unc\_DEMO_SAMPLE\20160602154451\' is denied.

If the folder is manually created, then the error is solved for some time.  However, after some time the error occurs again because the timestamp (20160602154451) has changed.  How can I create a folder dynamically?  Or can anyone suggest another solution to this problem?

A: When installing sql server I always make the UNC folder a shared folder.
You either make it RW available to everyone, not big deal for security.
Or identify the network login on which the replication agent is using and give it modify access to that folder.
This login was set during the sql server install.