text:
Q: Why doesn't shell automatically fix "useless use of cat"? Many people use oneliners and scripts containing code along the lines
cat "$MYFILE" | command1 | command2 > "$OUTPUT"

The first cat is often called "useless use of cat" because technically it requires starting a new process (often /usr/bin/cat) where this could be avoided if the command had been
< "$MYFILE" command1 | command2 > "$OUTPUT"

because then shell only needs to start command1 and simply point its stdin to the given file.
Why doesn't the shell do this conversion automatically? I feel that the "useless use of cat" syntax is easier to read and shell should have enough information to get rid of useless cat automatically. The cat is defined in POSIX standard so shell should be allowed to implement it internally instead of using a binary in path. The shell could even contain implementation only for exactly one argument version and fallback to binary in path.

A: The cat command can do things that the shell can't necessarily do (or at least, can't do easily). For example, suppose you want to print characters that might otherwise be invisible, such as tabs, carriage returns, or newlines. There *might* be a way to do so with only shell builtin commands, but I can't think of any off the top of my head. The GNU version of cat can do so with the -A argument or the -v -E -T arguments (I don't know about other versions of cat, though). You could also prefix each line with a line number using -n (again, IDK if non-GNU versions can do this).
Another advantage of cat is that it can easily read multiple files. To do so, one can simply type cat file1 file2 file3.  To do the same with a shell, things would get tricky, although a carefully-crafted loop could most likely achieve the same result. That said, do you really want to take the time to write such a loop, when such a simple alternative exists? I don't!
Reading files with cat would probably use less CPU than the shell would, since cat is a pre-compiled program (the obvious exception is any shell that has a builtin cat). When reading a large group of files, this might become apparent, but I have never done so on my machines, so I can't be sure.
The cat command can also be useful for forcing a command to accept standard input in instances it might not. Consider the following:
echo 8 | sleep
The number "8" will be not accepted by the "sleep" command, since it was never really meant to accept standard input. Thus, sleep will disregard that input, complain about a lack of arguments, and exit. However, if one types:
echo 8 | sleep $(cat)
Many shells will expand this to sleep 8, and sleep will wait for 8 seconds before exiting. You can also do something similar with ssh:
command | ssh 1.2.3.4 'cat >> example-file'
This command with append example-file on the machine with the address of 1.2.3.4 with whatever is outputted from "command".
And that's (probably) just scratching the surface. I'm sure I could find more example of cat being useful if I wanted to, but this post is long enough as it is. So, I'll conclude by saying this: asking the shell to anticipate all of these scenarios (and several others) is not really feasible.

A: "Useless use of cat" is more about how you write your code than about what actually runs when you execute the script. It's a sort of design anti-pattern, a way of going about something that could probably be done in a more efficient manner. It's a failure in understanding of how to best combine the given tools to create a new tool. I'd argue that stringing several sed and/or awk commands together in a pipeline also sometimes could be said to be a symptom of this same anti-pattern.
Fixing instances of "useless use of cat" in a script is a primarily matter of fixing the source code of the script manually.  A tool such as ShellCheck can help with this by pointing out the obvious cases:
$ cat script.sh
#!/bin/sh
cat file | cat

$ shellcheck script.sh

In script.sh line 2:
cat file | cat
    ^-- SC2002: Useless cat. Consider 'cmd < file | ..' or 'cmd file | ..' instead.

