text:
Q: Java code reuse without inheritance I have 2 methods calling same method names:
public void doSomething1(Obj1 obj1) {
    obj1.do1();
    obj1.do2();
    obj1.do3();
}

public void doSomething2(Obj2 obj2) {
    obj2.do1();
    obj2.do2();
    obj2.do3();
}

I would like to extract to "common code" in a third method, this would be possible if I could create a super class of Obj1 and Obj2 but I can't. There is no way make these 2 objects inherit from a super class.
So my question is, is there a way in Java to do this kind of extraction when there is no link between objects, something like:
public void doSomething1(Obj1 obj1) {
    refactor(obj1);
}

public void doSomething1(Obj2 obj2) {
    refactor(obj2);
}

private void refactor(NewObj newObj) {
    newObj.do1();
    newObj.do2();
    newObj.do3();
}

A: Yes, but it's ugly: Reflection. But before we get to that, let me push back on something in the question:
Use an interface

...this would be possible if I could create a super class of Obj1 and Obj2 but I can't. There is no way make these 2 objects inherit from a super class.

They don't have to: They can just implement the same interface, without inheriting from the same superclass:
public interface TheCommonInterface {
    void do1();
    void do2();
    void do3();
}

public class Obj1 implements TheCommonInterface {
    // ...
}

public class Obj2 implements TheCommonInterface {
    // ...
}

Then
private void refactor(TheCommonInterface obj) {
    obj.do1();
    obj.do2();
    obj.do3();
}

Use a wrapper
If for some reason you can't even add an interface, use a wrapper class (an adapter class) that implements the interface.
Use reflection
In the worst case, you can use reflection: Use any of the several mechanisms on Class that let you find methods (such a getMethod), and then use Method#invoke on that method:
public void refactor(Object obj) {
    Class cls = obj.getClass();
    cls.getMethod("do1").invoke(obj);
    cls.getMethod("do2").invoke(obj);
    cls.getMethod("do3").invoke(obj);
}

That example is re-discovering the methods every time. If you ran into a performance problem doing that, you might look at caching them.

A: If the method body is the exactly the same, then they should inherit from a parent because they share a feature.
Alternatively, you can create an interface to share a behavior between the classes. But this will require implementing the body of the interface in both classes implementing it

A: You could use a static method
private static void refactor(NewObj newObj) {
    newObj.do1();
    newObj.do2();
    newObj.do3();
}

However, both object classes need to have a common interface NewObj in which case you can add this method to the interface:
interface NewObj {
    default void do123() {
        do1();
        do2();
        do3();
    }

    void do1();
    void do2();
    void do3();
}

A: You can create an interface with common methods.
After you can modify the original classes to implements those methods.
Then you can use the new created interface instead of Object as parameter in the function.
public interface DoOperations {
    void do1();
    void do2();
    void do3();
}

In the Obj1, Obj2 classes you need only to implements DoOperations
public Obj1 implements DoOperations {
    ....
}

public Obj2 implements DoOperations {
    ....
}

To call it:
public void doSomething(DoOperations obj) {
    obj.do1();
    obj.do2();
    obj.do3();
}


text:
Q: failed to load resource the server responded with a status of 403 I am trying to make two ajax calls to get amazon servers link and after that I am trying to play it in a modal but getting this I don't know how to solve or is there any other way in first ajax call I am taking the url from my own server and by that url's page I am trying to get amazon server's link after that I am trying to play a video i.e. on that link but it's not working

       <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to insert text at beginning of a multi-line selection in vi/Vim In Vim, how do I  insert characters at the beginning of each line in a selection?
For instance,  I want to comment out a block of code by prepending // at the beginning of each line assuming my language's comment system doesn't allow block commenting like /* */.  How would I do this?

A: The general pattern for search and replace is:
:s/search/replace/

Replaces the first occurrence of 'search' with 'replace' for current line
:s/search/replace/g

Replaces all occurrences of 'search' with 'replace' for current line, 'g' is short for 'global'
This command will replace each occurrence of 'search' with 'replace' for the current line only.  The % is used to search over the whole file.  To confirm each replacement interactively append a 'c' for confirm:
:%s/search/replace/c

Interactive confirm replacing 'search' with 'replace' for the entire file
Instead of the % character you can use a line number range (note that the '^' character is a special search character for the start of line):
:14,20s/^/#/

Inserts a '#' character at the start of lines 14-20
If you want to use another comment character (like //) then change your command delimiter:
:14,20s!^!//!

Inserts a '//' character sequence at the start of lines 14-20
Or you can always just escape the // characters like:
:14,20s/^/\/\//

Inserts a '//' character sequence at the start of lines 14-20
If you are not seeing line numbers in your editor, simply type the following
:set nu

A: *

*Press Esc to enter 'command mode'

*Use Ctrl+V to enter visual block mode

*Move Up/Downto select the columns of text in the lines you want to
comment.

*Then hit Shift+i and type the text you want to insert.

*Then hit Esc, wait 1 second and the inserted text will appear on every line.

For further information and reading, check out "Inserting text in multiple lines" in the Vim Tips Wiki.

A: To insert "ABC" at the begining of each line:

*

*Go to command mode

*% norm I ABC

A: Another way that might be easier for newcomers:
 some█
 code
 here

Place the cursor on the first line, e.g. by
gg
and type the following to get into insert mode and add your text:
I / / Space
 // █some
 code
 here

Press Esc to get back to command mode and use the digraph:
j . j .
 // some
 // code
 //█here

j is a motion command to go down one line and . repeats the last editing command you made.

A: For commenting blocks of code, I like the NERD Commenter plugin.
Select some text:
Shift-V
...select the lines of text you want to comment....

Comment:
,cc

Uncomment:
,cu

Or just toggle the comment state of a line or block:
,c<space>

A: And yet another way:

*

*Move to the beginning of a line

*enter Visual Block mode (CTRL-v)

*select the lines you want (moving up/down with j/k, or jumping to a line with [line]G)

*press I (that's capital i)

*type the comment character(s)

*press ESC

A: This adds # at the beginning of every line:
:%s/^/#/

And people will stop complaining about your lack of properly commenting scripts.

A: This replaces the beginning of each line with "//":
:%s!^!//!

This replaces the beginning of each selected line (use visual mode to select) with "//":
:'<,'>s!^!//!

Note that gv (in normal mode) restores the last visual selection, this comes in handy from time to time.

A: I can recommend the EnhCommentify plugin.
eg. put this to your vimrc:
let maplocalleader=','
vmap <silent> <LocalLeader>c <Plug>VisualTraditional
nmap <silent> <LocalLeader>c <Plug>Traditional
let g:EnhCommentifyBindInInsert = 'No'
let g:EnhCommentifyMultiPartBlocks = 'Yes'
let g:EnhCommentifyPretty = 'Yes'
let g:EnhCommentifyRespectIndent = 'Yes'
let g:EnhCommentifyUseBlockIndent = 'Yes'

you can then comment/uncomment the (selected) lines with ',c'

A: If you want to get super fancy about it, put this in your .vimrc:
vmap \c :s!^!//!<CR>
vmap \u :s!^//!!<CR>

Then, whenever in visual mode, you can hit \c to comment the block and \u to uncomment it. Of course, you can change those shortcut keystrokes to whatever.

A: Yet another way:
:'<,'>g/^/norm I//

/^/ is just a dummy pattern to match every line.  norm lets you run the normal-mode commands that follow.  I// says to enter insert-mode while jumping the cursor to the beginning of the line, then insert the following text (two slashes).
:g is often handy for doing something complex on multiple lines, where you may want to jump between multiple modes, delete or add lines, move the cursor around, run a bunch of macros, etc.  And you can tell it to operate only on lines that match a pattern.

A: Mark the area to be comment as a visual block (<C-V)
and do c#<ESC>p

*

*change it to "#"

*put it back

If you do it often, define a short cut (example \q) in your .vimrc
:vmap \q c#<ESC>p

A: In case someone's multi-line-selection is actually a paragraph, there is no need to manually select the lines. vim can do that for you:

*

*vip: select and mark the whole paragraph

*shift-i: insert text at line beginning

*escape: leave insert mode/enter normal mode [line beginnings still selected]

*escape: unselect line beginnings

A: Mapping of most voted answer:
1st visual select the desired lines, then execute <leader>zzz, which values:
vnoremap <leader>zzz <C-V>^I-<Space><Esc>

*

*<C-V> to enter visual mode

*^ goes to start of line ( or use '0' to 1st non blank)

*I to insert in block mode

*-<Space> to insert '- ' (for example, edit as you need)

*<Esc> to apply same insert to all visual block lines

Or of last visual selection from normal mode:
nnoremap <leader>zzz gv<C-V>^I-<Space><Esc>


text:
Q: Solving the strict inequality with integer math and accounting for rounding errors I have an array of floating point numbers of type T, where T could be either float or double
T x[n];

These numbers are strictly positive and sorted, i.e.
0 < x[0] < x[1] < x[2] < ... < x[n-1]

I want to find the smallest floating point number H of type T such that the following inequality is strictly satisfied:
int(x[i+1]*H) > int(x[i]*H)   // for i=0..n-2

Let's assume that the numbers x are such that there are no underflow or overflow issues to worry about.
I am approaching the problem as described below, which I am not sure if it is robust and, when it works, I think produces a suboptimal result.
Is there a robust and accurate way to solve this? I could accept a suboptimal solution, but at least it needs to be robust.

My current method
I use the notation m(x) to indicate a floating point number which approximates x and may be affected by roundoff error. In the following passages, I modify the inequality below taking as appropriate upper and lower bounds. Note that the below is not to be interpreted as source code, but as the matehmatical steps and reasoning to get to the final equations.
Let a(x) be the closest floating point number toward -inf
Let b(x) be the closest floating point number toward +inf

// Original inequality, where the operation affected by rounding error
// are marked with m()
int(m(x[i+1]*H)) > int(m(x[i]*H))   // for i=0..n-2

// I remove `atoi` subtracting and adding 0.5
// this is a conceptual operation, not actually executed on the machine,
// hence I do not mark it with an m()
m(x[i+1]*H) - 0.5 > m(x[i]*H) + 0.5   // for i=0..n-2

// I reorganize terms
m(x[i+1]*H) - m(x[i]*H) >  1.0        // for i=0..n-2

// I would like to resolve the m() operator with strict LHS minorant and RHS majorant
// Note I cannot use `a(x)` and `b(x)` because I do not know `H`
// I use multiplication by `(1+2*eps)` or `(1-2*eps)` as I hope this
// will result in a number strictly greater (or lower) than the original one.
// I already know this does not work for example if x is very small.
// So this seems like a pitfall of this approach.
x[i+1]*H(1-2*eps) - x[i]*H*(1+2*eps) >  b(1)  // for i=0..n-2

// solve the inequality for H, marking the operations affected by rounding
// with m()
H > m( b(1) / m( x[i+1](1-2*eps) - x[i]*(1+2*eps) ) ) // for i=0..n-2

// take majorant or minorant as appropriate for rounded terms
H > b( b(1) / a( x[i+1](1-2*eps) - x[i]*(1+2*eps) ) )   // for i=0..n-2

// and eventually take a majorant which gives me the final formula for H
H = b( b( b(1) / min{ a( x[i+1](1-2*eps) - x[i]*(1+2*eps) ) } ) )


text:
Q: what is wrong with the selector for a valuetype here, objective-c? #import <UIKit/UIKit.h>

typedef enum
{
    CellTypeTextInput,
    CellTypePicker
}CellType;

@interface TVCellWithProperties : UITableViewCell {

    CellType _cellType;
}

-(void)setCellType:(CellType)newType;
-(CellType)CellType;

@end

The Header
#import "TVCellWithProperties.h"

@implementation TVCellWithProperties

-(void)setCellType:(CellType)newType
{
    _cellType = newType;
}

-(CellType)CellType
{
    return  _cellType;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)dealloc {
    [super dealloc];
}
@end

I'm doing
[cell setCellType:CellTypePicker];

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCell setCellType:]: unrecognized selector sent to instance 0x5f66c30'
I tried the default accessors first using synthesize, but didn't work so i tried doing things manually and it still can't find the selector. Because it's not seeing the UITableViewCell as TVCellWithProperties.
What's wrong with my implementation ?
I was doing the following:
TVCellWithProperties *cell = (TVCellWithProperties*)[tv dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"EditableContent" owner:self options:nil];

        cell = tvCell;
        self.tvCell=nil;
    }