Getting the shell to do this automatically would be difficult due to the nature of shell scripts.  The way a script executes depends on the environment inherited from its parent process, and on the specific implementation of the available external commands.
The shell does not necessarily know what cat is.  It could potentially be any command from anywhere in your $PATH, or a function.
If it was a built-in command (which it may be in some shells), it would have the ability to reorganise the pipeline as it would know of the semantics of its built-in cat command.  Before doing that, it would additionally have to make assumptions about the next command in the pipeline, after the original cat.
Note that reading from standard input behaves slightly differently when it's connected to a pipe and when it's connected to a file.  A pipe is not seekable, so depending on what the next command in the pipeline does, it may or may not behave differently if the pipeline was rearranged (it may detect whether the input is seekable and decide to do things differently if it is or if it isn't, in any case it would then behave differently).
This question is similar (in a very general sense) to "Are there any compilers that attempt to fix syntax errors on their own?" (at the Software Engineering StackExchange site), although that question is obviously about syntax errors, not useless design patterns. The idea about automatically changing the code based on intent is largely the same though.

A: Because it's not useless.
In the case of cat file | cmd, the fd 0 (stdin) of cmd will be a pipe, and in the case of cmd <file it may be a regular file, device, etc.
A pipe has different semantics from a regular file, and its semantics are not a subset of those of a regular file:

*

*a regular file cannot be select(2)ed or poll(2)ed on in a meaningful way; a select(2) on it will always return "ready". Advanced interfaces like epoll(2) on Linux will simply not work with regular files.

*on Linux there are system calls (splice(2), vmsplice(2), tee(2)) which only work on pipes [1]
Since cat is so much used, it could be implemented as a shell built-in which will avoid an extra process, but once you started on that path, the same thing could be done with most commands -- transforming the shell into a slower & clunkier perl or python. it's probably better to write another scripting language with an easy to use pipe-like syntax for continuations instead ;-)
[1] If you want a simple example not made up for the occasion, you can look at my "exec binary from stdin" git gist with some explanations in the comment here. Implementing cat inside it in order to make it work without UUoC would have made it 2 or 3 times bigger.

A: Remember that a user could have a cat in his $PATH which is not exactly the POSIX cat (but perhaps some variant which could log something somewhere). In that case, you don't want the shell to remove it.
The PATH  could change dynamically, and then cat  is not what you believe it is. It would be quite difficult to write a shell doing the optimization you dream of.
Also, in practice, cat  is a quite quick program. There are few practical reasons (except aesthetics) to avoid it.
See also the excellent Parsing POSIX [s]hell talk by Yann Regis-Gianas at FOSDEM2018. It gives other good reasons to avoid attempting doing what you dream of in a shell.
If performance was really an issue for shells, someone would have proposed a shell which uses sophisticated whole program compiler optimization, static source code analysis, and just-in-time compilation techniques (all these three domains have decades of progress and scientific publications and dedicated conferences, e.g. under SIGPLAN). Sadly, even as an interesting research topic, that is not currently funded by research agencies or venture capitalists, and I am deducing that it is simply not worth the effort. In other words, there is probably no significant market for optimizing shells. If you have half a million euro to spend on such research, you'll easily find someone to do it, and I believe it would give worthwhile results.
On a practical side, rewriting, to improve its performance, a small (un hundred lines) shell script in any better scripting language (Python, AWK, Guile, ...) is commonly done. And it is not reasonable (for many software engineering reasons) to write large shell scripts: when you are writing a shell script exceeding a hundred lines, you do need to consider rewriting it (even for readability and maintenance reasons) in some more suitable language: as a programming language the shell is a very poor one. However, there are many large generated shell scripts, and for good reasons (e.g. GNU autoconf generated configure scripts).
Regarding huge textual files, passing them to cat as a single argument is not good practice, and most sysadmins know that (when any shell script takes more than a minute to run, you begin considering optimizing it). For large gigabytes files, cat is never the good tool to process them.

A: The 2 commands are not equivalent: consider error handling:
cat <file that doesn't exist> | less will produce an empty stream that will be passed to the piped program... as such you end up with a display showing nothing.
< <file that doesn't exist> less will fail to open bar, and then not open less at all.
Attempting to change the former to the latter could break any number of scripts that expect to run the program with a potentially blank input.

A: Adding to @Kusalananda answer (and @alephzero comment), cat could be anything:
alias cat='gcc -c'
cat "$MYFILE" | command1 | command2 > "$OUTPUT"

or
echo 'echo 1' > /usr/bin/cat
cat "$MYFILE" | command1 | command2 > "$OUTPUT"

There is no reason that cat (on its own) or /usr/bin/cat on the system is actually cat the concatenate tool.

A: Because detecting useless cat is really really hard.
I had a shell script where I wrote
cat | (somecommand <<!
...
/proc/self/fd/3
...
!) 0<&3

The shell script failed in production if the cat was removed because it was invoked via su -c 'script.sh' someuser. The apparently superfluous cat caused the owner of standard input to change to the user the script was running as so that reopening it via /proc worked.

A: tl;dr: Shells don't do it automatically because the costs exceed the likely benefits.
Other answers have pointed out the technical difference between stdin being a pipe and it being a file. Keeping that in mind, the shell could do one of:

*

*Implement cat as a builtin, still preserving the file v. pipe distinction. This would save the cost of an exec and maybe, possibly, a fork.

*Perform a full analysis of the pipeline with knowledge of the various commands used to see if file/pipe matters, then act based on that.

Next you have to consider the costs and benefits of each approach. The benefits are simple enough:

*

*In either case, avoid an exec (of cat)

*In the second case, when redirect substitution is possible, avoidance of a fork.

*In cases where you have to use a pipe, it might be possible sometimes to avoid a fork/vfork, but often not. That's because the cat-equivalent needs to run at the same time as the rest of the pipeline.

So you save a little CPU time & memory, especially if you can avoid the fork. Of course, you only save this time & memory when the feature is actually used. And you're only really saving the fork/exec time; with larger files, the time is mostly the I/O time (i.e., cat reading a file from disk). So you have to ask: how often is cat used (uselessly) in shell scripts where the performance actually matters? Compare it to other common shell builtins like test — it's hard to imagine cat is used (uselessly) even a tenth as often as test is used in places that matter. That's a guess, I haven't measured, which is something you'd want to do before any attempt at implementation. (Or similarly, asking someone else to implement in e.g., a feature request.)
Next you ask: what are the costs. The two costs that come to mind are (a) additional code in the shell, which increases its size (and thus possibly memory use), requires more maintenance work, is another spot for bugs, etc.; and (b) backwards compatibility surprises, POSIX cat omits a lot of features of e.g., GNU coreutils cat, so you'd have to be careful exactly what the cat builtin would implement.

*

*The additional builtin option probably isn't that bad — adding one more builtin where a bunch already exist. If you had profiling data showing it'd help, you could probably convince your favorite shell's authors to add it.

*As for analyzing the pipeline, I don't think shells do anything like this currently (a few recognize the end of a pipeline and can avoid a fork). Essentially you'd be adding a (primitive) optimizer to the shell; optimizers often turn out to be complicated code and the source of a lot of bugs. And those bugs can be surprising — slight changes in the shell script could wind up avoiding or triggering the bug.
Postscript: You can apply a similar analysis to your useless uses of cat. Benefits: easier to read (though if command1 will take a file as an argument, probably not). Costs: extra fork and exec (and if command1 can take a file as an argument, probably more confusing error messages). If your analysis tells you to uselessly use cat, then go ahead.

A: The cat command can accept - as a marker for stdin. (POSIX, "If a file is '-', the cat utility shall read from the standard input at that point in the sequence.") This allows simple handling of a file or stdin where otherwise this would be disallowed.
Consider these two trivial alternatives, where the shell argument $1 is -:
cat "$1" | nl    # Works completely transparently
nl < "$1"        # Fails with 'bash: -: No such file or directory'

Another time cat is useful is where it's intentionally used as a no-op simply to maintain shell syntax:
file="$1"
reader=cat
[[ $file =~ \.gz$ ]] && reader=zcat
[[ $file =~ \.bz2$ ]] && reader=bzcat
"$reader" "$file"

Finally, I believe the only time that UUOC can really be correctly called out is when cat is used with a filename that is known to be a regular file (i.e. not a device or named pipe), and that no flags are given to the command:
cat file.txt

In any other situation the oroperties of cat itself may be required.

A: Two "useless" uses for cat:
sort file.txt | cat header.txt - footer.txt | less

...here cat is used to mix file and piped input.
find . -name '*.info' -type f | sh -c 'xargs cat' | sort

...here xargs can accept a virtually infinite number of filenames and run cat as many times as needed while making it all behave like one stream. So this works for large file lists where direct use of xargs sort does not.

A: Aside from other things, cat-check would add additional performance overhead and confusion as to which use of cat is actually useless, IMHO, because such checks can be inefficient and create problems with legitimate cat usage.
When commands deal with the standard streams, they only have to care about reading/writing to the standard file descriptors. Commands can know if stdin is seekable/lseekable or not, which indicates a pipe or file.
If we add to the mix checking what process actually provides that stdin content, we will need to find the process on the other side of the pipe and apply appropriate optimization. This can be done in terms of shell itself, as shown in the SuperUser post by Kyle Jones, and in terms of shell that's
(find /proc -type l | xargs ls -l | fgrep 'pipe:[20043922]') 2>/dev/null

as shown in the linked post. This is 3 more commands (so extra fork()s and exec()s) and recursive traversals ( so whole lot of readdir() calls ).
In terms of C and shell source code, the shell already knows the child process,so there's no need for recursion, but how do we know when to optimize and when cat is actually useless ? There are in fact useful uses of cat, such as
# adding header and footer to file
( cmd; cat file; cmd ) | cmd
# tr command does not accept files as arguments
cat log1 log2 log3 | tr '[:upper:]' '[:lower:]'

It would probably be waste and unnecessary overhead to add such optimization to the shell. As Kusalanda's answer mentioned already, UUOC is more about user's own lack of understanding of how to best combine commands for best results.


text:
Q: Finding the solution for $Ax=0$ Find the solution for $Ax=0$ for the following $3 \times 3$ matrix:
$$\begin{pmatrix}3 & 2& -3\\ 2& -1&1 \\ 1& 1& 1\end{pmatrix}$$
I found the row reduced form of that matrix, which was
$$\begin{pmatrix}1 & 2/3& -1\\ 0& 1&-9/7 \\ 0& 0& 1\end{pmatrix}$$
I'm not sure what I'm supposed to do next to find the "unique" solution besides $x=0$? Do I further reduce that matrix to the identity matrix?

A: You have shown that matrix is non singular (or invertible), so that the only solution, as you state, is ${\bf x}=0$.

A: First note that any linear system of the form $\mathbf{Ax} = \mathbf{0}$ has either one solution (which is $\mathbf{x} = \mathbf{0}$) or infinite solutions. In your case, once you reduce $\mathbf{A}$ to row-echelon form, none of the entries on the leading diagonal are zero. This means your matrix is invertible.
Hence, the only solution is $\mathbf{x} = \mathbf{0}$

A: now if you imagine   that  our  vector solution is
$x=x_1,x_2,x_3$
than we will get
$x_3=0$
$x_1+(2*x_2)/3=0$
$x_2=0$
so after inserting $x_3,x_2$   into first you get $x_1=0$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a better way to send variables to blade? I'm still learning Laravel and how the blade system all works..
I'm wondering what the better way of doing something is and that something is; I've done a query to pull a row from the database and then I want to put that query into an array so I can pick out whatever column I want.
Then I want to pass that to my home.blade.php and be able to use {{ $name }} for example. T
This is what I've got:
TO NOTE: THIS WORKS THE WAY I WANT IT TO BUT IM SURE IM DOING IT THE LONG WAY (WRONG) ROUND.
HomeController.php
<?php
class HomeController extends BaseController {
    public function home() {

        $hero_query = DB::table('heros')->where('owner_id', Auth::user()->id)->pluck('hero');

        if($hero_query) {
            $owner_id = Auth::user()->id;
            $user = DB::table('heros')->where('owner_id', $owner_id)->first();

            $name = $user->hero;
            $level = $user->level;
            $exp = $user->exp;
            $str = $user->str;
            $atk = $user->atk;
            $def = $user->def;
            $int = $user->int;
            $blk = $user->blk;

            return View::make('home', array(
                'name'  => $name,
                'level' => $level,
                'exp'   => $exp,
                'str'   => $str,
                'atk'   => $atk,
                'def'   => $def,
                'int'   => $int,
                'blk'   => $blk
            ));
        } else {
            return View::make('home');
        }
    }
}

home.blade.php
@if($hero = DB::table('heros')->where('owner_id', Auth::user()->id)->pluck('hero'))
                <form action="{{ URL::route('hero-delete') }}" method="POST">
                    Your hero:

                    {{ $hero; }} | <input type="submit" value="Delete">

                    Stats:
                        LvL: {{ $level }}
                        Exp: {{ $exp }}
                        Str: {{ $str }}
                        Atk: {{ $atk }}
                        Def: {{ $def }}
                        Int: {{ $int }}
                        Blk: {{ $blk }}
                </form>
            @else
                <form action="{{ URL::route('hero-create') }}" method="POST">
                    Hero:

                    You do not have a hero, create one!
                    <input type="text" name="hero">
                    <input type="submit" value="Create hero">

                    @if($errors->has('hero'))
                        {{ $errors->first('hero')}}
                    @endif

                    {{ Form::token()}}
                </form>
            @endif

Now I'm sure I'm doing it in some stupid moronic way as I'm just starting out.. but could someone explain where I'm going wrong?
Thanks in advance!

A: Just pass the entire $user to the view
$user = DB::table('heros')->where('owner_id', $owner_id)->first();
return View::make('home', array('user' => $user));

Then in your view
Str: {{ $user->str }}
Int: {{ $user->int }}

and so on.

A: You're doing lots of things wrong :(
I fix a little bit the code, but I didn't test it, so use this as a guide to implement what you want.
class HomeController extends BaseController {

    public function home() {

        $hero = Hero::where('owner_id', '=', $owner_id)->first();

        if($hero)
        {
            return Response::make('home', array('hero' => $hero->toArray()));
        }
        else
        {
            return Response::make('home');
        }
    }
}

The blade template
@if(isset($hero))
    {{ Form::open(array('route' => 'hero-delete', 'method' => 'DELETE')) }}
        Your hero:

        {{ $hero->hero }} | <input type="submit" value="Delete">

        Stats:

            LvL: {{ $hero->level }}
            Exp: {{ $hero->exp }}
            Str: {{ $hero->str }}
            Atk: {{ $hero->atk }}
            Def: {{ $hero->def }}
            Int: {{ $hero->int }}
            Blk: {{ $hero->blk }}
    {{ Form::close() }}
@else
    {{ Form::open(array('route' => 'hero-create')) }}
        Hero:

        You do not have a hero, create one!
        <input type="text" name="hero">
        <input type="submit" value="Create hero">

        @if($errors->has('hero'))
            {{ $errors->first('hero')}}
        @endif
    {{ Form::close() }}
@endif


text:
Q: Чтение файлов из asset Android В простом Java приложении все просто. Используется BufferReader.
try {
    BufferedReader in = new BufferedReader(new FileReader("dictionary.txt"));
        while ((word = in.readLine()) != null) {
            dictionary.put(word, 0);
        }
        in.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

И тогда все строки файла записаны в HashMap, с которым дальше работаем.
Но как сделать так, что бы Android увидел этот файл. Файл лежит в папке asset. Как бы логично что:
try {
        AssetManager assetManager;
        BufferedReader in = new BufferedReader(assetManager.open("dictionary.txt"));
        while ((word = in.readLine()) != null) {
            dictionary.put(word, 0);
        }
        in.close();
        //assetManager.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

Но нет, ошибка. Как достать этот файл?
UPD *SOLVED*
Метод:
public static void loadDictionary (Context context) throws IOException {
        try {
            AssetManager assetManager = context.getAssets();
            InputStreamReader istream = new InputStreamReader(assetManager.open("dictionary.txt"));
            BufferedReader in = new BufferedReader(istream);

            while ((word = in.readLine()) != null) {
                dictionary.put(word, 0);
            }
            in.close();
        } catch (FileNotFoundException e) {
            // FileNotFoundExpeption
        } catch (IOException e) {
            // IOExeption
        }
}

Вызов:
try {
    Spell.loadDictionary(getBaseContext());
} catch (IOException e) {
    //IOExpeptino
}

Спасибо user - afiki
A: AssetManager assetManager = this.getAssets();

а ты пытаешься вызвать метод у null.
try {
    AssetManager assetManager = this.getAssets();
    InputStreamReader istream = new InputStreamReader(assetManager.open("dictionary.txt"));
    BufferedReader in = new BufferedReader(istream);

    while ((word = in.readLine()) != null) {
        dictionary.put(word, 0);
    }

    in.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}


text:
Q: JavaFX child AnchorPane not showing after adding to parent AnchorPane So I am working on building an application that is kind of like an IDE, think Eclipse or Netbeans. I want to have different zones where users can select something like a view that will show up in one of the zones. My first attempt is to add a console view to on of my zones. In my application class I create the overall UI with the following code:
public void initialize() {
    try {
        mainController = (MainController) replaceSceneContent("/layout/main.fxml");
    }catch (Exception ex) {
        Logger.getLogger(MyApplication.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private Initializable replaceSceneContent(String fxml) throws Exception {

    FXMLLoader loader = new FXMLLoader();
    InputStream in = MyApplication.class.getResourceAsStream(fxml);
    loader.setBuilderFactory(new JavaFXBuilderFactory());
    loader.setLocation(MyApplication.class.getResource(fxml));

    AnchorPane page;
    try {
        page = (AnchorPane) loader.load(in);
    } finally {
        in.close();
    }

    Scene scene = new Scene(page);
    stage.setScene(scene);
    stage.sizeToScene();

    return (Initializable) loader.getController();
}

Which results in the following UI

I would then like to add a console widget/view to the southEast quadrant of the application. This will be handled by the MainController. In theory if someone chooses the Console view it will popup in one of the quadrants, but for now I just want to load it at start up. I try to do this with the following code:
public class MainController extends AnchorPane implements Initializable{

@FXML
SplitPane west, east;
@FXML
AnchorPane northWest, southWest, northEast, southEast, applicationHeader;
@FXML
MenuBar menuBar;

Stage stage;

@Override
public void initialize(URL arg0, ResourceBundle arg1) {
    try {
        ConsoleWidget cw = (ConsoleWidget)loadWidget("/widget/console.fxml");
        southEast.getChildren().add(cw);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private Initializable loadWidget(String fxml) throws Exception {

    FXMLLoader loader = new FXMLLoader();
    InputStream in = MainController.class.getResourceAsStream(fxml);
    loader.setBuilderFactory(new JavaFXBuilderFactory());
    loader.setLocation(MainController.class.getResource(fxml));

    AnchorPane page;
    try {
        page = (AnchorPane) loader.load(in);
    } finally {
        in.close();
    }

    return (Initializable) loader.getController();
}
}

This should result in the following console appearing in the south east quadrant.

Programatically this seems to work. My southEast anchor pane shows that it has 1 child in its list if you look at it, however my UI doesnt change. I need to know how to refresh my Main controller (or do whatever I need to do) to make the change show up to the user.
I have created applications before where I create an entire new scene as the user goes through different pages but I have never really done something like this where I need to update the scene after adding a node to a pane. I have tried things like stage.sizeToScene() to try to refresh it but that hasnt worked for me.

A: You must return AnchorPane page instead of (Initializable) loader.getController(); to be added to the southEast anchorPane.
Declaring a Controller which extends another Node, results in a controller-node, which are used for creating Custom Controls.
These controls have constructors to set the Controller and the Root node. See this example
In your case, loader.getController() returns you an AnchorPane(rather ConsoleWidget), which is not loaded from the FXML, but is an instance of the ConsoleWidget class.


text:
Q: Magic Square Java program //Kevin Clement
//Week3A Magic Squares
Hey all, doing an introductory assignment to 2dimensional arrays. Below is the code I have done which is pretty much done.
My problem I get is I'm not entirely sure how to print out the array, as well as getting everything to run right with a test method. I get an error out of bounds at the line msq[order][order] = 1;
I apologize if my formatting of question is wrong, still not used to this site. Any help would be great. Thanks!
import java.util.*;

class Magic
{
  private int order;
  int msq[ ][ ];

  public Magic(int size)
  {
     if(size < 1 || size % 2 == 0)
     {
        System.out.print("Order out of range");
        order = 3;
     }
     msq = new int[order][order];
     Build();
     Display();
   }

  public void Build()
   {
     int row = 0;
     int col =0;
    msq[order][order] = 1;

     for(int k = 1; k <= order * order; k++)
     {
        msq[row][col] = k;

        if(row == 0 && col == order -1)
           row++;
        else if(row == 0)
        {
           row = order - 1;
           col++;
        }
        else if(msq[row - 1][col + 1] != 0)
           row++;
        else if(msq[row -1][col + 1] == 0)
        {
           row--;
           col++;
        }
        if(col == order - 1)
        {
           col = 0;
           row--;
        }

     }
  }
  public void Display()
  {

     for(int i = 0; i < order; i++)
     {
        for(int k = 0; k < order; k++)
        {
           System.out.println(msq[i][k] + " ");
        }
     }

  }
}

A:
I get an error out of bounds at the line msq[order][order] = 1;

msq = new int[order][order];
// ..
msq[order][order] = 1;

If array size is n, then you need to access the elements from 0 to n-1. There is no nth index. In your case there is no order, order index. It is only from 0 to order-1 and is the reason for array index out of bounds exception.

A: What is the reason for this condition in the constructor?:
if(size < 1 || size % 2 == 0)
 {
    System.out.print("Order out of range");
    order = 3;
 }

Note that whenever you use a size input that doesn't satisfy the if clause, the variable order is not initialized and defaults to 0. As a result the 2d array has size zero and throws the out of bounds error. If you are trying to use 3 as a default value, then u want to move the line:
order = 3;

before the if block.
Other things to consider:
1. make the order variable final since u don't plan on changing it. Eclipse IDE would warn you about the situation described above if you do so.
or
2. If you are going to default to 3 for the value of order initialize it as such.
private int order = 3

Also you might consider printing a message saying order defaults to three when the condition is not satisfied.

A: To print a matrix of integers in Java
for (int i = 0; i < order; i++) {
    for (int k = 0; k < order; k++) {
       System.out.printf("%6d", msq[i][k]);
    }
    System.out.println();
 }

The second part of your question is answered by Mahesh.

A: msq[order][(order] = 1;
--> here is a syntax error. You have an '('.
You get end of bound error because array start from 0 not 1  (which is a mistake every beginner makes) therefore change it to msq[order-1][order-1] = 1;
The answer above is the correct way to print out the array.


text:
Q: How to visualise the relationship between two variables based on another one in R? I have a table (based on a .csv file named "bikes"), which contains around 10,000 rows and looks like this:
rentals  season  weatherCondition
  12        1         4
  6         4         1
  21        1         4
  4         3         1
  5         3         2
  19        1         4
  13        1         3
  10        2         4
  8         2         3
  ..        ..        ..

My task is to visualise the relationship between "RENTALS" and "SEASON" based on "weatherCondition".
So far I managed to do the following:
library(tidyverse)
ggplot(data=bikes, mapping = aes(x = season, y = rentals)) +
  geom_point(aes(color = weatherCond)) +
  theme_bw()

The result is:

I assume that I'm heading in the right direction, but it's far from perfect.

*

*It doesn't visualise the data perfectly.

*I assume that providing more information regarding the correlation, the connection or the relationship between the variables would be beneficial.

How would you solve this problem?

A: Seems like you probably want grouped box plots. You can add colours or fills to this if necessary
library(tidyverse)
bikes %>%
  ggplot(aes(x = factor(season), y = rentals, group = factor(weatherCond))) +
  geom_boxplot() +
  theme_bw()

A: I would summarize the data by weather condition and season, given the weather conditions are not thousand different ones. Ideally both can be named, like "rain", "summer" etc. Either case, the following works.
Data
dat <- structure(list(rentals = c(12L, 6L, 21L, 4L, 5L, 19L, 13L, 10L,
8L), season = c(1L, 4L, 1L, 3L, 3L, 1L, 1L, 2L, 2L), weatherCondition = c(4L,
1L, 4L, 1L, 2L, 4L, 3L, 4L, 3L)), class = "data.frame", row.names = c(NA,
-9L))

res <- data.frame( aggregate( rentals ~ weatherCondition + season, dat, sum ))

# for numerical data
  weatherCondition season rentals
1                3      1      13
2                4      1      52
3                3      2       8
4                4      2      10
5                1      3       4
6                2      3       5
7                1      4       6

# for named conditions and seasons
  weatherCondition season rentals
1            rainy   fall       6
2            foggy spring       8
3            snowy spring      10
4            rainy summer       4
5            sunny summer       5
6            foggy winter      13
7            snowy winter      52

The plotting
barplot( res[,"rentals"], names=apply( res[,1:2], 1, function(x) paste0(x[1],"_",x[2]) ), las=3 )

Obviously, the labels don't make much sense here in my toy example.


text:
Q: Declaring list with variable Quick one, why does this not work? How do I get it to work?
int iSize = 10;
float fList[iSize];

The above returns:

array bound is not an integer constant before ']' token

A: The C language doesn't let us do that; it wants a fixed array dimension at compile-time. Try const int iSize = 10; to make your iSize a constant.

A: this subject is called VLA (variable length array)
many C compilers prevent's you from doing that
you can either use pointer instead of array (if you want to resize it)
or use "const" key word (or #define which is probably better regarding arduino memory limitations)


text:
Q: Rijndael encrypter: Getting empty byte[]. Not encrypting anything Good evening!
I'm trying to implement an encrypter using Rijndael algorithm and Rijndael class in c#. I tried to follow (not doing exactly the same code) the link bellow, but the problem is given a string to be encrypted I'm not getting any result. I'm no getting any error message too.
https://learn.microsoft.com/pt-br/dotnet/api/system.security.cryptography.rijndael?view=netframework-4.8
CryptDecrypt.cs
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace RijndaelAlgorithm {
    public class CryptDecrypt {
        private Byte[] iv;
        private Byte[] key;

        public CryptDecrypt(String key) {
            iv = new Byte[] {21, 10, 21, 251, 132, 76, 121, 27, 210, 81, 215, 99, 14, 235, 11, 75};
            this.key = Encoding.ASCII.GetBytes(key);
        }

        public String encryptMsg(String originalMsg) {
            byte[] encryptedMsg;

            Rijndael rijAlg = Rijndael.Create();
            rijAlg.Key = formatKey();
            rijAlg.IV = iv;

            MemoryStream msEncrypt = new MemoryStream();
            ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
            CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

            StreamWriter swEncrypt = new StreamWriter(csEncrypt);
            swEncrypt.Write(originalMsg);

            encryptedMsg = msEncrypt.ToArray();
            Console.WriteLine("encryptedMsg.Length: " + encryptedMsg.Length);

            return Convert.ToBase64String(encryptedMsg, 0, encryptedMsg.Length);
        }

        private Byte[] formatKey() {
            int len = key.Length;

            String strKey = System.Text.Encoding.UTF8.GetString(key);
            String fillKey = "";
            String strFormatedKey = "";

            Byte[] formatedKeyByte;

            if (len < 16)
                fillKey = new String('X',(16 - len));

            strFormatedKey = String.Concat(strKey, fillKey);
            formatedKeyByte = Encoding.ASCII.GetBytes(strFormatedKey);

            return formatedKeyByte;
        }
    }
}

Menu.cs
using System;

namespace RijndaelAlgorithm {
    public class Menu {
        private CryptDecrypt r;

        public Menu() {
            r = new CryptDecrypt("123654");
        }

        public void showMenu() {
            Console.WriteLine("the encrypted message is: " + r.encryptMsg("isjustatest"));
        }
    }
}

A: You seem to want to encrypt a message with your .NET application and want to get the same encrypted bytes as a particular online service that you mention in one of your comments.
Parameter
One parameter for an encryption is the initialization vector (IV). It should be random and used only once. So if two apps are correctly implemented (with different random IVs), the encrypted bytes are different.
This service returns a different result every time you press the key, even if you use the same input.
However, if you generally take the different encrypted results and decrypt them with the same key, you will get the original bytes back.
The next problem with testing with this specific service is, that they delivering always the same prefix base64 sequence 'U2FsdGVkX1'. This is not standard AES output (if you decode this base64 sequence you get 'Salted_P'). So it makes sense to use a different online service for tests.
So if two AES-256 encoding implementations are using the same parameters, we will get the same encoded result. We need for it:

*

*Key (32 bytes, not 16 for AES-256)

*IV (16 bytes)

Speaking of key length: As others mentioned in the comments, you should not simply add "X" or something similar, but use a standard cryptographic mechanism to derive a good key.
Convenient for tests are methods that convert hex strings to byte arrays and back, e.g. see StringToByteArray and ByteArrayToString methods in this cool answer:
https://stackoverflow.com/a/311179
Let's give it a try. If we take your message 'isjustatest' which has the hex string'69736a7573746174657374374', we need a 32-byte key for AES-256 and 16 bytes IV.
As others mentioned in the comments, you need to flush and close the stream (or better yet, use a 'using' statement).
Taking your code and change the key and iv assignment and output the encrypted message to the console:
rijAlg.Key = StringToByteArray("519C7C3402A943D8AF83746C1548E475319EBDA6A38046059F83B21709BD6A5B"); //32 bytes
rijAlg.IV =  StringToByteArray("0D024CF947CE4C288880D0B34D29BFA5"); // 16 bytes
...
swEncrypt.Write(originalMsg);
swEncrypt.Flush();
swEncrypt.Close();
...
Console.WriteLine("encrypted bytes: '" + ByteArrayToString(encryptedMsg) + "'");

This results in the output of '419536f27da3406625b2d07f43833aab' in the debug console.
So now we can use an online service, e.g. https://cryptii.com/pipes/aes-encryption where we can enter input data, select the encryption algorithm, supply key and IV bytes and then we get the same result as in your program, see screenshot here:

As mentioned above, don't forget to use different random IVs when using it in a real application.


text:
Q: Нужно написать код для замены пропусков с условиями Ребята, помогите. Я новичок. Надо решить такой вопрос. Есть пропуски в файле csv в столбце Year_of_Release

Name.
Platform
Year_of_Release
Genre

Madden NFL 2004
PS2.

Sports

Madden NFL 2004
XB.
2003.0.
Sports

Madden NFL 2004
GC.
2003.0.
Sports

Madden NFL 2004
GBA.
2003.0.
Sports

Как написать код так чтобы пропуск заполнялся данными если они соответствуют той же Name + Genre?
Пробовал так
data.loc[data['year_of_release'] == 555, 'year_of_release'] = data.loc[data['year_of_release'] == 555, 'name']
Но он заполняет именами, а не годом.
import pandas as pd

pth1 = '/content/General project_1.csv'
pth2 = '/datasets/games.csv'
try:
  data = pd.read_csv(pth2)
except:
  data = pd.read_csv(pth1)
else:
     print('Что-то не так')
data.columns = data.columns.str.lower()
data[['year_of_release']] = data[['year_of_release']].fillna(555)
data.loc[data['year_of_release'] == 555, 'name'] = data.loc[data['year_of_release'] == 555, 'year_of_release']

A: Можно сгруппировать по двум полям и применить методы .bfill() и .ffill() для заполнения пустот назад и вперед последними (перед пустотами) непустыми значениями из столбца.
df = pd.DataFrame({'Name': ['Madden NFL 2004', 'Madden NFL 2004', 'Madden NFL 2004', 'Madden NFL 2004','Madden NFL 2004', 'Madden NFL 2004', 'Madden NFL 2004', 'Madden NFL 2004'],
                   'Platform': ['PS2.', 'XB.', 'GC.', 'GBA.', 'PS2.', 'XB.', 'GC.', 'GBA.'],
                   'Year_of_Release': [np.nan, '2003.0.', '2003.0.', '2003.0.', np.nan, '2004.0.', '2004.0.',np.nan],
                   'Genre': ['Sports', 'Sports', 'Sports', 'Sports', 'Action', 'Action', 'Action', 'Action']})
df['Year_of_Release'] = df.groupby(['Name','Genre'])['Year_of_Release'].bfill().ffill()
print(df)

              Name Platform Year_of_Release   Genre
0  Madden NFL 2004     PS2.         2003.0.  Sports
1  Madden NFL 2004      XB.         2003.0.  Sports
2  Madden NFL 2004      GC.         2003.0.  Sports
3  Madden NFL 2004     GBA.         2003.0.  Sports
4  Madden NFL 2004     PS2.         2004.0.  Action
5  Madden NFL 2004      XB.         2004.0.  Action
6  Madden NFL 2004      GC.         2004.0.  Action
7  Madden NFL 2004     GBA.         2004.0.  Action


text:
Q: Keras Regressor giving different prediction for my input everytime I built a Keras regressor using the following code:
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

import numpy as ny
import pandas

from numpy.random import seed
seed(1)
from tensorflow import set_random_seed
set_random_seed(2)

X = ny.array([[1,2], [3,4], [5,6], [7,8], [9,10]])
sc_X=StandardScaler()
X_train = sc_X.fit_transform(X)

Y = ny.array([3, 4, 5, 6, 7])
Y=ny.reshape(Y,(-1,1))
sc_Y=StandardScaler()
Y_train = sc_Y.fit_transform(Y)

N = 5

def brain():
    #Create the brain
    br_model=Sequential()
    br_model.add(Dense(3, input_dim=2, kernel_initializer='normal',activation='relu'))
    br_model.add(Dense(2, kernel_initializer='normal',activation='relu'))
    br_model.add(Dense(1,kernel_initializer='normal'))

    #Compile the brain
    br_model.compile(loss='mean_squared_error',optimizer='adam')
    return br_model

def predict(X,sc_X,sc_Y,estimator):
    prediction = estimator.predict(sc_X.fit_transform(X))
    return sc_Y.inverse_transform(prediction)

estimator = KerasRegressor(build_fn=brain, epochs=1000, batch_size=5,verbose=0)
# print "Done"

estimator.fit(X_train,Y_train)
prediction = estimator.predict(X_train)

print predict(X,sc_X,sc_Y,estimator)

X_test = ny.array([[1.5,4.5], [7,8], [9,10]])
print predict(X_test,sc_X,sc_Y,estimator)

The issue I face is that the code is not predicting the same value (for example, it predicting 6.64 for [9,10] in the first prediction (X) and 6.49 for [9,10] in the second prediction (X_test) )
The full output is this:
[2.9929883 4.0016675 5.0103474 6.0190268 6.6434317]
[3.096634  5.422326  6.4955378]

Why do I get different values and how do I resolve them?

A: The problem lies in this line of code:
prediction = estimator.predict(sc_X.fit_transform(X))

You are fitting a new scaler every time when you predict values for new data. This is where differences come from. Try:
prediction = estimator.predict(sc_X.transform(X))

In this case, you use a pretrained scaler.


text:
Q: re-arrange mixed input dataframe I have an input dataframe that is not consistent. Here it is.
df <- structure(list(Gene = c("k141_1305_1", "k141_1406_2", "k141_1406_3",
"k141_6669_1", "k141_9215_1", "k141_13242_1", "k141_13333_5",
"k141_17708_1", "k141_19670_1", "k141_19670_6"), Phylum = c("p__Actinobacteria",
"p__Firmicutes", "p__Firmicutes", "p__Cyanobacteria", "p__Actinobacteria",
"p__Actinobacteria", "p__Firmicutes", "p__Firmicutes", "p__Actinobacteria",
"p__Proteobacteria"), Class = c("c__Actinobacteria", "c__Clostridia",
"c__Clostridia", "o__Nostocales", "c__Actinobacteria", "c__Actinobacteria",
"c__Clostridia", "c__Bacilli", "c__Actinobacteria", "c__Gammaproteobacteria"
), Order = c("o__Pseudonocardiales", "o__Clostridiales", "o__Clostridiales",
"f__Hapalosiphonaceae", "o__Pseudonocardiales", "o__Pseudonocardiales",
"o__Clostridiales", "o__Bacillales", "o__Pseudonocardiales",
"o__Pseudomonadales"), Family = c("f__Pseudonocardiaceae", "f__Lachnospiraceae",
"f__Lachnospiraceae", "g__Fischerella", "f__Pseudonocardiaceae",
"f__Pseudonocardiaceae", "f__Clostridiales Family XIII. Incertae Sedis",
"g__Exiguobacterium", "f__Pseudonocardiaceae", "f__Pseudomonadaceae"
), Genus = c("g__Pseudonocardia", "s__Lachnospiraceae bacterium 10-1",
"s__Lachnospiraceae bacterium 10-1", "s__Fischerella muscicola",
"g__Pseudonocardia", "g__Pseudonocardia", "s__[Eubacterium] infirmum",
"s__Exiguobacterium enclense", "g__Pseudonocardia", "g__Pseudomonas"
), Species = c("s__Pseudonocardia sp. Ae331_Ps2", "unknown",
"unknown", "unknown", "s__Pseudonocardia sp. Ae331_Ps2", "s__Pseudonocardia sp. Ae331_Ps2",
"unknown", "unknown", "s__Pseudonocardia ammonioxydans", "s__Pseudomonas aeruginosa group"
)), .Names = c("Gene", "Phylum", "Class", "Order", "Family",
"Genus", "Species"), row.names = c(3212L, 3853L, 3854L, 17967L,
24006L, 34126L, 34325L, 43722L, 49328L, 49332L), class = "data.frame")

The dataframe looks like this
 Gene            Phylum             Class                Order                Family
3212   k141_1305_1 p__Actinobacteria c__Actinobacteria o__Pseudonocardiales f__Pseudonocardiaceae
3853   k141_1406_2     p__Firmicutes     c__Clostridia     o__Clostridiales    f__Lachnospiraceae
3854   k141_1406_3     p__Firmicutes     c__Clostridia     o__Clostridiales    f__Lachnospiraceae
17967  k141_6669_1  p__Cyanobacteria     o__Nostocales f__Hapalosiphonaceae        g__Fischerella
24006  k141_9215_1 p__Actinobacteria c__Actinobacteria o__Pseudonocardiales f__Pseudonocardiaceae
34126 k141_13242_1 p__Actinobacteria c__Actinobacteria o__Pseudonocardiales f__Pseudonocardiaceae
                                  Genus                         Species
3212                  g__Pseudonocardia s__Pseudonocardia sp. Ae331_Ps2
3853  s__Lachnospiraceae bacterium 10-1                         unknown
3854  s__Lachnospiraceae bacterium 10-1                         unknown
17967          s__Fischerella muscicola                         unknown
24006                 g__Pseudonocardia s__Pseudonocardia sp. Ae331_Ps2
34126                 g__Pseudonocardia s__Pseudonocardia sp. Ae331_Ps2

As you can see the dataframe is not structured as it should be. The dataframe was generated this way so i don´t have control over it.
The problem is that microorganisms should be annotated using different ranks (from Pylum to species, one per column). As you can see in some cases there are missing ranks , for example Gene 17967 (4th row) does not have a class rank (no "c__" annotation). What happens is that in the column class this particular taxa has the order ("o__Nostocales") instead of an empty "c__" annotation.
Same happens for others, for example 2nd row does not have genus "g__" annotation so the species is put in the genus column.
The first and two last rows are an example of how it should be.
Is there a chance to correct those rows in a quick way so that each colum has it corresponding taxonomic rank. ???
For example if i take the second row the correct output should be:
Gene            Phylum             Class                Order                Family
     3853   k141_1406_2     p__Firmicutes     c__Clostridia     o__Clostridiales    f__Lachnospiraceae
          Genus    Species
    3853  g__ s__Lachnospiraceae bacterium 10-1

Alternatevely it could be an unknown g__unknown tag.
3853   k141_1406_2     p__Firmicutes     c__Clostridia     o__Clostridiales    f__Lachnospiraceae
 3853  g__unknown s__Lachnospiraceae bacterium 10-1

A: Try using this code:
 adds=function(x){
   nam=c("k","p","c","o","f","g","s")
   l=which(is.na(match(nam,substr(x,1,1))));
   if(length(l)>0)`names<-`(head(unlist(append(x,paste0(nam[l],"__"),l-1)),-1),names(x))
   else x
 }

 data.frame(t(apply(df,1,adds)))

This should be able to append the desired name to the row. hence giving the expected result. If this helps, please let us know. Thank you.

A: First we need to recognize that the current columns are meaningless (apart from their names), and that the prefixes carry a meaning, that we'll map to the long column names.
so we build a lookup table and then use tidyr and dplyr
library(dplyr)
library(tidyr)
lkp <- data.frame(key1  = c("Phylum","Class","Order","Family","Genus","Species"),
                  key2 = c("p","c","o","f","g","s"),
                  stringsAsFactors = F)

df %>% gather(key,val,-Gene)          %>%  # put everything in a single column
  filter(val != "unknown")            %>%  # get rid of the unknowns, they don't contain info and have irregular format (no underscore)
  separate(val,c("key2","val2"),sep="__",remove = F) %>% # separate the values, keeping the original
  left_join(lkp)                      %>%  # add info from lookup table
  select(Gene,val,key1)               %>%  # keep only relevant columns
  spread (key1,val, fill = "unknown") %>%  # set back in wide format
  as.data.frame                            # convert from tibble to data.frame

# Gene                  Class                                       Family              Genus                Order            Phylum                           Species
# 1   k141_1305_1      c__Actinobacteria                        f__Pseudonocardiaceae  g__Pseudonocardia o__Pseudonocardiales p__Actinobacteria   s__Pseudonocardia sp. Ae331_Ps2
# 2  k141_13242_1      c__Actinobacteria                        f__Pseudonocardiaceae  g__Pseudonocardia o__Pseudonocardiales p__Actinobacteria   s__Pseudonocardia sp. Ae331_Ps2
# 3  k141_13333_5          c__Clostridia f__Clostridiales Family XIII. Incertae Sedis            unknown     o__Clostridiales     p__Firmicutes         s__[Eubacterium] infirmum
# 4   k141_1406_2          c__Clostridia                           f__Lachnospiraceae            unknown     o__Clostridiales     p__Firmicutes s__Lachnospiraceae bacterium 10-1
# 5   k141_1406_3          c__Clostridia                           f__Lachnospiraceae            unknown     o__Clostridiales     p__Firmicutes s__Lachnospiraceae bacterium 10-1
# 6  k141_17708_1             c__Bacilli                                      unknown g__Exiguobacterium        o__Bacillales     p__Firmicutes       s__Exiguobacterium enclense
# 7  k141_19670_1      c__Actinobacteria                        f__Pseudonocardiaceae  g__Pseudonocardia o__Pseudonocardiales p__Actinobacteria   s__Pseudonocardia ammonioxydans
# 8  k141_19670_6 c__Gammaproteobacteria                          f__Pseudomonadaceae     g__Pseudomonas   o__Pseudomonadales p__Proteobacteria   s__Pseudomonas aeruginosa group
# 9   k141_6669_1                unknown                         f__Hapalosiphonaceae     g__Fischerella        o__Nostocales  p__Cyanobacteria          s__Fischerella muscicola
# 10  k141_9215_1      c__Actinobacteria                        f__Pseudonocardiaceae  g__Pseudonocardia o__Pseudonocardiales p__Actinobacteria   s__Pseudonocardia sp. Ae331_Ps2

Replace val by val2 in the 2 last instances if you want to get rid of the prefixes by the same token.
df %>% gather(key,val,-Gene) %>%
  filter(val != "unknown") %>%
  separate(val,c("key2","val2"),sep="__",remove = F) %>%
  left_join(lkp) %>%
  select(Gene,val2,key1) %>%
  spread (key1,val2,fill="unknown") %>%
  as.data.frame


text:
Q: Number of views allowed to store in database Is there a limit to the number of views that I can create and store in a database or specifically Firebird? So far, I only managed to find the maximum number of tables that can be stored in a database.

A: Firebird considers views a form of tables, and as such the limit on the number of tables includes views (and system tables, and virtual tables like the monitoring tables).
This limit is 32768 (see https://www.firebirdsql.org/en/firebird-technical-specifications/).


text:
Q: How to move the views up while EditText grows with text AND how to retain a view or layout just on top of soft keyboard in fragment? I have a couple of EditTexts and a Camera and Camcorder ImageViews.
1). I want Camera and Camcorder to be just on top of the soft keyboard when it opened up when EditTexts takes the focus.
2). Also, with this layout when the text that user enters in editTextUserMessage view grows, view grows towards bottom under the keyboard. Instead I want it to grow up so that the spinner and the other EditText can move up. While achieving this, I want 1) to happen…that is I want imageCamera and imageVideo ImageViews to sit just on top of Keyboard.
I tried with different softInputModes in activity and in fragment..but I did not see any improvement in anything I want.
While Move layout up when soft keyboard is shown looks to be promising, keeping the views on top of keyboard happens only when the focus changes so this code can not keep the Cam and Camcorder images on top of Keyboard always.
All soultions just moves the entire layout up which is not I want. Also, this is not an activity but a fragment.
Can you help me ?
Below is the layout of my fragment:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearRootInScroll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:orientation="vertical"
        android:paddingBottom="@dimen/padding_bottom">

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:orientation="vertical">

            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="5dp"
                android:orientation="horizontal">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="@string/prefix_type"
                    android:textAppearance="?android:attr/textAppearanceMedium" />

                <Spinner
                    android:id="@+id/spinnerTypes"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:dropDownWidth="wrap_content"
                    android:padding="8dp" />

            </LinearLayout>

            <com.test.shield.views.SearchFriendCompletionView
                android:id="@+id/editTextAddFriend"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/underline_edittext"
                android:gravity="left|center"
                android:hint="@string/hint_add_friend"
                android:imeOptions="actionDone"
                android:minHeight="58dp"
                android:paddingLeft="5dp"
                android:paddingRight="5dp"
                android:scrollbars="vertical"
                android:textColorHint="@color/LIGHT_BLACK" />

            <EditText
                android:id="@+id/editTextUserMessage"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:background="@drawable/underline_edittext"
                android:gravity="left"
                android:hint="@string/hint_message"
                android:inputType="textCapSentences|textMultiLine"
                android:isScrollContainer="true"
                android:maxLength="140"
                android:minHeight="120dp"
                android:padding="5dp"
                android:scrollbars="vertical"
                android:textColorHint="@color/LIGHT_BLACK" />

            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/linearCamAndVideo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="start"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/imageCamera"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_marginRight="5dp"
                    android:background="?attr/selectableItemBackground"
                    android:padding="10dp"
                    android:scaleType="center"
                    android:src="@drawable/ic_photo_camera_black_24dp" />

                <ImageView
                    android:id="@+id/imageVideo"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:background="?attr/selectableItemBackground"
                    android:padding="10dp"
                    android:scaleType="center"
                    android:src="@drawable/ic_videocam_black_24dp" />

            </LinearLayout>

            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="15dp"
                android:gravity="start"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/textTime"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="@color/black" />

            </LinearLayout>
        </LinearLayout>

        <ImageView
            android:id="@+id/imageMap"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_gravity="center"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:padding="7dp"
            android:paddingBottom="5dp"
            android:scaleType="centerCrop" />
    </LinearLayout>
</ScrollView>

A: Well, I had to put enough efforts to achieve this.
For 2) that letting EditText grow upwards so that cursor is visible fix was adding this line in onCreateView() of my Fragment where my above layout is inflated :
    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
I tried applying the same bit in manifest for activity but it did not work.
For 1) that to keep the LinearLayout that has Camera and Camcorder on top of Keyboard when it is visible. Below is the solution that worked perfectly. See the comments within code to understand it:
/*
- LinearCamAndVideo is the one I want to keep on top of soft Keyboard when it is visible.
Without this code, mLinearCamAndVideo will be obscured under Keyboard.

- int mInitialLayoutHeight holds no of pixels that layout is growing when it is changed while user enters text. It grows
when user enters key to next line. This globalListener will be called for every change that happens in Layout.

- mRootLayout is root layout in above layout.

- mLinearRootInScroll is root in Scrollview */
mOnGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        if (!isRemoving()) {
            Rect r = new Rect();
            mRootLayout.getWindowVisibleDisplayFrame(r);

            int screenHeight = mRootLayout.getRootView().getHeight();

            //top of the screen starts with 0, bottom being max number of pixels which is height of screen too.
            int heightDifference = screenHeight - (r.bottom - r.top);

            mKeyboardVisible = heightDifference > (screenHeight / 3);
            if (mInitialLayoutHeight == 0) {
                mInitialLayoutHeight = mLinearCamAndVideo.getBottom();
            }

            mLayoutHeightGrown = mLinearCamAndVideo.getBottom() - mInitialLayoutHeight;

            if (mKeyboardVisible) {
                int layoutBottom = mLinearCamAndVideo.getBottom();
                int padding = heightDifference - layoutBottom + mLayoutHeightGrown;

                /*Setting padding to the parent layout in ScrollView is key as it provides
                enough extra space so that scrollTo() can move up the mLinearCamAndVideo layout. You do this only when KB is visible.*/
                mLinearRootInScroll.setPadding(0, 0, 0, padding + Math.round(Converter.convertDpToPixels(getContext(), 30)));
                mScrollView.scrollTo(0, layoutBottom);
            } else {
                   // Reset the padding when Keyboard is no more visible..
                   mLinearRootInScroll.setPadding(0, 0, 0, 0);
                mScrollView.scrollTo(0, r.top);
            }
        }

    }
};
mRootLayout.getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);


text:
Q: Firebase dependency conflict Found com.google.firebase:firebase-core:.11.0.4, but version 11.0.4 is needed The problem is I need Firebase version 11.0.4 but I have 11.0.4 ...
This is my build script
ext {
    supportLibraryVersion = '25.3.1'
    playServicesVersion = '11.0.4'
    firebaseVersion = '11.0.4'
}

dependencies {
compile project(":core")
compile fileTree(dir: 'libs', include: ['*.jar'])

// support libraries
compile "com.android.support:support-v4:$supportLibraryVersion"
compile "com.android.support:appcompat-v7:$supportLibraryVersion"
compile "com.android.support:cardview-v7:$supportLibraryVersion"
compile "com.android.support:recyclerview-v7:$supportLibraryVersion"

//play services
compile "com.google.android.gms:play-services-maps:$playServicesVersion"
compile "com.google.android.gms:play-services-location:$playServicesVersion"
compile "com.google.android.gms:play-services-auth:$playServicesVersion"
compile "com.google.android.gms:play-services-plus:$playServicesVersion"

compile "com.google.firebase:firebase-core:.$firebaseVersion"
compile "com.google.firebase:firebase-messaging:$firebaseVersion"

.....
}
apply plugin: 'com.google.gms.google-services'

Found com.google.firebase:firebase-core:.11.0.4, but version 11.0.4 is needed for the google-services plugin.
:app:processDebugGoogleServices FAILED
:app:processDebugGoogleServices (Thread[Daemon worker Thread 7,5,main]) completed. Took 0.001 secs.
FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':app:processDebugGoogleServices'.

Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 11.0.4.

*Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output.
My google play service version is 43, sugestions?

A: compile "com.google.firebase:firebase-core:$firebaseVersion"

/* note: . is removed in above line */


text:
Q: Apps Srcipt indexOf() not working properly I am reading the body text of emails. You can check how the body appears in the photo attached.
I want to get the following substring: 'Current status- ROB2ReOnb". I am noticing that when the text I am looking for, is not on the same row, the indexOf gives me "-1". However, when is on the same row I can get a positive value for the indexOf.
My code is the following:
current_status = body.substring(body.indexOf("Current status -"),body.indexOf("Active with App"))
Do you know what can I be doing wrong? I am trying to spot the error for so long. Any tip/clue is more than welcome.

A: I got the answer with @Nick Parsons comment:
help = HtmlService.createHtmlOutput('Active\nwith');
current_status_aux = body.substring(body.indexOf("Current status -"),body.indexOf(help))


text:
Q: Alfresco CMIS unauthorized im doing an integration of Liferay and alfresco, my goal is to use alfresco 5.2 to store content created in Liferay DXP.
To do that ,i have added this line to portal-ext.porperties
dl.store.impl=com.liferay.portal.store.cmis.CMISStore

and added the config file com.liferay.portal.store.cmis.configuration.CMISStoreConfiguration.cfg with this content:
repositoryUrl=http://localhost:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom

credentialsUsername=admin credentialsPassword=password

systemRootDir=Liferay

Everything worked fine but suddenly im getting this error while rebooting liferay:
21:19:37,536 ERROR [localhost-startStop-1][com_liferay_portal_store_cmis:97] [com.liferay.portal.store.cmis.CMISStore(1549)] The activate method has thrown an exception
org.apache.chemistry.opencmis.commons.exceptions.CmisUnauthorizedException: Unauthorized
    at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.convertStatusCode(AbstractAtomPubService.java:477)
    at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.read(AbstractAtomPubService.java:645)
    at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.getRepositoriesInternal(AbstractAtomPubService.java:808)
    at org.apache.chemistry.opencmis.client.bindings.spi.atompub.RepositoryServiceImpl.getRepositoryInfos(RepositoryServiceImpl.java:65)
    at org.apache.chemistry.opencmis.client.bindings.impl.RepositoryServiceImpl.getRepositoryInfos(RepositoryServiceImpl.java:90)
    at org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl.getRepositories(SessionFactoryImpl.java:135)
    at org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl.getRepositories(SessionFactoryImpl.java:112)
    at com.liferay.portal.store.cmis.CMISStore.createSession(CMISStore.java:591)
    at com.liferay.portal.store.cmis.CMISStore.activate(CMISStore.java:475)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.felix.scr.impl.inject.BaseMethod.invokeMethod(BaseMethod.java:224)
    at org.apache.felix.scr.impl.inject.BaseMethod.access$500(BaseMethod.java:39)
    at org.apache.felix.scr.impl.inject.BaseMethod$Resolved.invoke(BaseMethod.java:617)
    at org.apache.felix.scr.impl.inject.BaseMethod.invoke(BaseMethod.java:501)
    at org.apache.felix.scr.impl.inject.ActivateMethod.invoke(ActivateMethod.java:302)
    at org.apache.felix.scr.impl.inject.ActivateMethod.invoke(ActivateMethod.java:294)
    at org.apache.felix.scr.impl.manager.SingleComponentManager.createImplementationObject(SingleComponentManager.java:297)
    at org.apache.felix.scr.impl.manager.SingleComponentManager.createComponent(SingleComponentManager.java:108)
    at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManager.java:906)
    at org.apache.felix.scr.impl.manager.SingleComponentManager.getServiceInternal(SingleComponentManager.java:879)
    at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManager.java:823)
    at org.eclipse.osgi.internal.serviceregistry.ServiceFactoryUse$1.run(ServiceFactoryUse.java:212)
    at java.security.AccessController.doPrivileged(Native Method)

What does  unauthorized mean in this context?


text:
Q: ASP.NET Core SQL Linq using list of strings I have a list of strings like this
list = {a,b,c}

I would like to compare it in the database but I'm not sure how to go about doing that. This is my linq query:
var initialData = (from item in dbContext.DocumentCategories
    join df in dbContext.DocumentFields
    on item.Id equals df.DocumentCategoriesId
    join dfs in dbContext.DocumentFieldsStore
    on df.Id equals dfs.DocumentFieldsId
    select new SearchDocumentsListViewModel
    {
        CategoryId = item.Id,
        DocumentId = dfs.DocumentsId,
        FieldId = df.Id,
        Data = dfs.Data
    })
    .ToList();

initialData = initialData
    .Where(u => u.Data.Contains(list))
    .ToList();

Currently its showing me this error:

cannot convert from 'System.Collections.Generic.List' to
  'char'

Not sure what that means

A: There is a Where statement at the end that has the Contains expression backwards.
.Where(u => u.Data.Contains(list)

This line of code explained:
u.Data is being treated as a char[] and a char cannot contain a list.
This line of code needs to have the contains flipped around to:
.Where(u => list.Contains(u.Data)


text:
Q: xpath with multiple predicates equivalence I was told that the following are not the same:
a[1][@attr="foo"]
a[@attr="foo"][1]

Can someone explain why that is the case?

A: Think of XPath expressions as defining a result set1 - a set of nodes that fulfil all the requirements stated in the XPath expression. The predicates of XPath expressions (the parts inside []) either have no effect on the result set or they incrementally narrow it.
Put another way, in the following expression:
//xyz[@abc="yes"]

[@abc="yes"] reduces the result set defined to the left of it, by //xyz.
Note that, as Michael Kay has suggested, all that is said below only applies to XPath expressions with at least one positional predicate. Positional predicates are either a number: [1] or evaluate to a number, or contain position() or last().
If no positional predicate is present, the order of predicates in XPath expressions is not significant.

Consider the following simple input document:
<root>

</root>

As you can see, a[@attr = 'foo'] is not the first child element of root. If we apply
//a[1]

to this document, this will of course result in

Now, crucially, if we add another predicate to the expression, like so:
//a[1][@attr="foo"]

Then, [@attr="foo"] can only influence the result set defined by //a[1] already. In this result set, there is no a[@attr="foo"] - and the final result is empty.
On the other hand, if we start out with
//a[@attr="foo"]

the result will be

-----------------------

and in this case, if we add a second predicate:
//a[@attr="foo"][1]

the second predicate [1] can narrow down the result set of //a[@attr="foo"] to only contain the first of those nodes.

If you know XSLT, you might find an XSLT (and XPath 2.0) proof of this helpful:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />

    <xsl:template match="/">
      <result1>
          <xsl:copy-of select="//a[1][@attr='foo']"/>
      </result1>
      <result2>
          <xsl:copy-of select="//a[@attr='foo'][1]"/>
      </result2>
    </xsl:template>

</xsl:transform>

And the result will be
<result1/>
<result2>

</result2>

1 Technically speaking, only XPath 1.0 calls this result a node-set. In XPath 2.0, all sets have become true sequences of nodes.


text:
Q: when use auth('api')->user() in class `AppServiceProvider` return null when use auth('api')->user() in class AppServiceProvider return null
this code config/auth
'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],
`
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

`
this is code function boot in class AppServiceProvider
view()->composer('dashboard::layouts.*', function ($view) {
            dd(auth('api')->user());
            $view->with('user', auth('api')->user());
        });

A: you use session or token in your app? if you use token you should include token in your header request so if token did not send you get null user because the user is not authenticated, but if you use session so just use Auth::user() to get authenticated user

A: send token in header most time is possible with Bearer prefix like:Bearer token_value, and if you use nginx add token value to Authorization parameter in header, dont forget add client middleware to your route.
for get authenticated user info you can do with this:
 $token = $request->bearerToken();
 $tokenId = (new Parser())->parse($token)->getHeader('jti');
    $client = Token::find($tokenId);
    return $client['user_id'];


text:
Q: Android apk upload fails with error 'The apk must be signed with the same certificates as the previous one' I know this question has been asked before, but I am pretty sure I am using the same keystore.
I stored the keystore I used to sign the first version of my app and then used the same to create the second release.
jarsigner -verbose -digestalg SHA1 -sigalg MD5withRSA -keystore app_signing.keystore target/HNewsDroid-2.0.apk release
zipalign -v 4 target/HNewsDroid-2.0.apk target/HNewsDroid-2.0-release.apk  I

Even though I have no access to my previous Linux installation from where I generated the app_signing.keystore using keytool, I believe only the keystore file needs to be the same while signing the jar (even though my private ssh key has changed on my new Linux installation).
In case it helps, I am using maven android plugin to generate the jars/apks.
Could someone point out what I am doing wrong?
EDIT:
I have no idea why the certificate I signed my app with is not working. I changed my package name and uploaded the application as a new application, finally.

A: keytool -list -v -keystore app_signing.keystore - get the info about the certificate and check if its ok

A: You are correct in the assumption that only the keystore needs to be the same - the private SSH key on your machine doesn't matter.
You can sign the app on as many different machines as you would like (assuming you are using the same keystore).

A: It turned out that I had incorrectly generated the private key with keytool. It had two names and that was causing the problem. I regenerated the certificate with only one name and the problem went away.


text:
Q: BrowserEngine: 29 - UI element not found in Silk Performer I have recorded my application using internet explorer in Silk performer using BDLT approach as this protocol by default it will consider for recording IE only, but my application is comapatable with Chrome. While replaying the script using chrome getting below error.
Error   VUser-Profile1_1    localhost   65  00:01:19    BrowserClick    BrowserEngine: 29 - UI element not found
The chrome window is getting opened and application URL is also loading. But it is not moving further and facing that issue.

A: That error could be related to the synchronization mode used to recognize when has an action finished and the next one can be performed.
You can try setting sync mode to HTML instead of AJAX around the functions where the error occur:
BrowserSetOption(BROWSER_OPT_SYNC_MODE, SYNC_MODE_HTML);
/*The actions where the error occur*/
BrowserSetOption(BROWSER_OPT_SYNC_MODE, SYNC_MODE_AJAX);


text:
Q: Spring mvc with thymeleaf How to use thymeleaf to add an object of String without any pojos?
@RequestMapping("/hello")
public String s(Model model){
    model.add("e","model test");
    return "view1";
}

what to do next to get the data from the view ?!

A: These are very well explained in Thymeleaf docs, have you gone through them?
<p th:text="${e}">1</p>


text:
Q: Auto-py-to-exe automatically runs cscript.exe I am using VBScript in my code to convert each sheet of a given excel file into a CSV file.
I have tried other methods such as using pandas but they are comparatively slow and the vb script method performs pretty well when I run the script.
The only problem I am facing is that when I use auto-py-to-exe to convert my script into an exe for a client, the VBScript is executed automatically when auto-py-to-exe is compiling the code.
I have searched a lot but couldn't find anything similar to my problem.
Any help in this regard would be much appreciated. Thanks!
The snippet where I call cscript is given below:
    if not os.path.exists('./Temp'):
        os.mkdir('./Temp')
    s = time.time()
    temp = './Temp'
    call(['cscript.exe', os.path.join(os.getcwd(),'ExcelToCsv.vbs'), filename, temp])
    e = time.time()
    print("Time taken to convert excel sheets to CSV files: ", e - s)

A: Well, maybe this will sound stupid, but have you tried replacing call function within os.system function? I have done something like that many times and it worked perfectly. This is the first time i see this error.


text:
Q: File-based services and concurrency issues I am designing the architecture for a set of WCF services.  Due to the nature of the deployment of these services (remotely deployed onto a number of unmanageable systems on client sites, therefore we cannot afford the administrative overhead of database servers), the data store has to be file based (we are leaning quite heavily toward XML for the file format).
Once again, the nature of the services means that there is a potential for concurrency issues within individual files, and I am trying to come up with a system that will behave correctly in all instances and avoid attempting to read data when there is a write operation pending.
My current thinking is taking one of two possible routes.

*

*locking files
This would operate in the following way.
All file operations will have a locking mechanism.  Reads would check to ensure the required file is not currently locked before requesting data.  If the file is locked, the service should sleep for a random number of milliseconds (within an as-yet undetermined range).  Write operations would set the lock, commit the data and then unlock the file.

*additional program in the background to provide data to the services
This version would have a secondary application in the background, exposing various public static methods, callable by the services.  The background app would be solely responsible for maintaining an in-memory representation of the data, providing the data to the services, and keeping the file copies in synch with the in memory objects.  In this respect, it would behave as if it were a transactionalised database server.
Of the two (or possibly other) methods of realising the goal of creating these kinds of services, which option would provide the greatest performance with least chance of concurrency conflicts?  The simplicity of the design of option 1 means that I'm more in favour of that one, but I am worried that performance may suffer as a result of the "sleep" operations.

A: I know you say you don't want administrative overhead for database servers but why don't you just use something like SQL Express.  All you need is the runtime installed.  Same thing would go for say using an Access database file.  just needs a runtime.  Then you can get around these other issues and you can just make sure you have the runtime as part of the required components of your installer.  This I think would make your life much easier and you would not have the overhead of a real db server.
Another option would be something say like SQL Lite.  It only needs a couple dll's deployed with your app.  No overhead at all but benefit of having a db over having to manage all the file access yourself.
SQL Lite, MySQL, and even SQL Express are small and lightweight enough that they are used as data stores on hand held devices so I don't see why something like that would not work here.

A: I'll turn John Saunders' comment into an answer:
It is quite likely that both options will turn out to require more administrative overhead than a simple installation of Sql Express.
You can profit from desktop-aimed features like quiet installation and attached db files.
Regarding 1), what will happen if there is a crash when files are locked?

A: Check out SQL Server Compact edition. It does not require any running service and supports XCopy deployment.

A: A database is an abstraction over a set of files. They're asking you to reinvent the wheel, at a fraction of the cost. I think you really need to push back on this and explain the business impact of trying to write your own database - it will take longer, cost more, and be much less reliable.

A: If you really have to write directly to the file system, I'd recommend that you have your service objects talk to an object hosted on the service that maintains authority for the file, rather than having multiple objects directly access it.  Then, you can lock that object appropriately to maintain consistency.


text:
Q: Records are getting re-delivered with manual ack ( AckMode.MANUAL_IMMEDIATE) Is it possible that record will redeliver again once it is properly ack?  Sometime we are getting same record multiple time.
Attached image https://i.stack.imgur.com/9yC1M.jpg. Can see in image, multiple service receive same record at different time
I can't able to reproduce this in local machine.
@KafkaListener(topics = "${kafka.sample.topic}", containerFactory = "kafkaListenerContainerFactory")
    public void listen(ConsumerRecord<String, String> record, Acknowledgment ack) {

        //Ack record
        sendAck(ack);

    }

private void sendAck(Acknowledgment ack) {
        try {
            ack.acknowledge();
        } catch (Exception e) {
            logger.error("Exception occurred while sending ack");
            logger.error(ExceptionUtils.getStackTrace(e));
        }
    }

@Bean
KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {

    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();

    factory.setConsumerFactory(consumerFactory());
    factory.setConcurrency(Integer.parseInt(10));
    factory.getContainerProperties().setAckMode(AckMode.MANUAL_IMMEDIATE);

    return factory;
}

public Map<String, Object> consumerConfigs() {

        Map<String, Object> consumerPropsMap = new HashMap<>();

        consumerPropsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        consumerPropsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, autoCommitConfig);
        consumerPropsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, autoCommitConfigIntervalMs);
        consumerPropsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, sessionTimeout);
        consumerPropsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        consumerPropsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        consumerPropsMap.put(ConsumerConfig.GROUP_ID_CONFIG, groupIdConfig);
        consumerPropsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        consumerPropsMap.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed");
        consumerPropsMap.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 1);

        consumerPropsMap.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, "org.apache.kafka.clients.consumer.CooperativeStickyAssignor");

        if(StringUtils.isNotBlank(heartbeatIntervalMs)){
            consumerPropsMap.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, heartbeatIntervalMs);
         }

        return consumerPropsMap;
}


text:
Q: Catchable fatal error: Object of class PDOStatement could not be converted to string in main.loader.php on line 111 The code I'm doing maintenance is a school system, I'm having problems when it arrives in the part of starting the enrollment, it returns an object error, that is in line 111, in my code this is giving error in line 111 in
$qryMatricula = $conn->query($sqlMatricula);
echo $qryMatricula;

What could I be? How can I solve this?
main.loader.php
<?php

                $sqlMatricula = "SELECT M.Situacao FROM {$pfx}Matricula M
                                    INNER JOIN {$pfx}Curso C ON (C.CursoID = M.CursoID)
                    WHERE AlunoID = $alunoid AND C.PeriodoLetID = $periodoid";

                $qryMatricula = $conn->query($sqlMatricula);

                echo $qryMatricula;
                $situacaoMatricula = 0;
                if ($m = $qryMatricula->fetchObject())
                    $situacaoMatricula = $m->Situacao;

A: I guess you are using PDO::query() which returns an instance of a PDOStatement object and could not be converted to a string with echo.
Try the following:
$sth = $conn->query($sqlMatricula);
$result = $sth->fetchAll();
var_dump($result);


text:
Q: Excel reading gives java.lang.StringIndexOutOfBoundsException I have tried to read a excel file using jxl. It is giving StringIndexOutOfBoundsException.I don't know why I'm getting that for this code.
public class TestExcelReader {