The problem was that in the nibfile, the tableviewCell i was loading was of type 'UITableViewCell', so i made it 'TVCellWithProperties'.
and it worked.
Thank you NR4TR

A: Are you sure that you are sending message to TVCellWithProperties instance but not UITableViewCell instance? Check initializations inside cellForRowAtIndexPath method.


text:
Q: Meaningful English sentences containing very few distinct letters An English pangram is a sentence that contains each of the 26 letters used in English, the classic example being `the quick brown fox jumps over the lazy dog.' What I am looking for is precisely the opposite. I am looking for meaningful English phrases or sentences that contain very few distinct letters, preferably 8 or less.
A small example is the computer science phrase `hello world' which is meaningful and contains only 7 distinct letters (h,e,l,o,w,r,d). Is there a repository containing examples of similar phrases, or can Stack Exchange users generate their own?

Why would you want such phrases?
I am mathematician and I plan to teach a group of high school about Huffman codes. A Huffman code is a code for converting letters into binary (0s and 1s). Given a sentence (or passage, or book) the coding is chosen so as to minimize the total number of binary digits needed. So for example, in English the letter E is very frequent and the letter Z is not; one might then assign the letter E the short binary sequence 110, and the letter Z the longer sequence 111100101. That way when you convert a book into binary you will use fewer digits than if, say, you had assigned 111100101 to E and 110 to Z.
In working through examples in class, the tediousness of generating the code is directly proportional to the number of distinct letters contained in the passage one is encoding. Roughly speaking, the fewer letters present, the shorter the code book needs to be. English sentences containing few distinct letters would, for this reason, be great examples to Huffman encode.

A: This one has four distinct letters:

Madam, I'm Adam.

It's also notable because it is a palindrome, and it was also the first sentence uttered by a human being (joke).

A: Sounds like a fun lesson you have planned.
The trick here is to find words with repeated letters, and alliteration and assonance help.
Your hello world example had 7 letters, so I created some phrases with less than 7 letters:

*

*An assassin sins (4 letters)

*Eleven elves (5 letters)

*Free the referee (5 letters)

*Twitter tweet (5 letters)

*Catch the cat (5 letters)

*Hum drum (5 letters)

*I rent tents (5 letters)

*Groggy puppy (6 letters)

*No inhibition (6 letters)

*Beekeepers keep bees (6 letters)

Here is a resource from professor David Singmaster at puzzlemuseum.com which lists (among other things) words with repeating letters, categorized by word length which might assist you if you want to create any more.

A: As sentences need a verb, the strategical approach to this is to first consider verbs with as few letters as possible, i.e., two. Then it's an easy programming task to find further words using only those two letters. Finally, you have see whether you can arrange those words to a meaningful sentence.
Using this strategy, I found the following sentences with only two distinctt letters (ignoring capitalisation):

*

*
Add Dada, dad.

A father is asked to incorporate a style into some piece of art.

*
Isis is Isis.
  Sissi's sis is Sissi's sis.

It is asserted that somebody named Isis or the sister of somebody named Sissi acted according to their nature.

*
Toot, Otto!

An elephant named Otto is asked to produce a sound.

*
Pee, Pepe!

Somebody named Pepe is asked to urinate.


text:
Q: HTML div element doesn't fall into keyboard tabbing order I have a HTML file in which generating a
 element with knockout css binding.
Now, the problem is the newly/dynamically generated DOM element doesn't fall into the keyboard tabbing order. Keyboard tabbing would skip this DOM and focus on the next DOM.
If I manually set focus using JavaScript focus(), the DOM is accessible (I can navigate through other Divs within this DOM). I've also set the tabindex="0" for this DOM.
But it just doesn't fall under keyboard's logical ordering.
    Any idea what's wrong with the HTML ?

        <button class="toolbar-group-button toggle-button" id="toggle-query-mode" title="Toggle query builder" data-bind="event: { mousedown: onMouseDown, mouseover: onMouseOver, mouseout: onMouseOut, focus: onFocus, blur: onBlur, keydown: onKeyDown, keyup: onKeyUp }">

          Query
        </button>


text:
Q: Bootstrap carousel event isn't work in Firefox browser I was trying to customize the bootstrap carousel to make it a simple content slider. I saw two events in bootstrap docs and using animate.css for animation, chrome even Internet explorer showing the animation perfectly. but in firefox animation working just for first time.
here is the code I used to set the animation
$('#home-slider').on('slide.bs.carousel', function () {
$('#home-slider .slideInLeftTrigger').removeClass('slideInLeft');
$('#home-slider .fadeInRightBigTrigger').removeClass('fadeInRightBig');

$('#home-slider .slideInLeftTrigger').addClass('slideInLeft');
$('#home-slider .fadeInRightBigTrigger').addClass('fadeInRightBig');

console.log('next');
})

Mysterious thing is console log is printing perfectly but the addClass and removeClass isn't working.
Is there any way to show the animation in all browser?
**I'm new here, pardon me for any mistakes!

A: I have solved the problem now its working on firefox,
I was going to delete this topic but may be its better to keep the solution here for future referance.
I used two bootstrap carousel events, one for removing animation class and one to adding,
$('#home-slider').bind('slide.bs.carousel', function (e) {
  $('#home-slider .slideInLeftTrigger').removeClass('slideInLeft');
  $('#home-slider .fadeInRightBigTrigger').removeClass('fadeInRightBig');
})

$('#home-slider').bind('slid.bs.carousel', function (e) {
  $('#home-slider .slideInLeftTrigger').addClass('slideInLeft');
  $('#home-slider .fadeInRightBigTrigger').addClass('fadeInRightBig');

})

Thanks


text:
Q: IP Block Regex for Javascript Please can someone help me write a regex to validate an IP BLock eg. 196.126.0.1/29.
Thanks!

A: If you want to check that the IP is correct you can use the following expression :
 ^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$

\d{1,3}\. check that you have one to three digit following with a dot.
(\d{1,3}\.){3} repeteat the test three time.
\d{1,3}\/\d{1,2} last IP digits following with a slash and a port number (change the max number of digit if the port may be more than two digit).


text:
Q: What is the difference between storing table data by filecontents and pgfplotstableread? In this MWE, the table data loaded from poles.dat is successfully parsed as shown in the left plot.
However, storing the same data inside a macro using \pgfplotstableread doesn't result in the same expected output.
Why is there a difference between both ways? and how to make the second approach of pgfplotstableread work like the first one of *.dat file?
\documentclass[border=1cm]{standalone}

\usepackage{pgfplots,pgfplotstable}