    public static void main(String args[]) throws BiffException, IOException{
        File file=new File("D:\\TestExcel.xls");
        Workbook workbook=Workbook.getWorkbook(file);  \\Line number 14

        Sheet sheet=workbook.getSheet(0);
        System.out.println("No of rows is "+sheet.getRows());
    }

}

My exception:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 68
    at java.lang.String.checkBounds(Unknown Source)
    at java.lang.String.<init>(Unknown Source)
    at jxl.biff.StringHelper.getString(StringHelper.java:164)
    at jxl.read.biff.WriteAccessRecord.<init>(WriteAccessRecord.java:56)
    at jxl.read.biff.WorkbookParser.parse(WorkbookParser.java:821)
    at jxl.Workbook.getWorkbook(Workbook.java:237)
    at jxl.Workbook.getWorkbook(Workbook.java:198)
    at ext.gt.test.TestExcelReader.main(TestExcelReader.java:14)

A: The problem is because you are using an Excel95 file, and unfortunately it seems that is not supported (only files after Excel97 are).
Take a look here
http://jexcelapi.sourceforge.net/resources/javadocs/2_6_10/docs/jxl/Workbook.html#getWorkbook(java.io.InputStream)
and here
http://www.java-forum.org/allgemeine-java-themen/140138-java-tabelle-auslesen-xls-excel-fehler.html


text:
Q: React: animationOut not showing using Animated.css I have an example of a toggle that hide/display content.
I used https://www.npmjs.com/package/react-animated-css and it worked perfectly when displaying the content, meaning that after showing the content the animation is playing.
Now that I press the toggle button, the content instantly vanishes without animation.
I checked in the console and the class for the animationOut is working, but it seems that the content closes before the animation have the time to play, so it's hidden.
How to fix this issue ?
The working code : https://stackblitz.com/edit/react-sorgz5?file=src/App.js
import React, { Component } from "react";
import ContentComponent from "./content.js";
import { Animated } from "react-animated-css";

export default class toggleComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      isShowBody: false
    };
  }

  handleClick = event => {
    this.setState({ isShowBody: !this.state.isShowBody });
  };

  checkbox = () => {
    return (

            <input
              type="checkbox"
              name="select"
              onClick={this.handleClick.bind(this)}
            />

    );
  };

  render() {
    return (

        {this.checkbox()}

        <Animated
          animationIn="bounceInLeft"
          animationOut="fadeOut"
          isVisible={this.state.isShowBody}
        >

{this.state.isShowBody && <ContentComponent />}

        </Animated>

    );
  }
}

A: Solved. I needed to remove this.state.isShowBody in
so the condition of the visibility is controller by isVisible.
<Animated
          animationIn="bounceInLeft"
          animationOut="fadeOut"
          isVisible={this.state.isShowBody}
        >