\pgfplotsset{compat=newest,
    poles/.style= { only marks, mark=x, mark size = 1ex, thick},
    point meta = explicit symbolic,
    visualization depends on={\thisrow{angle} \as \myangle},
    visualization depends on={value \thisrow{label} \as \mylabel},
    Label Style/.style args = {#1}{
        nodes near coords,
        every node near coord/.style = %
        {
            anchor=south, label={[#1]\myangle:{\mylabel}}
        },
    }
}

\usepackage{filecontents}
\begin{filecontents*}{poles.dat}
    Re      Im      label       angle
    -2      2       (-2,2)      270
    -2      -2      (-2,-2)     90
    -4      0       (-4,0)      60
\end{filecontents*}

\pgfplotstableread{
    Re      Im      label       angle
    -2      2       (-2,2)      270
    -2      -2      (-2,-2)     90
    -4      0       (-4,0)      60
}\mytable

\begin{document}
    \begin{tikzpicture}
    \begin{axis}
        \addplot[Label Style={blue,fill = gray!20},poles]   table {poles.dat};
    \end{axis}
    \end{tikzpicture}
    \begin{tikzpicture}
    \begin{axis}
        \addplot[Label Style={blue,fill = gray!20},poles]   table {\mytable};
    \end{axis}
    \end{tikzpicture}
\end{document}

A: Here is a crazy workaround: write the table to a file and read it again. (Of course, in the present example this does not make sense.) However, there are situations in which it can make sense, e.g. when you create the table through macros or when you really want to skip some rows, like here.
\documentclass[border=1cm]{standalone}

\usepackage{pgfplots,pgfplotstable}

\pgfplotsset{compat=newest,
    poles/.style= { only marks, mark=x, mark size = 1ex, thick},
    point meta = explicit symbolic,
    visualization depends on={\thisrow{angle} \as \myangle},
    visualization depends on={value \thisrow{label} \as \mylabel},
    Label Style/.style args = {#1}{
        nodes near coords,
        every node near coord/.style = %
        {
            anchor=south, label={[#1]\myangle:{\mylabel}}
        },
    }
}

% from https://tex.stackexchange.com/a/445369/121799
\newcommand*{\ReadOutElement}[4]{%
    \pgfplotstablegetelem{#2}{#3}\of{#1}%
    \let#4\pgfplotsretval
}
% based on https://tex.stackexchange.com/a/307032/121799
% and https://tex.stackexchange.com/a/451326/121799
\newcommand{\GetRow}[2]{
\pgfplotstablegetcolsof{\mytable}
\pgfmathtruncatemacro{\colnumber}{\pgfplotsretval-1}
\foreach \XX in {0,...,\colnumber}
{%
\ReadOutElement{\mytable}{#1}{[index]\XX}{\tmp}%
\ifnum\XX=0%
\xdef#2{{\tmp}}%
\else%
\xdef#2{#2,{\tmp}}%
\fi%
}
}

\usepackage{filecontents}
\begin{filecontents*}{poles.dat}
    Re      Im      label       angle
    -2      2       (-2,2)      270
    -2      -2      (-2,-2)     90
    -4      0       (-4,0)      60
\end{filecontents*}

\pgfplotstableread{
    Re      Im      label       angle
    -2      2       (-2,2)      270
    -2      -2      (-2,-2)     90
    -4      0       (-4,0)      60
}\mytable

\pgfplotstablegetrowsof{\mytable}%
\pgfmathtruncatemacro{\rownum}{\pgfplotsretval-1}%
\pgfplotstablegetcolsof{\mytable}%
\pgfmathtruncatemacro{\colnum}{\pgfplotsretval-1}%
\foreach \X in {0,...,\colnum}%
{\pgfplotstablegetcolumnnamebyindex{\X}\of{\mytable}\to\pgfplotsretval%
\ifnum\X=0%
\xdef\tmp{\pgfplotsretval}%
\else%
\xdef\tmp{\tmp,\pgfplotsretval}%
\fi}
\newwrite\myoutput% from https://tex.stackexchange.com/a/290058/121799
\immediate\openout\myoutput=\jobname-tmp.dat%
\immediate\write\myoutput{\tmp}% create table header
\foreach \X in {0,...,\rownum}% rows
{\GetRow{\X}{\myrow}%
\immediate\write\myoutput{\myrow}}%
\immediate\closeout\myoutput%

\begin{document}
    \begin{tikzpicture}
    \begin{axis}
        \addplot[Label Style={blue,fill = gray!20},poles]   table {poles.dat};
    \end{axis}
    \end{tikzpicture}
    \begin{tikzpicture}
    \begin{axis}
        \addplot[Label Style={blue,fill = gray!20},poles]
        table[col sep=comma] {\jobname-tmp.dat};
    \end{axis}
    \end{tikzpicture}
\end{document}

Needless to say that one could clean up the macros. I hesitate to do that before I know all possible applications. One is to skip rows, which is important for regression plots, and another one is like here in which one uses pgfplots to do more complicated annotations. I'm wondering if there are further obvious use cases.

A: I found the following in the pgfplots source code.
% The normal implementation of \thisrow is not accessable here. And the
% worst is: error messages are impossible either because they are
% not executed... we resort to the associated math functions:
\def\thisrow##1{thisrow("##1")}% let us hope that math parsing is active!

Note that this solution always uses \mytable.  The key was the use of \coordindex.
\documentclass[border=1cm]{standalone}

\usepackage{pgfplotstable,pgfplots}

\pgfplotsset{compat=newest,
    poles/.style= { only marks, mark=x, mark size = 1ex, thick},
    point meta = explicit symbolic,
    visualization depends on={\thisrow{angle} \as \myangle},
    %visualization depends on={value \thisrow{label} \as \mylabel},
    Label Style/.style args = {#1}{
        nodes near coords,
        every node near coord/.style = %
        {
            anchor=south, label={[#1]\myangle:{\pgfplotstablegetelem{\coordindex}{label}\of{\mytable}\pgfplotsretval}}
        },
    }
}
\newcommand{\myotherlabel}{\pgfmathparse{\thisrow{label}}\pgfmathresult}

\usepackage{filecontents}
\begin{filecontents*}{poles.dat}
    Re      Im      label       angle
    -2      2       (-2,2)      270
    -2      -2      (-2,-2)     90
    -4      0       (-4,0)      60
\end{filecontents*}

\pgfplotstableread[columns/label/.style={string}]{
    Re      Im      label       angle
    -2      2       (-2,2)      270
    -2      -2      (-2,-2)     90
    -4      0       (-4,0)      60
}\mytable

\begin{document}
    \begin{tikzpicture}
    \begin{axis}
        \addplot[Label Style={blue,fill = gray!20},poles]   table {poles.dat};
    \end{axis}
    \end{tikzpicture}
    \begin{tikzpicture}
    \begin{axis}
        \addplot[Label Style={blue,fill = gray!20},poles]   table {\mytable};
    \end{axis}
    \end{tikzpicture}
\end{document}


text:
Q: How can I get my search query to show up in URL? Using MVC 4
I have a partial view where I am creating a a search box.
When the submit button is clicked it then passes the value of my search to the control to filter my groups.
Everything filters just fine.  However the url I am hoping to get after performing the action is not coming up.  I just get localhost/
What I would like to show up would be localhost/mySearchValue
The routing in my project is set up so that if I were to type a value after local host it would then filter the groups just as my search button does.
Any ideas on what I need to do to get my search value to show up in the URL?
Here is my partial view
@using (Html.BeginForm("List","Group"))
{
   @Html.TextBox(name: "search")
   <input type="submit"  value="search" />
}

My Controller
public ViewResult List(string search, int page = 1)
    {
        if (search == "")
        {
            search = null;
        }
        GroupsListViewModel model = new GroupsListViewModel
        {
            Groups = repository.Groups
            .Where(g => search == null || g.Tag == search || g.Tag2 == search)
            .OrderBy(g => g.GroupId)
            .Skip((page - 1) * PageSize)
            .Take(PageSize),
            PagingInfo = new PagingInfo
            {
                CurrentPage = page,
                ItemsPerPage = PageSize,
                TotalItems = repository.Groups.Count()
            },
            CurrentSearch = search
        };

Update
@Html.BeginForm("List","Group",FormMethod.Get)

Helps me get a url as follows localhost/?search=test however search is not being set when the controller is called and so no filtering happens.  My url schema for searching is as follows localhost/test
Here is my routing information
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(null,
            "",
            new {
                controller = "Group", action = "List",
                search = (string)null, page = 1
            }
    );

        routes.MapRoute(null,
            "Page{page}",
            new { controller = "Group", action = "List", search = (string)null },
            new { page = @"\d+" }
            );

        routes.MapRoute(null,
            "{search}",
            new { Controller = "Group", action = "List", page = 1 }
            );

        routes.MapRoute(null,
            "{search}/Page{page}",
            new { controller = "Group", action = "List" },
            new { page = @"\d+" }
        );

        routes.MapRoute(null, "{controller}/{action}");
    }

A: Description
As long as i understand the question
Default form method is POST so you need set the form method to GET in order to see the search string in the url.
Please let me know (as a comment) if i dont understand what your want in order to help you more)
Sample
@Html.BeginForm("List","Group",FormMethod.Get)

More Information

*

*MSDN - FormExtensions.BeginForm Method


text:
Q: Overriding layouts in RefineryCMS I have just started working with ruby on rails properly like for a week and now I have started working on RefineryCMS, I followed the official guide and created a demo application and got to know the interface and the CMS itself a little bit, now I am trying to create a proper site using RefineryCMS. The first thing I wanted to do was to change the appearance of the default homepage, hence I override it and added my own HTML that I have and replaced the default layout that worked fine to some extent. Now the problem is I had style sheet associated with my HTML, as I am new to this CMS I cannot find a way to properly link my style sheets/ override my style sheets associated with the home page.   I have followed the official documentation but was unable to get through the idea of how to override the stylesheets, I have followed other various links as well.
Can someone please guide me to a tutorial where there is a stepwise explanation regarding how to do that, or even better a stepwise detailed tutorial for newbies like me to get started with the RefineryCMS, I have spent hours but still have found a proper way, maybe I havent been looking or googling the right question because I am new to this CMS i.e. "How do I properly link my overridden HTML in refineryCMS to its corresponding stylesheets also to the corresponding images and javascript files"
I would really appreciate any sort of help to get me going. Thank you.

A: Thanks for using Refinery.  There are two ways to do this, but really the first one is my preference.
The easy and recommended way, using CSS selectors:
First, check out the getting started guide's section on "styling views".
Now, just create an asset file for the home page, let's call it app/assets/stylesheets/home.css.scss.  To that, we can add nested styles under the following ID selector.  I've added background: red; so that you can see an immediate result:
body#home-page {
  background: red;
}

This is the way that I would recommend adding CSS for templates.
For the non-recommended, complicated way that requires extra assets and adding to the precompile list:
First, see the overriding views guide.
Now, with the refinery/pages/home.html.erb template that you will have, you can link to a stylesheet:
<% content_for :stylesheets, stylesheet_link_tag('home') %>

The stylesheet should now be linked in the <head> section of the page and you should be able to add CSS that just relates to the home page by creating the app/assets/stylesheets/home.css.scss file and applying it in the same way as the first section:
body#home-page {
  background: red;
}

Note that because this is in the same directory as the manifest file application.css it will automatically get included for all templates, too, and so this is more complicated.  It also requires you to add to the precompile list in config/application.rb:
config.assets.precompile += %w(home.css)


text:
Q: RestKit Mapping error when compiling release builds iOS I am using RestKit in one of my projects and using it to map a json response. The mapping behaviour as expected on a fresh install or debug build.
However when complied as a release build and distributed via TestFlight all my mapping fails. Logging the JSON to the console shows the json to be as expected and matches the model.
I can only assume recently i have made a compiler change (or xCode defaults have changed) but i cannot spot what is causing the issue.
Anyone had this issue before?
Cheers
Dan
Update: i have tried updating to latest stable build of Restkit and not made a difference

A: I reverted the project settings to default and slowly added each item until it started to work. I think I had a missing DNS_BLOCK_ASSERTION.
Hope this helps someone in the future


text:
Q: django Не открывается страница админки Изучаю django по книге Дронов В. А., "Практика создания веб сайтов". Успешно прошел первую часть - все люкс, все ясно и все работает... вот только не открывается админка. Не могу понять где накосячил.
Вот что выдает browser

samplesite\urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('bboard.urls')),
    path('admin', admin.site.urls)

bboard\urls.py
from django.urls import path

from .views import index, by_rubric, BdCreateView

urlpatterns = [
    path('add/', BdCreateView.as_view(), name='add'),
    path('<int:rubric_id>/', by_rubric, name='by_rubric'),
    path('', index, name='index')
]

A: admin URL - адрес должен быть первым:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('nw.urls', namespace='posts')),

]
В противном случае оно будет перехвачено другим соответствующим регулярным выражением в вашем приложении сообщений urlpatterns, а именно:
url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'),

Как правило, всегда размещайте адрес администратора в верхней части страницы проекта.urlpatterns


text:
Q: recursive exercise on codingbat I am currently working on an exercise on codingbat website which says:

Given an array of ints, compute recursively if the array contains a 6.
  We'll use the convention of considering only the part of the array
  that begins at the given index. In this way, a recursive call can pass
  index+1 to move down the array. The initial call will pass in index as
  0.

Example:
array6([1, 6, 4], 0) → true
array6([1, 4], 0) → false
array6([6], 0) → true
my solution is below but for some reason when my if(nums[index] == 6) is true it still executes the code within the else block.
My Question:
Technically, it should not execute the code within the else block when the code within the if statement is executed. so why does that persist?;
public static boolean array6(int[] nums, int index) {

    if(nums.length == 0){
          return false;
    }

    if(index == nums.length-1 && nums[index] != 6){
          return false;
    }

    if(index == nums.length-1 && nums[index] == 6){
          return true;
    }

    if(nums[index] == 6){
           return true;

    }else{
           array6(nums,index+1);
    }

    return false;
}

A: Return the value you receive by recursion. Change
array6(nums,index+1);

to something like
return array6(nums,index+1);

A: public static boolean find(int[] a, int value) {
    if (a == null) {
        throw new IllegalArgumentException("Illegal argument!");
    }
    return find(a, value, 0);
}

private static boolean find(int[] a, int value, int index) {
    if (index == a.length) return false;
    if (a[index] == value) return true;
    return find(a, value, index + 1);
}

A: Check if my answer satisfies your question
public boolean array6(int[] nums, int index) {
  if(nums.length == 0 || index > nums.length-1){
    return false;
  }
  if(nums[index] == 6){
    return true;
  }

  return array6(nums,index+1);
}


text:
Q: How to loop through pack_rows in r using kableextra package? A   C
-------
KK  1
KK  3
KK  3
AA  4
AA  52
BB  33
BB  7
BB  83
DD  91
DD  10

i have a table like the  one above i want to use column A and make it into groups
and use start and end index to be used in pack_rows to automate using the dataframe above.
i tried to use for loop but it didn't work it showing error in loop so how can i loop through
using below code
kbl(df,booktabs = T,longtable = T) %>%
kable_styling(latex_options = c("repeat_header"),bootstrap_options = "bordered",font_size = 7,full_width = F)%>%
  row_spec(0, bold = T, color = "white", background = "#008752")%>%
  pack_rows("KK", 1, 3,background = "#008000")%>%
  pack_rows("AA", 4, 5,background = "#008000")

A: Make A column as factor with levels same as appearance. Use table in pack_rows -
library(knitr)
library(kableExtra)

df$A <- factor(df$A, unique(df$A))

kbl(df,booktabs = T,longtable = T) %>%
  kable_styling(latex_options = c("repeat_header"),
        bootstrap_options = "bordered",font_size = 7,full_width = F)%>%
  row_spec(0, bold = T, color = "white", background = "#008752")%>%
  pack_rows(index = table(df$A), background = "#008000")


text: Q: WordPress как искать файлы Подскажите некий алгоритм как через Chrome, искать файлы Wordpress, допустим на странице есть какой-то элемент к которому привязан Js код. Как лучше всего найти где на хостинге хранится этот код?


text:
Q: cmake and make resulting in different binary sizes when cross-compiling I am cross-compiling to an ARM target in a Ubuntu 20.04 host machine.
The files I am building are from an SDK from Quectel, which already has makefiles and it builds fine.
My job is to translate the makefiles into a CMakeFileList.txt to do the same as the makefile does. That is already done.
Procedure to translate makefiles to cmake
I ran the make with verbose mode, and then I collected all the flags that are set, linker options, compiler options, linker mapping, etc.
Issue found on this
I noticed that the binary differs from what is built via the makefiles and what is built via CMakeList.txt, although they are working.
Output from the original makefiles:
Memory region         Used Size  Region Size  %age Used
LOAD_IRAM_MCUVECTOR:         100 B        100 B    100.00%
   LOAD_IRAM_MCU:        4056 B       5020 B     80.80%
UNLOAD_DRAM_USRNV:          1 KB         1 KB    100.00%
   LOAD_DRAM_MCU:          48 B         4 KB      1.17%
UNLOAD_DRAM_PSPHYRET:          6 KB         6 KB    100.00%
       LOAD_IRAM:       32404 B        32 KB     98.89%
LOAD_DRAM_SHARED:      124448 B       156 KB     77.90%
   LOAD_DRAM_BSP:        3884 B         8 KB     47.41%
UNLOAD_DRAM_FLASHMEM:          7 KB         7 KB    100.00%
UNLOAD_DRAM_SLPMEM:         224 B        992 B     22.58%
       FLASH_APP:     2356204 B      2560 KB     89.88%

Output from the CMakeList.txt developed:
Memory region         Used Size  Region Size  %age Used
LOAD_IRAM_MCUVECTOR:         100 B        100 B    100.00%
   LOAD_IRAM_MCU:        4056 B       5020 B     80.80%
UNLOAD_DRAM_USRNV:          1 KB         1 KB    100.00%
   LOAD_DRAM_MCU:          48 B         4 KB      1.17%
UNLOAD_DRAM_PSPHYRET:          6 KB         6 KB    100.00%
       LOAD_IRAM:       32404 B        32 KB     98.89%
LOAD_DRAM_SHARED:      124464 B       156 KB     77.91%
   LOAD_DRAM_BSP:        3884 B         8 KB     47.41%
UNLOAD_DRAM_FLASHMEM:          7 KB         7 KB    100.00%
UNLOAD_DRAM_SLPMEM:         224 B        992 B     22.58%
       FLASH_APP:     2354932 B      2560 KB     89.83%

As you can see, the difference is quite small, 3984 Bytes more in the CMakeList.txt case.
The compiler and linker used are the same:
arm-none-eabi-gcc --version
arm-none-eabi-gcc (GNU Toolchain for the Arm Architecture 11.2-2022.02 (arm-11.14)) 11.2.1 20220111
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

arm-none-eabi-ld --version
GNU ld (GNU Toolchain for the Arm Architecture 11.2-2022.02 (arm-11.14)) 2.37.20220122
Copyright (C) 2021 Free Software Foundation, Inc.
This program is free software; you may redistribute it under the terms of
the GNU General Public License version 3 or (at your option) a later version.
This program has absolutely no warranty.

Question: Is there a reason for this difference?


text:
Q: Regex for -1 to 999 but can accept blank Regex for -1 to 999 but can accept blank
I have created this ^(?:^[0-9]+)?$ . This regex accepts positive numbers and also blank values. How do I limit it to 3 digits and allow it to accept -1 also.
I tried using the annotations @max and @min in Java . But they do not allow blank fields. I am using the annotation @pattern to match the incoming number to a regex

A: I would use:
^(?:-1|[0-9]{1,3})$

Demo
But actually, I wouldn't use this regex if I were using a programming language.  Instead, this requirement would more easily be handled by a range check, e.g. in Java:
int input = 10;
if (input >= -1 && input <= 999) {
    System.out.println("MATCH");
}

If you also want to allow blanks, then just add an empty case to the alternation:
^(?:-1|[0-9]{1,3}|)$


text:
Q: What is a good way to access the "last" [...,-1] dimension of a numpy array when it might be 0-D? What is a good way to access the last ("-1") dimension of a numpy array, say X, when X.ndim can be equal to either 0 (i.e. X is effectively a scalar) or a positive integer (1,2,3)? I am trying to write a generalized function that takes either a scalar or an array of initial values, and does something with them over iterations.
Is there a way to neatly extend the answer given here: Numpy: Indexing over the last axis when you don't know the rank in advance ? It worked perfectly for all cases except the 0D case.
I am currently getting an Index Error (IndexError: too many indices for array) with the following minimal example:
n = 0.1
n = np.asarray(n)
n = n[...,-1]

A: Best solution is to never allow 0-d arrays.  They cause strange errors like this.
Instead of using np.array(a), if you expect that you might get a singleton input,  use np.atleast_1d(a), which returns array([2]) for a = 2, and can be indexed as normal.

A: You can check the number of dimensions at runtime with ndim, for example:
import numpy as np

def get_last_dim(arr):
    if arr.ndim==1:
        return arr
    else:
        return arr[:,-1]

a = np.array([1,2,3])
b = np.array([[1,2],[3,4]])

print(get_last_dim(a))
print(get_last_dim(b))

A: >>> import numpy as np
>>> n = 0.1
>>> n = np.asarray(n)
>>> n = np.atleast_1d(n)[...,-1]
>>> n
array(0.1)


text:
Q: What can I do to determine why my hdd is not mounting? PURPOSE: Determine why the hdd will not mount after creating a duplicate hdd out of it.
Host hdd: 4tb.gold
Destination hdd: boo.boo
Originally mount the hdd = When I 1st connected the 2 hdd's to the computer before doing any other steps afterwards; the number 1 thing I did after starting the computer.

I used the following command to make the duplicate
"sudo dd if=/dev/sdx bs=16M of=/dev/mapper/boo.boo"

whereby the destination hdd ("of...") was mounted before running that command.
I used the following command to originally mount the hdd b/f duplication, and then again when trying to mount the hdd after duplication:
"sudo mount /dev/mapper/boo.boo /mnt"

... The duplicating finished, but now the hdd shows up in lsblk, opens with cryptsetup, but will not mount.
Common error message: "bad superblock, wrong fs type, bad..."

UPDATE:
"sudo fsck /dev/sdx" = fsck from util-linux 2.33.1
$ sudo fdisk -l /dev/mapper/boo.boo (destination hdd which was only hdd mounted)
GPT PMBR size mismatch (3907029167 != 3906996399) will be corrected by write.
Disk /dev/mapper/4tb.gold: 1.8 TiB, 2000382156800 bytes, 3906996400 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 4096 bytes / 33553920 bytes
Disklabel type: dos
Disk identifier: 0x00000000

Device                     Boot Start        End    Sectors  Size Id Type
/dev/mapper/4tb.gold-part1          1 3906996399 3906996399  1.8T ee GPT

Partition 1 does not start on physical sector boundary.

A: Does /dev/sdX holds some partitions ?
What is the output of fdisk -l /dev/mapper/4tb.gold ?
If /dev/mapper/4tb.gold represents the whole disk (which was partitionned), then you have to mount one of theses partitions.

A:
"sdx" has 3 partitions, "dev/mapper" likely had 1

If the source had 3 partitions, after you cloned it, the mapper device also has 3 partitions now. (It doesn't really matter what the destination had – you overwrote everything while cloning.)
So you cannot mount it for the same reason you cannot actually mount sdx as a whole: a disk with a partition table doesn't have anything mountable. The partitions are mountable, not the disk itself.
Device-mapper devices will not automatically recognize a partition table inside them; you'll have to separately create new dm-linear mappings for each partition. This can be most easily done using the kpartx tool from multipath-tools:
kpartx -av /dev/mapper/diskname

mount /dev/mapper/disknamep1 /mnt

(I would recommend re-doing the cloning from scratch, and this time leaving the partition table unencrypted – instead create a separate crypt device for every partition.)


text:
Q: CodeIgniter RESTful and controller Hi i am new to CI and MVC in general and i am trying to make a REStful application.
I have read a lot (really) and i have the following specification
RESTful
Read (GET)
/object
/object.xml
/object.json

Read id (GET)
/object/id
/object/id.xml
/object/id.json

Create (POST)
/object
/object.xml
/object.json

Update (PUT)
/object/id
/object/id.xml
/object/id.json

Delete (DELETE)
/object/id
/object/id.xml
/object/id.json

Based on the above when extension is .xml return xml, when .json returns json and on extension returns html
When comes to CI CRUD i have the followig urls
 /object
 /object/edit/id
 /odject/delete/id

My question is
Do i need 2 controllers 1 for RESTful and 1 for CI CRUD or i can have only 1,
and how can i have the multiple respesentation (html,xml,json).
Any help appricated (link for reading too)
Thanks

A: Take a look at: http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/
You can also do this a different way, however I think the above is probably the best place to start.
Update
Another way, could be to use routes.
$routes['object\.(xml|http|json)'] = 'process_object/$1';
$routes['object/(:num)\.(xml|http|json)'] = 'process_object/$2/$1';
$routes['object/crud/\.(xml|http|json)'] = 'process_object/$1/null/true';
$routes['object/crud/(:num)\.(xml|http|json)'] = 'process_object/$2/$1/true';

Then your process_object action:
function process_object($Format = 'xml', $ID = null, $CRUD = false)
{
    $method = $this->_detect_method(); // see http://stackoverflow.com/questions/5540781/get-a-put-request-with-codeigniter
    $view = null;
    $data = array();
    switch($method)
    {
        case 'get' :
        {
            if($CRUD !== false)
                $view = 'CRUD/Get';
            if($ID === null)
            {
                // get a list
                $data['Objects'] = $this->my_model->Get();
            }
            else
            {
                $data['Objects'] = $this->my_model->GetById($ID);
            }
        }
        break;
        case 'put' :
        {
            if($CRUD !== false)
                $view = 'CRUD/Put';
            $this->my_model->Update($ID, $_POST);
        }
        break;
        case 'post' :
        {
            if($CRUD !== false)
                $view = 'CRUD/Post';
            $this->my_model->Insert($_POST);
        }
        break;
        case 'delete' :
        {
            if($CRUD !== false)
                $view = 'CRUD/Delete';
            $this->my_model->Delete($ID);
        }
        break;
    }
    if($view != null)
    {
        $this->load->view($view, $data);
    }
    else
    {
        switch(strtolower($Format))
        {
            case 'xml' :
            {
                // create and output XML based on $data.
                header('content-type: application/xml');
            }
            break;
            case 'json' :
            {
                // create and output JSON based on $data.
                header('content-type: application/json');
                echo json_encode($data);
            }
            break;
            case 'xml' :
            {
                // create and output HTML based on $data.
                header('content-type: text/html');
            }
            break;
        }
    }
}

Note: I haven't tested this code in anyway, so it will need work.


text:
Q: I'm having an error processing JSON data with GSON in Android: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $ I'm trying to fetch data from a server and convert one row containing a 2D array into a list, but I'm getting an error when I do this.
Here is my logcat monitor:
08-16 10:48:50.146 4914-4914/? I/zygote: Not late-enabling -Xcheck:jni
(already on)
08-16 10:48:50.261 4914-4914/? W/zygote: Unexpected CPU variant for X86
using defaults: x86
08-16 10:48:51.295 4914-4914/com.example.alexlevine.oceanapp I/InstantRun:
starting instant run server: is main process
08-16 10:48:52.253 4914-4914/com.example.alexlevine.oceanapp I/zzbx: Making
Creator dynamically
08-16 10:48:52.354 4914-4914/com.example.alexlevine.oceanapp W/zygote:
Skipping duplicate class check due to unrecognized classloader
08-16 10:48:52.390 4914-4914/com.example.alexlevine.oceanapp
I/Google Maps Android API: Google Play services client version: 11020000
08-16 10:48:52.395 4914-4914/com.example.alexlevine.oceanapp
I/Google Maps Android API: Google Play services package version: 11302470
08-16 10:48:52.415 4914-4921/com.example.alexlevine.oceanapp I/zygote: Do
partial code cache collection, code=30KB, data=13KB
08-16 10:48:52.415 4914-4921/com.example.alexlevine.oceanapp I/zygote: After
code cache collection, code=26KB, data=13KB
08-16 10:48:52.415 4914-4921/com.example.alexlevine.oceanapp I/zygote:
Increasing code cache capacity to 128KB
08-16 10:48:52.685 4914-5006/com.example.alexlevine.oceanapp W/afz:
copyMemory is missing from platform - proto runtime falling back to safer
methods.
08-16 10:48:52.718 4914-4990/com.example.alexlevine.oceanapp
D/NetworkSecurityConfig: No Network Security Config specified, using
platform default
08-16 10:48:52.869 4914-5022/com.example.alexlevine.oceanapp
D/OpenGLRenderer: HWUI GL Pipeline
08-16 10:48:52.989 4914-5022/com.example.alexlevine.oceanapp
I/OpenGLRenderer: Initialized EGL, version 1.4
08-16 10:48:52.989 4914-5022/com.example.alexlevine.oceanapp
D/OpenGLRenderer: Swap behavior 1
08-16 10:48:52.989 4914-5022/com.example.alexlevine.oceanapp
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED,
retrying without...
08-16 10:48:52.990 4914-5022/com.example.alexlevine.oceanapp
D/OpenGLRenderer: Swap behavior 0
08-16 10:48:53.025 4914-5022/com.example.alexlevine.oceanapp
D/EGL_emulation: eglCreateContext: 0xa3f06500: maj 2 min 0 rcv 2
08-16 10:48:53.030 4914-5022/com.example.alexlevine.oceanapp
D/EGL_emulation: eglMakeCurrent: 0xa3f06500: ver 2 0 (tinfo 0xa3f035b0)
08-16 10:48:53.127 4914-5022/com.example.alexlevine.oceanapp
W/android.hardware.graphics.mapper@2.0::Mapper: getService: found null
hwbinder interface
08-16 10:48:53.129 4914-5022/com.example.alexlevine.oceanapp I/vndksupport:
sphal namespace is not configured for this process. Loading
/system/lib/hw/gralloc.ranchu.so from the current namespace instead.
08-16 10:48:53.239 4914-4921/com.example.alexlevine.oceanapp I/zygote: Do
partial code cache collection, code=60KB, data=49KB
08-16 10:48:53.239 4914-4921/com.example.alexlevine.oceanapp I/zygote: After
code cache collection, code=60KB, data=49KB
08-16 10:48:53.239 4914-4921/com.example.alexlevine.oceanapp I/zygote:
Increasing code cache capacity to 256KB
08-16 10:48:53.240 4914-4921/com.example.alexlevine.oceanapp I/zygote: Do
full code cache collection, code=60KB, data=66KB
08-16 10:48:53.241 4914-4921/com.example.alexlevine.oceanapp I/zygote: After
code cache collection, code=0B, data=22KB
08-16 10:48:53.441 4914-5022/com.example.alexlevine.oceanapp
D/EGL_emulation: eglMakeCurrent: 0xa3f06500: ver 2 0 (tinfo 0xa3f035b0)
08-16 10:48:53.456 4914-5016/com.example.alexlevine.oceanapp
D/EGL_emulation: eglCreateContext: 0xa13f85a0: maj 1 min 0 rcv 1
08-16 10:48:53.502 4914-5016/com.example.alexlevine.oceanapp
D/EGL_emulation: eglMakeCurrent: 0xa13f85a0: ver 1 0 (tinfo 0xa26647f0)
08-16 10:48:53.568 4914-4923/com.example.alexlevine.oceanapp I/zygote:
Waiting for a blocking GC ObjectsAllocated
08-16 10:48:53.574 4914-4923/com.example.alexlevine.oceanapp I/zygote:
WaitForGcToComplete blocked for 6.769ms for cause ObjectsAllocated
08-16 10:48:53.591 4914-5022/com.example.alexlevine.oceanapp
D/EGL_emulation: eglMakeCurrent: 0xa3f06500: ver 2 0 (tinfo 0xa3f035b0)
08-16 10:48:53.612 4914-5022/com.example.alexlevine.oceanapp
D/RenderScript HIDL Adaptation: IRenderScriptDevice::getService()
08-16 10:48:53.616 4914-5022/com.example.alexlevine.oceanapp
W/android.hardware.renderscript@1.0::Device: getService: found null hwbinder
interface
08-16 10:48:53.616 4914-5022/com.example.alexlevine.oceanapp
D/RenderScript HIDL Adaptation: IRenderScriptDevice::getService() returned
0x0
08-16 10:48:53.617 4914-5022/com.example.alexlevine.oceanapp
D/RenderScript HIDL Adaptation: Using Fallback Path.
08-16 10:48:53.658 4914-5022/com.example.alexlevine.oceanapp D/RenderScript:
Successfully queried cache dir:
/data/user_de/0/com.example.alexlevine.oceanapp/code_cache
08-16 10:48:53.658 4914-5022/com.example.alexlevine.oceanapp D/RenderScript:
Setting cache dir:
/data/user_de/0/com.example.alexlevine.oceanapp/code_cache
08-16 10:48:53.829 4914-4927/com.example.alexlevine.oceanapp I/zygote:
NativeAllocBackground concurrent copying GC freed 3145(241KB) AllocSpace
objects, 5(144KB) LOS objects, 50% free, 2MB/4MB, paused 6.862ms total
47.477ms
08-16 10:48:53.874 4914-5022/com.example.alexlevine.oceanapp
D/EGL_emulation: eglMakeCurrent: 0xa3f06500: ver 2 0 (tinfo 0xa3f035b0)
08-16 10:48:53.999 4914-4927/com.example.alexlevine.oceanapp I/zygote:
NativeAllocBackground concurrent copying GC freed 1640(91KB) AllocSpace
objects, 0(0B) LOS objects, 49% free, 2MB/4MB, paused 9.294ms total 44.961ms
08-16 10:48:54.272 4914-5020/com.example.alexlevine.oceanapp
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1

Process: com.example.alexlevine.oceanapp, PID: 4914

java.lang.RuntimeException: An error occurred while executing
doInBackground()

at android.os.AsyncTask$3.done(AsyncTask.java:325)

at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)

at java.util.concurrent.FutureTask.setException(FutureTask.java:252)

at java.util.concurrent.FutureTask.run(FutureTask.java:271)

at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)

at
java.util.concurrent.ThreadPoolExecutor.runWorker
(ThreadPoolExecutor.java:1162)

at
java.util.concurrent.ThreadPoolExecutor$Worker.run
(ThreadPoolExecutor.java:636)

at java.lang.Thread.run(Thread.java:764)

Caused by: com.google.gson.JsonSyntaxException:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line
1 column 1 path $

at com.google.gson.Gson.fromJson(Gson.java:873)

at com.google.gson.Gson.fromJson(Gson.java:826)

at com.google.gson.Gson.fromJson(Gson.java:775)

at
com.example.alexlevine.oceanapp.fetchSOCATData.doInBackground
(fetchSOCATData.java:67)

at
com.example.alexlevine.oceanapp.fetchSOCATData.doInBackground
(fetchSOCATData.java:29)

at android.os.AsyncTask$2.call(AsyncTask.java:305)

at java.util.concurrent.FutureTask.run(FutureTask.java:266)

at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)