{<ContentComponent />}

        </Animated>


text:
Q: "The WS-Management service cannot process the request. The service is configured to not accept any remote shell requests" when managing server I can't do anything in server manager. I have tried enabling "Allow Remote Shell Access" in GPO. This is ridiculous how this just doesn't work for software costing OVER A THOUSAND DOLLARS!
UPDATE: Microsoft just doesn't know what the hell they're doing, they make an operating system for "datacenters" and yet their bulls****y OSes come broken. Now, if their OS was working, when the value found at "WSMAN:\localhost\Shell\AllowRemoteShellAccess" says "True", you'd think that it really is true, but it just isn't. Microsoft is a billion dollar company built on broken software and utterly horrible customer support.

A: Have you tried installing the required features from a different server's Server Manager by adding this server as a remote server ?
This is how I worked around the issue.  It seemed the local server manager on the specific server had issues.

A: I tried all the recommended stuff - Allow Remote Shell Access; gpupdate /force in an admin window; WM service restart.  All to no avail.  BUT simple Windows restart fixed it. OMG!


text:
Q: css for xpath related to nth sibling under header element I'm trying to get css for below xpath
//*[@id="key-facts-heading"]/h4[1]/text()[2]

but couldn't understand what to do after #key-facts-heading
I don't understand why chrome console doesn't have css selector but it has xpath, is there another way to get css from chrome console directly ?
Note:
Earlier I was relying on https://cssify.appspot.com/ but this website is not more working with error "