at
java.util.concurrent.ThreadPoolExecutor.runWorker
(ThreadPoolExecutor.java:1162)

at
java.util.concurrent.ThreadPoolExecutor$Worker.run
(ThreadPoolExecutor.java:636)

at java.lang.Thread.run(Thread.java:764)

Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was
STRING at line 1 column 1 path $

at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:351)

at
com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read
(CollectionTypeAdapterFactory.java:80)

at
com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read
(CollectionTypeAdapterFactory.java:61)

at com.google.gson.Gson.fromJson(Gson.java:861)

at com.google.gson.Gson.fromJson(Gson.java:826)

at com.google.gson.Gson.fromJson(Gson.java:775)

at
com.example.alexlevine.oceanapp.fetchSOCATData.doInBackground
(fetchSOCATData.java:67)

at
com.example.alexlevine.oceanapp.fetchSOCATData.doInBackground
(fetchSOCATData.java:29)

at android.os.AsyncTask$2.call(AsyncTask.java:305)

at java.util.concurrent.FutureTask.run(FutureTask.java:266)

at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)

at
java.util.concurrent.ThreadPoolExecutor.runWorker
(ThreadPoolExecutor.java:1162)

at java.util.concurrent.ThreadPoolExecutor$Worker.run
(ThreadPoolExecutor.java:636)

at java.lang.Thread.run(Thread.java:764)
08-16 10:48:54.838 4914-5018/com.example.alexlevine.oceanapp
W/DynamiteModule: Local module descriptor class for
com.google.android.gms.googlecertificates not found.
08-16 10:48:54.870 4914-5053/com.example.alexlevine.oceanapp I/Process:
Sending signal. PID: 4914 SIG: 9

Here are the first few lines of my data: Note the complete one has many thousands of lines in rows:
{
 "table": {
    "columnNames": ["year", "longitude", "latitude", "fCO2_recommended",
"time"],
    "columnTypes": ["int", "double", "double", "double", "String"],
    "columnUnits": [null, "degrees_east", "degrees_north", "uatm", "UTC"],
    "rows": [
      [2015, -8.0721, -70.533, 394.45842722124314, "2015-01-01T00:00:01Z"],
      [2015, -8.0721, -70.533, 393.47776480047287, "2015-01-01T00:01:07Z"],
      [2015, -8.0721, -70.533, 394.12413998170973, "2015-01-01T00:02:16Z"],
      [2015, -8.0721, -70.533, 393.19812650057384, "2015-01-01T00:03:22Z"],
      [2015, -8.0721, -70.533, 393.06835948609546, "2015-01-01T00:04:28Z"],
      [2015, -8.0721, -70.533, 392.560674296763, "2015-01-01T00:05:35Z"]
     ]
  }
}