Access to XMLHttpRequest ...from origin 'https://cssify.appspot.com'
  has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
  header is present on the requested resource.

"

A: Updated :
To get 2,43,078.87 Cr as the output,
// Target the element
WebElement element = driver.findElement(By.cssSelector("#key-facts-heading > h4:nth-of-type(1) > span"));
// Get the following text using a JS Executor
String text = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].nextSibling.textContent.trim()", element);
System.out.println(text);

Note : 2,43,078.87 Cr is within <h4> and not <span>


text:
Q: Getting TypeError when makemigration to a model when using Django I am currently learning Python from the book "Python Crash Course" by Eric Matthes. I am trying one of the assignments and am currently stuck. Can't figure out why this error appears.
from django.db import models

# Create your models here.
class Pizza(models.Model):
    """List of pizzas"""
    name = models.CharField(max_length=50)

    def __str__(self):
        """Return a string representation of the model"""
        return self.name

class Topping(models.Model):
    """Toppings"""
    pizza = models.ForeignKey(Pizza)
    name = models.CharField(max_length=50)

    def __str__(self):
        """Return a string representation of the model"""
        return self.name

Getting the error when I add the model Topping to the code.
    Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\Samuel Tee\Desktop\pizzeria\pp_env\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "C:\Users\Samuel Tee\Desktop\pizzeria\pp_env\lib\site-packages\django\core\management\__init__.py", line 347, in execute
    django.setup()
  File "C:\Users\Samuel Tee\Desktop\pizzeria\pp_env\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Samuel Tee\Desktop\pizzeria\pp_env\lib\site-packages\django\apps\registry.py", line 112, in populate
    app_config.import_models()
  File "C:\Users\Samuel Tee\Desktop\pizzeria\pp_env\lib\site-packages\django\apps\config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\Samuel Tee\Desktop\pizzeria\pizzas\models.py", line 12, in <module>
    class Topping(models.Model):
  File "C:\Users\Samuel Tee\Desktop\pizzeria\pizzas\models.py", line 14, in Topping
    pizza = models.ForeignKey(Pizza)