I just want to be able to get "rows" and use it as an array list. Please note that I do not have access to manipulate this data.
Here is the snippet of my code that's causing the problem:
Gson gson = new Gson();

Type collectionType = new
   TypeToken<Collection<OfficialSOCATPoint.TableBean>>() {}.getType();
Collection<OfficialSOCATPoint.TableBean> enums = gson.fromJson(result,
   collectionType);
SOCATCO2DataPoint.FeaturesBean[] protoExtract = enums.toArray(new
    SOCATCO2DataPoint.FeaturesBean[enums.size()]);
List<List<String>> dataArray = (List<List<String>>) protoExtract[3];

Thanks!

A: You defined table as a collection here Collection<OfficialSOCATPoint.TableBean>. Change it to single object:
TableBean table =  gson.fromJson(result, TableBean.class);


text:
Q: Reference request: Left $R/k$-modules In the paper titled:
On the module of differentials of a noncommutative algebra and symmetric biderivations of a semiprime algebra
I found the following definition:

Let $k$ be a commutative ring with an identity element, let $R$ be a $k$-algebra (not necessary with an identity element).
An additive abelian group $M$ is called a left $R/k$-module if it is a left R-module and a unitary $k$-module satisfying $a(xm) = (ax)m = x(am)$ for all $m \in M$, $x \in R$ and $a \in k$.

I search a reference (i.e. book) where I can find the definition of this kind of modules.
Thanks.

A: This is a very basic question. See e.g. Section 1.1 of the book:
R.S. Pierce: Associative algebras,  Graduate Texts in Mathematics, 88. Springer-Verlag, 1982.


text:
Q: how to Refresh Database and then put the new data in a simplecursoradapter in android? Mainactivity where I check the clicking of the refresh button
 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Will close the drawer if the home button is pressed
    if (drawerToggle.onOptionsItemSelected(item)) {
        return true;
    }

    switch (item.getItemId()) {
        case R.id.search:
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
                return false;
            } else {
                // Legacy search mode for Eclair
                onSearchRequested();
                return true;
            }
        case R.id.refresh:
            startDownloadSchedule();
            // TODO: resolve this
            Toast.makeText(getApplication(), "Updating database", Toast.LENGTH_SHORT).show();
            return true;
    }
    return false;
}

private void startDownloadSchedule() {

    progressBar.clearAnimation();
    progressBar.setIndeterminate(true);
    progressBar.setProgress(100);
    progressBar.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.fade_out));
    progressBar.setMax(100);
    progressBar.setVisibility(View.VISIBLE);
//JsonToDatabase gets data from google sheets in json format and then saves it in a database
    JsonToDatabase dataDownload = new JsonToDatabase(getApplicationContext());
    dataDownload.setOnJsonToDatabaseCallback(new JsonToDatabase.JsonToDatabaseCallback() {

        @Override
        public void onDataLoaded() {
            Toast.makeText(getApplication(), "done updating", Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.GONE);
            TracksListFragment tracksListFragment1 = new TracksListFragment();
            tracksListFragment1.onCreate(new Bundle());
        }

    });
    dataDownload.startDataDownload();
  }

TracklistFragment.class ( this is the activity whose data I want to refresh)
public class TracksListFragment extends SmoothListFragment {
//public String[] columns;
//public int[] to;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    displaydata();

}

public void displaydata() {
   String[] columns = new String[]{DatabaseHelper.TABLE_COLUMN_NAME, DatabaseHelper.TABLE_COLOUMN_INFORMATION};
    // THE XML DEFINED VIEWS WHICH THE DATA WILL BE BOUND TO
    int[] to = new int[]{R.id.textView_track_title, R.id.textView_track_information};
    DatabaseManager db = DatabaseManager.getInstance();
    if (getActivity() != null) {
        SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(
                getActivity(), R.layout.list_tracks, db.getTracks(), columns, to, CursorAdapter.NO_SELECTION);
        setListAdapter(mAdapter);
        Toast.makeText(getActivity(),"display data",Toast.LENGTH_SHORT).show();

    }

}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    String text = ((TextView) v.findViewById(R.id.textView_track_title)).getText().toString();
    Intent intent = new Intent(getActivity(), TrackActivity.class);
    intent.putExtra("TRACK", text);
    startActivity(intent);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    setEmptyText("No data present");
}

}
I am just stuck at how to display the new refreshed data. I have checked that the data gets downloaded. Any help would be appreciated. Thanks in advance.

A: Version the database. Add SharedPreferences for the database and increment it each time new data is added, then Call updateDb from Open helper.


text:
Q: Ng-init if array not yet created I'm trying to build a template for a application and want to display a dynamic list with names. so i got this code to show the list and add/remove rows;

        Company
        Contact
        Phone

            <input type="text" ng-model="row.name" />

            <input type="text" ng-model="row.contact" />

            <input type="text" ng-model="row.phone" />

            <button ng-click="page.businessRows.splice($index,1)">
                Remove
            </button>

<button class="btn" ng-click="page.businessRows.push({})">addRow</button>

the thing as that when this template is loaded page.busnessRows will most likely be loaded with rows so i want to change the ng-init to only create the empty array if businessRows is not initialised.
I have tried ng-init="page.businessRows = page.businessRows.length < 1 ? [] : page.businessRows but it did not work. How am i inteded to do conditions in jsangular expressions?
All help appreciated. Thanks in advance

A: I don't think the ng-init will evaluate conditional statements properly. But you could refactor the condition into a controller function and call the function from ng-init.

The just put your conditional evaluation in the function on the controller scope.

A: You can do this instead:

Update
I look at the parser code of AngularJS and notice that version 1.2 (currently RC) supports ternary expression.  So if you use AngularJS 1.2, this will also work (although more verbose than the above code):

See demo here.
However, your original code might not work if page.businessRows is null, because the parser will fail to dereference length property of null. So just be careful there.

A: I think you're trying to solve the wrong problem.
The problem is that you're allowing an action to occur before the data is loaded or ready.  A secondary problem is you're using an expression in an ng-click where a scope function or controller function should be.
So...

*

*Disable that button if the form isn't ready.

*Use your controller to control these interactions.

So here's an example of the controller. The $timeout was added to simulate a delayed load of data into your $scope.page variable.
app.controller('MyCtrl', function($scope, $timeout, $window) {
  //Timeout to simulate the asynchronous load
  //of the page object on the $scope
  $timeout(function(){
    $scope.page = {
      businessRows: []
    };
  }, 2000);

  //scope method to add a row.
  $scope.addRow = function (){
    //for safety's sake, check to see if the businessRows array is there.
    if($scope.page && angular.isArray($scope.page.businessRows)) {
      $scope.page.businessRows.push({});
    }
  };

  //scope method to remove a row
  $scope.removeRow = function(index, row) {
    if($window.confirm('Are you sure you want to delete this row?')) {
      $scope.page.businessRows.splice(index, 1);
    }
  };
});

... and the HTML view (notice the ng-disabled and the ng-click) (and lack of ng-init):

            Company
            Contact
            Phone

                <input type="text" ng-model="row.name" />

                <input type="text" ng-model="row.contact" />

                <input type="text" ng-model="row.phone" />

                <button ng-click="removeRow($index, row)">
                    Remove
                </button>

    <button class="btn" ng-disabled="!page" ng-click="addRow()">addRow</button>

Also, here's the obligatory Plunker for you to see this in action.


text:
Q: jdbc driver class not loaded when connecting to SAP HANA DB I have below logstash.conf which connects to SAP HANA DB
input {
    jdbc{
         jdbc_connection_string => "jdbc:sap://<host>:<port>"
         jdbc_driver_library => "/app/tomcat/jdbc_lib/ngdbc-2.4.61.jar"
         jdbc_driver_class => "com.sap.db.jdbc.Driver"
         jdbc_user => "xxx"
         jdbc_password => "xxx"
         statement => "SELECT coumn1 FROM table1 "
         use_column_value => true
         tracking_column => "NOMINEE_ID"
         tracking_column_type => numeric

    }
}