TypeError: __init__() missing 1 required positional argument: 'on_delete'

A: Add on_delete to pizza ForeignKey.
class Topping(models.Model):
    """Toppings"""
    pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE)

on_delete is required in Django 2 - https://docs.djangoproject.com/en/2.0/releases/2.0/#features-removed-in-2-0:

The on_delete argument for ForeignKey and OneToOneField is now
  required in models and migrations. Consider squashing migrations so
  that you have fewer of them to update.

A: The issue comes from the foreign key which should be defined as follows:
pizza = models.ForeignKey('Pizza', on_delete=models.CASCADE)


text:
Q: SPICE Models with >3 Terminals for use in SIMPLIS I'm trying to convert a GaN FET SPICE model to use in a SIMPLIS schematic. The SPICE model is based on a typical MOSFET model (G-D-S) but also includes the TJ, TC and SS pin, as shown in figure.

I've found here (https://www.simplistechnologies.com/documentation/simplis/sp_semi/topics/mosfet_models_gt_3_terminals.htm) a way to convert this kind of model to use it in SIMPLIS, basically creating a "wrapped" model. In particular, the source pin of the wrapper sub-circuit is connected to both the source and bulk connector of the original sub-circuit (SS).
In my schematic I need to access externally the SS pin, avoiding connecting it to the source pin. How can I proceed? Is there a way to maintain the SS pin while converting the SPICE model in order to use it in SIMPLIS simulator?


text:
Q: dataWithContentsOfURL returns NSCocoaErrorDomain Code=256 over cellular, but not wifi Really odd problem I'm having: dataWithContentsOfURL has begun returning an error code 256 over cellular, but not over wifi.

The operation couldn't be completed. (Cocoa error 256.)

I do indeed have a cellular data connection, and it is functioning, so it is not a problem with my cellular connection. Plus the code works fine on wifi, so the basic code is not the issue. The code in question is:
dispatch_queue_t queue = dispatch_queue_create("com.appName.FetchImage", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
                    ...
                    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
                    NSLog(@"URL: %@", url);
                    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
                    NSError *error = [[NSError alloc] init];
                    NSData *imgData = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
                    if (error) NSLog(@"Error loading data: %@", error);
                    UIImage *image = [UIImage imageWithData:imgData];
                    ...
});

Any thoughts? I'm at a loss as to why this might be happening. It also occurs with the vanilla dataWithContentsOfURL (as opposed to with options).

A: NSCocoaErrorDomain Code = 256 means:

A file system or file I/O related error whose reason is unknown.

Simply, it tells us nothing.
However in general, NSData's dataWithContentsOfURL should only be use to access local file resources.

Important: Do not use this synchronous method to request network-based
  URLs. For network-based URLs, this method can block the current thread
  for tens of seconds on a slow network, resulting in a poor user
  experience, and in iOS, may cause your app to be terminated.

You can try improving your code and use a better way of downloading data. It might fix the issue you are experiencing. Instead of using dataWithContentsOfURL, you can use NSURLConnection's class methods like:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request
                          queue:(NSOperationQueue *)queue
              completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler;

Based on:
Using NSURLConnection
NSData Class Reference

A: In my case, the issue was a bad network connection on my mobile 4G. It was not xcode-specific, it also existed in regular safari browsing. I switched to a different network and that fixed the problem. The "hint" was that the method did not return immediately - it timed out after about a minute.