But when I starting logstash.conf, below error occurs. Does anyone have idea?
[2019-10-15T13:15:48,683][ERROR][logstash.javapipeline    ] A plugin had an unrecoverable error. Will restart this plugin.
  Pipeline_id:main
  Plugin: <LogStash::Inputs::Jdbc jdbc_user=>"xxx", use_column_value=>true, tracking_column=>"NOMINEE_ID", jdbc_password=><password>, statement=>"SELECT NOMINEE_ID, NOMINATION_ID, NOMINEE_USER_ID, READINESS, CREATED_DATE, CREATED_BY FROM SFBIZX3_TALSHELLEYH.SM_NOMINEE", tracking_column_type=>"numeric", jdbc_driver_library=>"/app/tomcat/jdbc_lib/ngdbc-2.4.61.jar", jdbc_connection_string=>"jdbc:sap://<host>:<port>", id=>"4a9ee1ee41b1f9376ca7e0c2d199233d62c0e09cd555272d527de0745ee102c8", jdbc_driver_class=>"com.sap.db.jdbc.Driver", enable_metric=>true, codec=><LogStash::Codecs::Plain id=>"plain_212f3f66-0328-42f0-87e0-7b078904b8e9", enable_metric=>true, charset=>"UTF-8">, jdbc_paging_enabled=>false, jdbc_page_size=>100000, jdbc_validate_connection=>false, jdbc_validation_timeout=>3600, jdbc_pool_timeout=>5, sql_log_level=>"info", connection_retry_attempts=>1, connection_retry_attempts_wait_time=>0.5, parameters=>{"sql_last_value"=>0}, last_run_metadata_path=>"C:\\Users\\I073341/.logstash_jdbc_last_run", clean_run=>false, record_last_run=>true, lowercase_column_names=>true>
  Error: com.sap.db.jdbc.Driver not loaded. Are you sure you've included the correct jdbc driver in :jdbc_driver_library?
  Exception: LogStash::ConfigurationError
  Stack: C:/elkstack/logstash-7.0.1/logstash-7.0.1/vendor/bundle/jruby/2.5.0/gems/logstash-input-jdbc-4.3.13/lib/logstash/plugin_mixins/jdbc/jdbc.rb:163:in `open_jdbc_connection'


text:
Q: Can someone check/revise my understanding of Blackberry development options? I'd like my Blackberry devices to get and possibly set data to the server, and am a little confused by all the options:
RIM-Push/Pap-Push. Use any library that is able to compose a HTTP GET request to the MDS-CS service (not MDS-IS).  This is a one way operation from the server to the device.

*

*RIM-Push  (Push a URL and or shorcut to a device for possible offline viewing)

*PAP-Push  (Same as above, BUT allows for message confirmation of delivery)

WebServices:  Use Visual Studio 2008 to create a Web Services only project.  I'm unclear if this is supported anymore, or if MDS-IS is used.  This is a 2 way operation.
MDS-IS: Use Eclipse to develop the applications and Java is required, I am unsure of what client libraries are able to do (2 way operation).
Let me know if missing any option, or if I need to revise my understanding of the basics

A: This is actually quite a broad question - there are a lot of ways for a BlackBerry device to interact with a server, and the ideal way depends heavily on your specific application.
Generally:
MDS Studio: the Visual Studio 2008 method is no longer actively supported.  It was a mostly visual forms designer, but not a great solution for a lot of reasons.  Basically, don't use it.
Mobile Web: Depending on what you need to do, this might work.  Everything server side.  The thing to be aware of (and why this doesn't work for a lot of problems) is that prior to BlackBerry 6 the browser wasn't very capable, either in terms of HTML support or JavaScript support.  You can, however, create shortcuts to mobile web sites which appear as icons on the BlackBerry homescreen.  And you can use BlackBerry Web Signals: http://na.blackberry.com/eng/developers/browserdev/websignals.jsp to push changes to mobile web pages to devices
Widgets: Supported in BlackBerry OS 5 and higher.  http://na.blackberry.com/eng/developers/browserdev/widgetsdk.jsp  These are packaged much like 'native' BlackBerry apps, but written using HTML and JavaScript.  Can be a good option for rapid development if you're ok with just targeting OS 5, and with the limitations of the BlackBerry Browser.  Lots of JavaScript hooks to system functions, so they give you more functionality than pure mobile web, and you can distribute them through App World and the like.
Java Apps: Most development work, but you get potentially the best user experience, and the most functionality.  Too broad a topic to cover adequately here, but there are a lot of questions related to these on SO and elsewhere.  A good starting point is the BlackBerry developer zone: http://www.blackberry.com/developers  RIM Push and PAP Push both fall into this category, as they interact with Java apps, though there are other methods that you can use to achieve similar results (client polling, or I've even seen SMS or email used to push info or wake up a client, though this isn't recommended by RIM).
For a deeper overview of the options I'd recommend a book by my friend John Wargo, called BlackBerry Development Fundamentals.  He covers the various options pretty well.


text:
Q: Caption numbering in Word 2010 The page numbering format can be different for each sections of a Word document.
For example: section 1 will have roman numbers (I, ii) and section 2 will have numbers that have "Include chapter number" (1-1, 2-3).
I cannot change the caption format the same way.
What I need is that each section will have a different "Numbering" > "Include chapter number" > "Chapter start with style" type.
For example:
I have a Word file that has a Main part that includes Headings 1-4. Figure captions are then Figure 1-1, Figure 1-3, Figure 3-2.
The second part of the file includes appendices, for which I want the figure captions to be Figure A-1, Figure A-3, Figure C-2.
Is there a way to do this without manually changing something? This is a large manual that is updated with different figures being added to both the main and appendix sections.

A: 1. You can base the caption numbers on the respective chapter numbers (by inserting chapters as the first part of the number):

and then:

This will place the chapter number in front of the caption number
2. You can use another type of Captions for each section:

They still can all go into one table, as the table can be built by format style.

A: Posted the question also in the Microsoft community, and received the following very helpful reply:
Since captions can only be restarted following one of the built-in styles, you will have to use (say) Heading 7 for appendix titles. Create a separate caption label for use with that heading. For details, see http://www.shaunakelly.com/word/numbering/numberingappendixes.html.


text:
Q: Problem building a ANN Regressor model with Autoencoder in Tensorflow 2.11 My input is a 2D numpy array of dimensions (364660, 5052). The target is (364660, 1), a regression variable. I a trying to build a guided autoencoder + ANN regressor where encoded layer of autoencoder serves as input to ann regressor. I would like to train both models at one go. However, the loss for autoencoder should be a combined autoencoder loss + ann loss. Where as ANN loss remains the same. Here is my sample code
class AutoencoderRegressor(tf.keras.Model):
    def __init__(self, encoder_layers, decoder_layers, regressor_layers, autoencoder_loss_weights):
        super(AutoencoderRegressor, self).__init__()
        self.autoencoder = tf.keras.models.Sequential(encoder_layers + decoder_layers)
        self.regressor = tf.keras.models.Sequential(regressor_layers)
        self.autoencoder_loss_weights = autoencoder_loss_weights

    def call(self, inputs, training=None, mask=None):
        autoencoder_output = self.autoencoder(inputs)
        regressor_input = self.autoencoder.get_layer(index=2).output
        regressor_output = self.regressor(regressor_input)
        return autoencoder_output, regressor_output

    def autoencoder_loss(self, autoencoder_output, inputs):
        binary_crossentropy = tf.keras.losses.BinaryCrossentropy()
        mean_squared_error = tf.keras.losses.MeanSquaredError()
        autoencoder_reconstruction_loss = binary_crossentropy(inputs, autoencoder_output)
        autoencoder_regression_loss = mean_squared_error(inputs, autoencoder_output)
        #autoencoder_loss = self.autoencoder_loss_weights[0] * autoencoder_reconstruction_loss + self.autoencoder_loss_weights[1] * autoencoder_regression_loss
        autoencoder_loss = autoencoder_reconstruction_loss+autoencoder_regression_loss

        return autoencoder_loss

    def regressor_loss(self, regressor_output, targets):
        mean_squared_error = tf.keras.losses.MeanSquaredError()
        regressor_loss = mean_squared_error(targets, regressor_output)
        return regressor_loss

# define the encoder layers
encoder_layers = [
tf.keras.layers.Dense(64, activation='relu', input_shape=(reduced_x_train2.shape[1],)),
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dense(16, activation='relu')]

# define the decoder layers
decoder_layers = [
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(reduced_x_train2.shape[1], activation='sigmoid')]

# define the regressor layers
regressor_layers = [
tf.keras.layers.Dense(8, activation='relu', input_shape=(16,)),
tf.keras.layers.Dense(1, activation='linear')]

# define the
autoencoder_loss_weights = [0.8, 0.2]

autoencoder_regressor = AutoencoderRegressor(encoder_layers, decoder_layers,    regressor_layers, autoencoder_loss_weights)

autoencoder_regressor.compile(optimizer='adam', loss=[autoencoder_regressor.autoencoder_loss, autoencoder_regressor.regressor_loss])

autoencoder_regressor.fit(reduced_x_train2, [reduced_x_train2, y_train], epochs=100,
                      batch_size=32, validation_split=0.9,shuffle =True,
                     verbose = 2)

I get the following error:
TypeError                                 Traceback (most recent call last)
Input In [14], in <cell line: 60>()
56 autoencoder_regressor = AutoencoderRegressor(encoder_layers, decoder_layers, regressor_layers, autoencoder_loss_weights)
58 autoencoder_regressor.compile(optimizer='adam', loss=[autoencoder_regressor.autoencoder_loss, autoencoder_regressor.regressor_loss])
---> 60 autoencoder_regressor.fit(reduced_x_train2, [reduced_x_train2, y_train], epochs=100,
61                           batch_size=32, validation_split=0.9,shuffle =True,
62                          verbose = 2)
TypeError: in user code:
File "/user/iibi/amudireddy/.conda/envs/tfni10_py38/lib/python3.8/site-packages/keras/engine/training.py", line 1051, in train_function  *
    return step_function(self, iterator)
File "/user/iibi/amudireddy/.conda/envs/tfni10_py38/lib/python3.8/site-packages/keras/engine/training.py", line 1040, in step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/user/iibi/amudireddy/.conda/envs/tfni10_py38/lib/python3.8/site-packages/keras/engine/training.py", line 1030, in run_step  **
    outputs = model.train_step(data)
File "/user/iibi/amudireddy/.conda/envs/tfni10_py38/lib/python3.8/site-packages/keras/engine/training.py", line 890, in train_step
    loss = self.compute_loss(x, y, y_pred, sample_weight)
File "/user/iibi/amudireddy/.conda/envs/tfni10_py38/lib/python3.8/site-packages/keras/engine/training.py", line 948, in compute_loss
    return self.compiled_loss(
File "/user/iibi/amudireddy/.conda/envs/tfni10_py38/lib/python3.8/site-packages/keras/engine/compile_utils.py", line 215, in __call__
    metric_obj.update_state(loss_metric_value, sample_weight=batch_dim)
File "/user/iibi/amudireddy/.conda/envs/tfni10_py38/lib/python3.8/site-packages/keras/utils/metrics_utils.py", line 70, in decorated
    update_op = update_state_fn(*args, **kwargs)
File "/user/iibi/amudireddy/.conda/envs/tfni10_py38/lib/python3.8/site-packages/keras/metrics/base_metric.py", line 140, in update_state_fn
    return ag_update_state(*args, **kwargs)
File "/user/iibi/amudireddy/.conda/envs/tfni10_py38/lib/python3.8/site-packages/keras/metrics/base_metric.py", line 449, in update_state  **
    sample_weight = tf.__internal__.ops.broadcast_weights(
File "/user/iibi/amudireddy/.conda/envs/tfni10_py38/lib/python3.8/site-packages/keras/engine/keras_tensor.py", line 254, in __array__
    raise TypeError(

TypeError: You are passing KerasTensor(type_spec=TensorSpec(shape=(), dtype=tf.float32, name=None), name='Placeholder:0', description="created by layer 'tf.cast_15'"), an intermediate Keras symbolic input/output, to a TF API that does not allow registering custom dispatchers, such as 'tf.cond, 'tf.function', gradient tapes, or 'tf.map_fn'. Keras Functional model construction only supports TF API calls that *do* support dispatching, such as 'tf.math.add' or 'tf.reshape'. Other APIs cannot be called directly on symbolic Kerasinputs/outputs. You can work around this limitation by putting the operation in a custom Keras layer 'call' and calling that layer on this symbolic input/output.

Where am I going WRONG?
###EDITED question. I missed an implementation requirement.
In autoencoder_loss, autoencoder_reconstruction_loss should take inputs as (inputs, autoencoder_output) and autoencoder_regression_loss should take input as (targets, regressor_output)
I am not to sure how to implement this. Please help.

A: It seems you can't access a submodel's output layer from within your model like you did with the line regressor_input =self.autoencoder.get_layer(index=2).output. However, here is an alternative that works:
import numpy as np
import tensorflow as tf

class AutoEncoderRegressor(tf.keras.Model):
    def __init__(self, encoder, decoder, regressor, loss_weights):
        super(AutoEncoderRegressor, self).__init__()
        self.encoder = encoder
        self.decoder = decoder
        self.regressor = regressor
        self.loss_weights = loss_weights

    def call(self, inputs, training=None, mask=None):
        encoded = self.encoder(inputs)
        decoded = self.decoder(encoded)
        regression = self.regressor(encoded)
        return decoded, regression

    def autoencoder_loss(self, autoencoder_output, inputs):
        return tf.keras.losses.BinaryCrossentropy()(inputs,autoencoder_output)

    def regressor_loss(self, regressor_output, targets):
        return tf.keras.losses.MeanSquaredError()(targets, regressor_output)

def main():
    input_dim = 10

    # generate random training data
    rng = np.random.default_rng()
    X   = rng.random((100,input_dim))
    y   = [X, rng.random((100,1))]

    encoder = tf.keras.Sequential([
        tf.keras.layers.Dense(64, activation='relu', input_shape=(input_dim,)),
        tf.keras.layers.Dense(32, activation='relu'),
        tf.keras.layers.Dense(16, activation='relu')
    ])

    decoder = tf.keras.Sequential([
        tf.keras.layers.Dense(32, activation='relu'),
        tf.keras.layers.Dense(64, activation='relu'),
        tf.keras.layers.Dense(input_dim, activation='sigmoid')
    ])

    regressor = tf.keras.Sequential([
        tf.keras.layers.Dense(8, activation='relu', input_shape=(16,)),
        tf.keras.layers.Dense(1, activation='linear')
    ])

    model = AutoEncoderRegressor(encoder, decoder, regressor, loss_weights=[0.8, 0.2])
    model.compile(
        optimizer = 'adam',
        loss = [model.autoencoder_loss, model.regressor_loss],
        loss_weights = model.loss_weights
    )

    model.fit(X,y,
      epochs = 100,
      batch_size = 32,
      validation_split = 0.9,
      shuffle = True,
      verbose = 2
    )

if __name__ == "__main__":
    main()

I used random training data with smaller dimensions for testing here, adjust this to your actual dataset.
EDIT Just for clarification: your model has 2 loss functions for its 2 outputs. You don't have to add those together yourself, because Tensorflow will do this automatically. With the loss_weights you've provided, the total loss of the model will be
total_loss = 0.8*autoencoder_loss+0.2*regressor_loss

Here, autoencoder_loss is the binary cross-entropy between X_true and X_pred and regressor_loss is the mean squared error between y_true and y_pred.


text:
Q: can't verify selected checkbox, Selenium Webdriver Java In my test I want to verify selected checkbox. Below is my code
if (CheckboxForFirstCitizenship.isSelected()) {
        System.out.println("Checkbox selected");
    } else {
        System.out.println("Checkbox not selected");
    }
    if (CheckboxForSecondCitizenship.isSelected()) {
        System.out.println("Checkbox selected");
    } else {
        System.out.println("Checkbox not selected");
    }

Web elements I have in PageObjects class
@FindBy(xpath = "/html[1]/body[1]/ufe-root[1]/div[1]/div[1]/div[1]/ng-component[1]/div[1]/ufe-klient[1]/app-dashboard[1]/main[1]/div[1]/div[2]/app-individual-client-edit-container[1]/app-process-container[1]/app-local-loader[1]/div[1]/div[3]/app-individual-client-edit-client-data[1]/app-form-container[1]/p-accordion[1]/div[1]/p-accordiontab[1]/div[2]/div[1]/div[2]/div[1]/app-form-data-set-container[1]/div[1]/div[1]/app-individual-client-edit-personal-data-form[1]/app-data-container[1]/div[1]/div[2]/app-container-state[1]/div[1]/form[1]/div[1]/div[8]/div[1]/div[1]/app-individual-client-edit-citizenship-form[1]/div[2]/p-checkbox[1]/div[1]/div[2]")
@CacheLookup
public WebElement CheckboxForFirstCitizenship;

@FindBy(xpath = "/html[1]/body[1]/ufe-root[1]/div[1]/div[1]/div[1]/ng-component[1]/div[1]/ufe-klient[1]/app-dashboard[1]/main[1]/div[1]/div[2]/app-individual-client-edit-container[1]/app-process-container[1]/app-local-loader[1]/div[1]/div[3]/app-individual-client-edit-client-data[1]/app-form-container[1]/p-accordion[1]/div[1]/p-accordiontab[1]/div[2]/div[1]/div[2]/div[1]/app-form-data-set-container[1]/div[1]/div[1]/app-individual-client-edit-personal-data-form[1]/app-data-container[1]/div[1]/div[2]/app-container-state[1]/div[1]/form[1]/div[1]/div[8]/div[1]/div[2]/app-individual-client-edit-citizenship-form[1]/div[2]/p-checkbox[1]/label[1]")
@CacheLookup
public WebElement CheckboxForSecondCitizenship;

In test result I have two printlines 'Checkbox not selected' despite of firstCheckox is selected. What I'm doing wrong? Can someone help?

            <input type="checkbox" name="undefined" value="undefined">

    Główne

A: To be able to use isSelected method, you have to address to the input type="checkbox" element.
Use css selector #main-citizenship-checkbox-0 input for the first checkbox.
Probably for the second one, it will be #main-citizenship-checkbox-1 input.
@FindBy(css = "#main-citizenship-checkbox-0 input")
@CacheLookup
public WebElement checkboxForFirstCitizenship;


text:
Q: Bulk Upload PDF Forms to AEM Repository We recently began using Adobe LiveCycle and Adobe Experience Manager. We're not using AEM for our web site, however. We're just wanting to use the Forms Portal portion of it to allow us to organize our forms, tag them, etc, then provide a searchable interface.
We have several hundred pre-AEM/LiveCycle PDF forms. Rather than manually uploading one PDF file at a time, we would like to do a bulk upload into the repository.
If I remember correctly, I saw someone do this using CRXDE Lite, navigating to /content/dam/formsanddocuments, then dragging the documents in. However, when I try that, it just opens up Acrobat Reader to display the PDF.
Any help would be greatly appreciated!

A: I'm not sure about drag/drop in the browser (never tried it), but there are a couple of methods you could use:
Curl / Bash
If you're happy scripting this in Bash, one method is to use curl to upload the file, along the lines of:
curl -F"./*=@form1.pdf" \
     -F"./*@TypeHint=nt:file" \
http://admin:admin@localhost:4502/content/dam/forms/form1

For example, you could create a script to loop over all the PDFs in your directory & upload them one at a time.
VLT
Another option would be to add create a content package with Maven, build it and install via CRX Package Manager.
Or you could use the Filevault (VLT) tool that Adobe provide as a VCS-style link between your file system & the repository — checkout to a directory, add the PDFs in and then do a vlt add; vlt ci to push them back into AEM.
WebDav
AEM supports mounting the repository via WebDav, so that you could drag the files in using Finder/Explorer.
It can be slow, but if you're just doing a one-off dump of files into AEM, it could be an option.


text:
Q: Why setup time is greater than hold time? One of my friend was asked this question in an interview. What should be the answer?
One more question how hold time can be negative?

A:
Why setup time is greater than hold time?

Who says that it is? It depends very much on the design of a particular sequential circuit.
However, it is often desirable for setup time to be greater than hold time (or put another way, for hold time to be as low as possible), because this means that you can cascade FFs directly to create shift registers, etc. without having to worry about metastability.

How can hold time be negative?

You can trade off between setup and hold time by adding a delay in either the data input path or the clock input path. If the delay that you add to the data is greater than the FF's actual hold time requirement, the overall hold time requirement for the combination can be negative.

A: Why setup time is greater than hold time?
This is true in most cases and it mainly depends on the architecture of Flip Flop being used. Consider the master slave flip flop below:

The propagation delay of the darkened path (fig 1) is the setup time. When the clock goes high, the path WXYZ forms a loop propagating the data that was floating at Z at the moment and we have to make sure that D has gone all the way to Z before clock goes high. Hence the setup time constraint.

For hold time, the darkened path in the above picture (fig 2) is only considered. when the clock toggles high, it takes some delay for T1 to shut off and we have to make sure only the right value of D goes through to W. So, the value of D should remain constant for the period equivalent to the delay of T1 minus the delay of the inverter before T1.
Hold time could be NEGATIVE if the delay of the inverter is greater than the delay of T1.


text:
Q: Calendar notification on macOS not going away The calendar app on macOS Big Sur keeps showing me a red (1) notification icon that is not going away:

I don't know what entry is causing the notification. The invitation list is empty. I tried resetting the Exchange account but the badge came back up. I tried resetting the dock as well to no avail.
Any suggestions?
EDIT: as it turns out, the notification disappeared as magically as it turned up. I'll leave open this thread anyway in case anyone finds any non-magical solutions that (s)he wishes to share here.


text:
Q: Spark Streaming Kafka direct consumer consumption speed drop
Kafka direct consumer started to limit reads to 450 events(5 * 90 partitions) per batch (5 seconds), it was running fine for 1 or 2 days before that (about 5000 to 40000 events per batch)
I'm using spark standalone cluster (spark and spark-streaming-kafka version 1.6.1) running in AWS and using S3 bucket for checkpoint directory StreamingContext.getOrCreate(config.sparkConfig.checkpointDir, createStreamingContext), there are not scheduling delays and enough disk space on each worker node.
Didn't change any Kafka client initialization parameters, pretty sure that kafka's structure hasn't changed:
val kafkaParams = Map("metadata.broker.list" -> kafkaConfig.broker)
val topics = Set(kafkaConfig.topic)
val stream = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](
  ssc, kafkaParams, topics)

Also can't understand why when direct consumer description says The consumed offsets are by the stream itself I still need to use checkpoint directory when creating the streaming context?

A: This is usually the result of enabling backpressure via the setting spark.streaming.backpressure.enabled to true. Usually, when the backpressure algorithm sees that there's more data coming in then it's used to, it starts capping each batch to a rather small size until it can "stabilize" itself again. This sometimes has false positives and causes your stream to slow down the processing rate.
If you want to tweak the heuristic a little, there are some undocumented flags it is using (just make sure you know what you're doing):
val proportional = conf.getDouble("spark.streaming.backpressure.pid.proportional", 1.0)
val integral = conf.getDouble("spark.streaming.backpressure.pid.integral", 0.2)
val derived = conf.getDouble("spark.streaming.backpressure.pid.derived", 0.0)
val minRate = conf.getDouble("spark.streaming.backpressure.pid.minRate", 100)

If you want the gory details, PIDRateEstimator is what you're looking for.


text:
Q: How to parse a string containing equal signs to object I have a string variable
let stringValue = "{DATA={VERSION=1.1, STATE=true, STATUS=ONLINE}}"

I would like to parse it to object as result where result will be:
let result = {"DATA":{"VERSION":1.1, "STATE": true, "STATUS": "ONLINE"}}

How would you convert a stringValue to result object so it would be possible to access the nested keys?
console.log(result.DATA.STATUS)

A: Under the assumption that keys and string values are fully capitalized:

*

*I used the regex /[A-Z]+/g and .match(regex) to get an array of every all caps word in the string.

*Create a Set out of the the array to remove duplicates and avoid repeating the next step on the same string multiple times.

*Then iterate over each word and replace it in the main string with itself between quotes. DATA => "DATA"

*Then replace = with :

*And finally JSON.parse() and we get the object.

let stringValue = "{DATA={VERSION=1.1, STATE=true, STATUS=ONLINE}}";

let regex = /[A-Z]+/g
let objectStrings = stringValue.match(regex)
let uniqueStrings = [... new Set(objectStrings)]

uniqueStrings.forEach((string) => stringValue = stringValue.replaceAll(string, '"'+string+'"'));
stringValue  = stringValue.replaceAll('=', ':');

console.log(JSON.parse(stringValue))

Here it is in JSBin to show that the keys are properly assigned without the quotes.


text:
Q: pagination/prev and next page links not showing $('a.prev, a.next').click(function(){
var a = $(this),
    current = $('#pagin li a.current'),
    page = parseInt(current.text());
if (a.hasClass('prev')) {
    page--;
    if (page < 1) page = 1;
} else if (a.hasClass('next')) {
    page++;
    if (page > pageCount) page = pageCount;
}
$('.page:eq(' + (page - 1) + ')').click();
});

This not working. Please help me..
How to add next and previous buttons in this code.
Please see Js fiddle link: http://jsfiddle.net/jfm9y/609/

A: You needed to declare the pageCount of the content.
Working example : http://jsfiddle.net/jfm9y/611/
pageSize = 1;
pageCount = $(".content").length;

showPage = function(page) {
    $(".content").hide();
    $(".content").each(function(n) {
        if (n >= pageSize * (page - 1) && n < pageSize * page)
            $(this).show();
    });
}

showPage(1);

$("#pagin li a").click(function() {
    $("#pagin li a").removeClass("current");
    $(this).addClass("current");
    showPage(parseInt($(this).text()))
});
    $('a.prev, a.next').click(function(){
    var a = $(this),
        current = $('#pagin li a.current'),
        page = parseInt(current.text());
        console.log(page);
    if (a.hasClass('prev')) {
        page--;
        if (page < 1) page = 1;
    } else if (a.hasClass('next')) {
        page++;
        if (page > pageCount) page = pageCount;
    }

    $($('#pagin li a')[page- 1]).click();
});