text:
Q: Call order after starting a programm Can anybody explain to me the order of the output? Especially, what the "this(D()1" in the constructor causes?
Are there some "rules" ijn which order which variable is declared? (static/instance and so on)
Sorry for my bad english.

A: A Java program executes from the top down in the main()-method. From there it does whatever the code tells it to do. In your case, it can be summarized as follows:

*

*Prints the line to console.

*When creating a new Dog, its superclass (Mammal) must first be created. The this("D(2)") calls the other constructor of class Dog.

*From there the superclass Mammal is instantiated, since it extends DomesticAnimal, that must be created first. and since the variable da is declared to be initialized outside the constructor, it is done first.

*The constructor completes and prints the line.

*The rest of Mammal is instantiated, same as in (3)

*The line is printed after the super class is successfully instantiated. Same as (4)

*With all super classes created, class Dog's attribute outside the constructor is initialized. Same as in (5) and (3).

*Line is printed. Same as (6) and (4)

*The other constructor method has competed, so the rest of the initially called constructor executes. I.e. the line is printed.


text:
Q: How do I split the $0 variable to find directory and relative paths in bash? The $0 variable contains the path info of the script.

*

*How can I change the path info to absolute path? I mean how to process ~, ., .. or similar?

*How can I split the path info into directory and file name?

I could use python/perl for this, but I want to use bash if possible.

A: Using dirname and basename like mentioned by Michael should be the safest way to get what you want.
Anyway if you really want to do this with "bash only tools" you could use parameter substitution:
echo `basename $PWD`        # Basename of current working directory.
echo "${PWD##*/}"           # Basename of current working directory.
echo
echo `basename $0`          # Name of script.
echo $0                     # Name of script.
echo "${0##*/}"             # Name of script.
echo
filename=test.data
echo "${filename##*.}"      # data
                            # Extension of filename.

This example is directly taken from the Advanced Bash Scripting Guide which is worth a look.
The explanation is pretty simple:

${var#Pattern} Remove from $var the
  shortest part of $Pattern that matches
  the front end of $var. ${var##Pattern}
  Remove from $var the longest part of
  $Pattern that matches the front end of
  $var.

Look at the pattern like some regex and the # or ## as some kind of greedy/non-greedy modifier.
This might become useful if you will have to do some more complicated extractions of a paths part.

A: realpath is a command which tells you the real path (removes .. and symbolic links etc.)
It is standard with FreeBSD. According to this discussion it's also available for Linux:
http://www.unix.com/shell-programming-scripting/89294-geting-real-path.html
That discussion also offers a bash solution:
$ bash -c "cd /foo/../bar/ ; pwd"

A: You don't need to process things like ~, the shell does it for you. That's why you can pass ~/filename to any script or program and it works -- all those programs don't handle ~ themselves, your shell converts the argument to /home/username/filename and passes that to the program instead:
$ echo ~/filename
/home/mrozekma/filename

If you need a canonical filename (one that doesn't include things like ..), use realpath (thanks Neil):
$ realpath ~/../filename
/home/filename

As for splitting the path into directory name and filename, use dirname and basename:
$ dirname /foo/bar/baz
/foo/bar

$ basename /foo/bar/baz
baz

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to assign class based on regexp match (sorting in perl) I am reading from file. Based on value in one column, I want to assign my own class/tag to it.
These regexps:
'LTR*','MLT*','MST*' ...
 belong to the class HERV.
'Charlie*','Looper*' ...
belong to the class DNA
Right now I have two arrays, one with regexps and one with respective classes:
 my @array = map { qr{$_} } ('Alu*', 'HERV*', 'Charlie*' ...
 my @classes = ('Alu', 'HERV', 'DNA', 'LINE' ...

So that I know that if my line matches Charlie*, it belongs to the class DNA.
To sum it up, for every line of the file I am looping the whole array and looking for match:
for my $i (0 .. $#array) {

        if ($type =~ m/$array[$i]/) {
                       my $class=$classes[$i];
        }

}

Of course, this is not too clever. It would be much better to say: "this group of regexps belongs to this class" which suggests use of hash.
However, I consider it quite inconvenient to loop all lines, than all keys of hashmap and then all values of certain keys and, when there is a match, use the key as the resulting class/tag. Is this good solution or not?
Thank you very much.

A: You can do something like this:
my %re = (
       HERV=>qr/LTR|MLT|MST/,
       DNA=> qr/Charlie|Looper/
   );
my $class;
for (keys %re) {
    $class = $_, last if ($type =~ $re{$_});
}

This will save you some regex compilation and one loop.

A: The CPAN module Text::Prefix::XS appears to do what you want:  determine which if any of a list of prefixes match a given text.  I have not used the module, but from what I can tell you would do something like:
my %prefix2class = ( LTR => 'HERV',
                     MLV => 'HERV',
                     ...
                     Charlie => 'DNA' );

my $search = prefix_search_create( keys %prefix2class );

# ... now, for a given $type, no need to loop ...
my $pfx = prefix_search($search, $type);
my $class = $prefix2class{$pfx};

(Note:  Your regexes look to me like shell-style/fnmatch-style patterns dubiously compiled as regexes, and from this I infer that you actually want simple prefix matching.  Otherwise, the regex /Charlie*/, for example, would match Charli, Charlieeee, fooCharliebar, and so on — that seems unlikely to be representative of your "value in one column".)


text:
Q: Angular/2 : angular2-select populate from observable I'm using https://www.npmjs.com/package/angular2-select package. I'm trying to populate the select tag with the value of "tagOptions" which is populated as follows:
I'm subscribing to an observable and formatting the returned data in the subscribe as follows:
/**
 * Load all available tags
 */
private getTags() : void {

    // The observable
    this.tagService.tags$
    .subscribe( (tags) => {

        for (var i = 0; i < tags.length; i++) {

            this.tagOptions.push({ value: tags[i].id, label: tags[i].name });
        }

        this.variantForm.patchValue({
            tags: this.tagOptions
        });
    });

    let criteria = {columns: ['id','name']};
    // Make an ajax request and populate the observable
    this.tagService.load(this.utilityService.encode(criteria))
    .subscribe();
}

My template reads as
<ng-select
    [options]="tagOptions"
    placeholder="Select one"
    multiple="true"
    allowClear="true"
    formControlName="tags">
</ng-select>

My template bombs out on page load with
"core.umd.js:3462 EXCEPTION: Cannot set property 'selected' of undefined"
I suspect my approach to populating the select is incorrect. Any advice is appreciated.

A: The <ng-select> seems to not reflect changes to its [options] input after it has been rendered. To get around this, you'll need to have the data ready to go before the <ng-select> is rendered. The angular route guard 'resolve' function does exactly that. If you make the resolve function wait on a subscription, then the page will not be rendered until the data is available.
Link to Router resolve guide.
Happy coding :)

A: With ng-select (as angular2-select is now called) you can pass an observable and add  | async to your options as such:
<ng-select
    [options]="tagOptions | async"
    placeholder="Select one"
    multiple="true"
    allowClear="true"
    formControlName="tags">
</ng-select>

This seems to work better.
See https://ng-select.github.io/ng-select#/data-sources


text:
Q: android: how to set listener for Viewgroup and its child views at the same time? I'm using a customized adapter for my listview. Here is the code:
    public class ContentAdapter extends ArrayAdapter<Content>{

    private ArrayList<Content> items;

    public ContentAdapter(Context context, int textViewResourceId, ArrayList<Content> objects) {
        super(context, textViewResourceId, objects);
        this.items=objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v=convertView;
        if (v==null){
            LayoutInflater inflater=(LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v=inflater.inflate(R.layout.list_items_layout, null);
        }
        Content content=items.get(position);
        if (content!=null){
            TextView nm=(TextView)v.findViewById(R.id.itemname);
            TextView sm=(TextView)v.findViewById(R.id.itemsubname);
            nm.setTextColor(Color.RED);
            nm.setText(content.getName());
            sm.setTextColor(Color.GRAY);
            sm.setText(content.getSubname());
        }
        return v;
    }

R.layout.list_items_layout:
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants">

<TextView android:id="@+id/itemname"
    android:textIsSelectable="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:textSize="20sp"/>

<TextView android:id="@+id/itemsubname"
    android:textIsSelectable="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:textSize="15sp"/>

When I used setOnItemClick(listener) to create the listener for my listview, although the listener was set,it can only recognize when I click the blank part of the viewgroup. If I click on any of the two TextView, it just can't respond.
Is there any ways to set a OnItemClickListener that can monitorthe viewgroup and its child views at the same time?


text:
Q: Помочь переписать с C++ Builder на СИ. Здравствуйте!
Вся суть описана тут:
http://www.cyberforum.ru/cpp-builder/thread1093527.html
Если можете, пишите тут, свяжемся. Оплатить работу готов. Делаем параллельно, по скайпу или почте и т.д.
Т.е. Вы говорите, я делаю.
Спасибо.
A: Вы уверены, что это не бредовая затея? Ну я еще понял бы переписать на Java или С#, но переписывать с С++ на С да еще и в консоль! Как это вы собираетесь графический интерфейс реализовывать в консоли? Не проще ли уделить пару дней и изучить основы С++, чем изобретать велосипед на С? Тем более, что эти 300 строк на плюсах, чтобы получить хотя бы похожий функционал перерастут не в щдну тысячу строк сишного кода


text:
Q: Stacking font symbols and aligning the spaces around a font using html5/css I am trying to insert a symbol at a fixed position and stack another symbol over it using font-symbols. But the spacing around the font is preventing me to do so. (note the symbol is from unicode-font)
So far I have tried adjusting z-index and line-height, which enable me to adjust the height of the total space taken by the element and the font but they are still misaligned. I have tried adjusting the positioning or vertical alignment. What other alignment modification can be done with the font itself?
Here is the code:
#back
{
font-size: 15em;
font-weight:100;
line-height:1.15em;
height:0.9em;
padding: 0;
margin: 0;
border: 1px solid black;
vertical-align: bottom;
 z-index:300;
 position:fixed;
 top:155px;
 background-color:white;
 }

#front {
font-size: 15em;
font-weight:100;
line-height:1.15em;
height:0.9em;
padding: 0;
margin: 0;
border: 1px solid black;
vertical-align: bottom;
 z-index:1000;
 position:fixed;
 top:165px;
 left:30px;
 background-color:white;
 }

https://jsfiddle.net/gns07zax/

A: The icons are offset in the actual font itself . Considering they're essentially 'text' in this regard, you can offset them by making use of the line-height property.
Note that your snippet has a number of incorrect selectors, such as the omission of the hastag in the ID selectors. However, I assume you're trying to align the cards to their boxes, and you're looking for a value of about 186px.
Here's a minimal example showcasing this:

* {
  font-family: "Segoe UI", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif;
}

h1 {
  font-size: 15em;
  font-weight: 100;
  line-height: 1.15em;
  height: 0.9em;
  padding: 0;
  margin: 0;
  border: 1px solid black;
  vertical-align: bottom;
}

#back {
  position: fixed;
  background-color: white;
}

#front {
  position: fixed;
  left: 180px;
  background-color: white;
}

#back, #front {
  line-height: 186px;
}

&#127137

&#x1F0A1

You may need to change positioning to suit.
However, you may find it more beneficial to change the height to 1em, which will allow the cards to be fully contained by their borders. In this case, you're looking for 0.875em for the line-height.
Here's a minimal example showcasing this:

* {
  font-family: "Segoe UI", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif;
}

h1 {
  font-size: 15em;
  font-weight: 100;
  line-height: 1.15em;
  height: 1em;
  padding: 0;
  margin: 0;
  border: 1px solid black;
  vertical-align: bottom;
}

#back {
  position: absolute;
  background-color: white;
}

#front {
  position: absolute;
  left: 180px;
  background-color: white;
}

#back, #front {
  line-height: 0.875em;
}

&#127137

&#x1F0A1

Hope this helps! :)


text:
Q: scss class variables visibility Hey guys  im making a calculator app and im trying to add a class for a "main". So basically i made a working script in JS which allows me to switch between several "main" classes (depends on what color theme i click). Unfortunately it does not see variables inside a class ".dark" (and probably other ones as well). When i put them in global scope it obviously works but not inside theme classes. Themes are placed inside additional scss file. Im probably making a stupid mistake but cant figure it out.
live site:  https://adrian397.github.io/frontEndMentorChallenges/calculator-app-main/index.html
Have a look at my github repo to view the files:
https://github.com/Adrian397/frontEndMentorChallenges/tree/master/calculator-app-main
The problem is between style.scss and _themes.scss


text:
Q: Beginner question : logic and set theory First post on here, and apologies for its very basic content (I don't even understand most of the questions on here) but I'm wondering if anyone can help. I'm trying to teach myself maths at the ripe old age of 47, and wanted to start quite basic, with a book called "Advanced precalculus" by Daniel Kim. I liked the proposed approach, which is more theoretical and proof based than any of the other precalculus stuff I've come across (which I have gone through before, but it never seems to stick as the books never explain why stuff works).
I've stumbled across something that's got be stumped though. One of the problems right at the start asks the reader to evaluate the truth of falsity of $A \subseteq B \cup C \to A \subseteq B \lor A \subseteq C$
I looked at this and doodled a Venn diagram and concluded that it had to be false, since I can find an example of a set A that is a subset of the union of B and C but is not a subset of either (e.g. A={4,5,6}; B={3,4,5}; C={5,6,7}).
But the book says that the statement is true, and gives the following proof.
$A \subseteq B \cup C \to \forall x \in U, x \in A \to x \in B \cup C$
$A \subseteq B \cup C \to \forall x \in U, x \in A \to x \in A \to (x \in B \lor x \in C)$
$A \subseteq B \cup C \to \forall x \in U, x \in A \to \sim(x \in A) \lor (x \in B \lor x \in C)$
$A \subseteq B \cup C \to \forall x \in U, x \in A \to \sim(x \in A) \lor \sim(x \in A) \lor (x \in B \lor x \in C)$
$A \subseteq B \cup C \to \forall x \in U, x \in A \to (\sim(x \in A) \lor x \in B) \lor (\sim(x \in A) \lor x \in C)$
$A \subseteq B \cup C \to \forall x \in U, (x \in A \to x \in B) \lor (x \in A \to x \in C)$
$\therefore A \subseteq B \cup C \to A \subseteq B \lor A \subseteq C$
It seems to me that the existence of a counterexample (I'm doubting myself so badly I'm wondering if it even is a counterexample now) must mean there is something wrong with the proof, but I'm struggling to see what it is. I'm guessing intuitively that something goes awry around line 4 or 5 in the author's use of the Idempotent and Associative Laws. I'm thinking along the lines that for every x in U, x can be (not in A but in B), or (not in A but in C), but that does not imply that x is always in B or always in C (it can be in either) and so A does not have to be a subset of B or C.

A: What the author appears to have done is to lift from the definition of SET UNION:
$$x\in A\cup B \iff x\in A \lor x\in B$$
the conclusion that this can automatically be applied to whole sets, i.e. his claim that:
$$C\subseteq A\cup B \iff C\subseteq A \lor C\subseteq B$$
which is false, as we can see if we consider:
$$ C=\{x\in A \land x\not\in B, y\in B \land y\not\in A\}$$
Then we have $C\subseteq A\cup B$ but not $C\subseteq A \lor C\subseteq B$.


text:
Q: How to import a Whatsapp text file into python pandas dataframe4 Just starting off and I'm a beginner and playing around and learning so apologies if this is basic.
I've changed the working directory to pick up the file where it is saved under:
os.chdir('C:/Users/MyName/Documents')
print("Current working directory: {0}".format(os.getcwd()))

Importing the file here:
conversation = 'WhatsApp Chat with AC.txt'
with open(conversation, encoding="utf-8") as fp:
    fp.readline()
    messageBuffer = []
    date, time, author = None, None, None
    while True:
        line = fp.readline()
        if not line:
            break
        line = line.strip()
        if date_time(line):
            if len(messageBuffer) > 0:
                data.append([date, time, author, ' '.join(messageBuffer)])
            messageBuffer.clear()
            date, time, author, message = getDatapoint(line)
            messageBuffer.append(message)
        else:
            messageBuffer.append(line)

But when I put a test here:
df = pd.DataFrame(data, columns=["Date", 'Time', 'Author', 'Message'])
df['Date'] = pd.to_datetime(df['Date'])
print(df.tail(20))
print(df.info())
print(df.Author.unique())

An empty dataframe shows up with 0 index entries. Just don't know what I'm missing to pick up the text file.


text:
Q: Authentication Page - UWP app I am develop a new UWP app, and I want that my first page be an Authentication Page.
But I would like to know if there is any way to manage users. For example, this new application that I am developing will be available in the Microsoft Store (to make the update process easier) but it will be hidden in the store, and I only want 3 to 4 people to be able to access my app so I need an Authentication Page
I want the user to enter a username and password and that this data can be validated, that is, check if they have access to my application. And if so, they can enter the application.
I do not know if I could explain it correctly.

A: You can limit the user who can download the app by email id. See the links below
Managing hidden apps, beta apps and visibility of in-app purchases in Dev Center
Set app pricing and availability
How ever you can create a login page if you want. store the details in a database(SQLite or LocalStorage) compare the details entered with the stored details. if they match go to first page or else ask for re-enter or exit the app.


text:
Q: Difference between NSLayoutAttribute "Top" and "TopMarigin" Can any one please explain the difference between NSLayoutAttributeTopMargin and NSLayoutAttributeTop, I googled it but didn't find any clear solution.

A: NSLayoutAttributeTop aligns to the top of the container. NSLayoutTopMargin aligns to the top margin of the container, which is 8 points below the top of the container by default on iOS8.
See this answer for a great description of margins: What is "Constrain to margin" in Storyboard in Xcode 6


text:
Q: Prove that the elements of sequences $(a_n),(b_n)$ are rational numbers such that $a_n<\sqrt{2}For reference I am in Introduction to Abstract Math; I have taken Discrete Math, Calculus 1, and Linear Algebra. I am stuck on the inductive step of the proof below. What would be a good approach to go about doing it? I have no idea.
Let $a_0 = 1$ and $b_0 = 2$. For $n \geq 0$, define $m_n, a_{n+1},$ and $b_{n+1}$ as follows:
(i) Let $m_n = (a_n +b_n)/2$.
(ii) If $m^2_n \leq 2$, let $a_{n+1} = m_n$ and $b_{n+1} = b_n$;
If $m^2_n > 2$, let $a_{n+1} = a_n$ and $b_{n+1} = m_n$.
Compute the first six terms of the sequences $(a_n), \: (b_n),$ and $(m_n)$.
$$m_0 = (a_0 + b_0)/2 = (1 + 2)/2 = \frac{3}{2}$$
$$m_0^2 = \frac{9}{4} > 2, \: \therefore a_1 = a_0 = 1, \: b_1 = m_0 = \frac{3}{2}$$
$$m_1 = (a_1 + b_1)/2 = \left(1 + \frac{3}{2}\right) /2 = \frac{5}{4}$$
$$m_1^2 = \frac{25}{16} \leq 2, \: \therefore a_2 = m_1 = \frac{5}{4}, \: b_2 = b_1 = \frac{3}{2}$$
$$m_2 = (a_2 + b_2)/2 = \left(\frac{5}{4} + \frac{3}{2}\right)/2 = \frac{11}{8}$$
$$m_2^2 = \frac{121}{64}\leq 2, \: \therefore a_3 = m_2 = \frac{11}{8}, \: b_3 = b_2 = \frac{3}{2}$$
$$m_3 = (a_3 + b_3)/2 = \left(\frac{11}{8} + \frac{3}{2}\right)/2 = \frac{23}{16}$$
$$m_3^2 = \frac{529}{256} > 2, \: \therefore a_4 = a_3 = \frac{11}{8}, \: b_4 = m_3 = \frac{23}{16}$$
$$m_4 = (a_4 + b_4)/2 = \left(\frac{11}{8} + \frac{23}{16}\right)/2 = \frac{45}{32}$$
$$m_4^2 = \frac{2025}{1024} \leq 2, \: \therefore a_5 = m_4 = \frac{45}{32}, \: b_5 = b_4 = \frac{23}{16}$$
$$m_5 = (a_5 + b_5)/2 = \left(\frac{45}{32} + \frac{23}{16}\right)/2 = \frac{91}{64}$$
$$m_5^2 = \frac{8281}{4096} > 2, \: \therefore a_6 = a_5 = \frac{45}{32}, \: b_6 = m_5 = \frac{91}{64}$$
$$m_6 = (a_6 + b_6)/2 = \left(\frac{45}{32} + \frac{91}{64}\right)/2 = \frac{181}{128}$$
$$(a_n)=\left(1, 1, \frac{5}{4}, \frac{11}{8}, \frac{11}{8}, \frac{45}{32}, \frac{45}{32}, \: \ldots \right)$$
$$(b_n)=\left(2, \frac{3}{2}, \frac{3}{2}, \frac{3}{2}, \frac{23}{16}, \frac{23}{16}, \frac{91}{64}, \: \ldots \right)$$
$$(m_n)=\left(\frac{3}{2}, \frac{5}{4}, \frac{11}{8}, \frac{23}{16}, \frac{45}{32}, \frac{91}{64}, \frac{181}{128}, \: \ldots \right)$$
Use induction to prove that $a_n$ and $b_n$ are rational numbers such that
$$a_n < \sqrt{2} < b_n = a_n + 2^{-n} \textrm{ for all } n \geq 1.$$
Base Case
Try to see if the statement holds true for $n=0$.
$$a_0 < \sqrt{2} < b_0 = a_0 + 2^0$$
$$1 < \sqrt{2} < 2 = 1 + 1$$
$$1 < \sqrt{2} < 2 = 2$$
Thus, the statement is true for $n=0$.
Here's where I got stuck, I don't know where to start for this.

A: At the risk of sounding like I'm taking your question too literally, the best way to start is to start writing down the "boilerplate" of the proof. Because we're doing induction on a non-negative integer $n$ you start with the first two sentences below[0], "Consider..." and "Assume...". Then we need to prove something about $a_{n+1}$ and $b_{n+1}$ so we better figure out what they are. This immediately leads to the next sentence ("The definitions of...").

Consider the case $n+1$ for $n \ge 0$. Assume the inductive hypothesis, $a_n < \sqrt{2} < b_n$. The definitions of $a_{n+1}$ and $b_{n+1}$ depend on whether $m_n^2 \le 2$ so we consider each case separately:
If $m_n^2 \le 2$, then $a_{n+1} = ***$ and $b_{n+1} = ***$. Then $***$. So $a_{n+1} < \sqrt{2} < b_{n+1}$.
If $m_n^2 > 2$, then $a_{n+1} = ***$ and $b_{n+1} = ***$. Then $***$. So $a_{n+1} < \sqrt{2} < b_{n+1}$.

Now you have a much more concrete problem: fill in the $***$s. But it's important to understand that in order to get to this point the only non-mechanical knowledge I used was that we would need to know the definitions of $a_{n+1}$ and $b_{n+1}$. But the first two sentences are entirely mechanical because it's a proof by induction. And then the rest is mechanical because the only way to get at the definitions of $a_{n+1}$ and $b_{n+1}$ is by getting "inside" the case analysis found in their definition using our own case analysis. Of course in general practice you may discover things like there are some shared facts between the cases and so on so that the basic pattern ends up getting changed as you write the proof, but the pattern is still where you'll start.
In this case, try proving the $m_n^2 > 2$ case first, because it turns out it doesn't even depend on definition of $m$ (i.e. statement (i)). There's a bit more trouble to prove the final inequality is strict for the $m_n^2 \le 2$ case and you'll have to know something about $m$.
[0] These may need to be rewritten depending on target audience preferences; e.g. we may need to use indexes shifted back by one so we talk about $n-1$ and $n$. Or there may be a set way of writing induction proofs you're supposed to be following, so use that instead. But it will amount to the same thing.

A: Suppose the statement is true for $n$. Then $m_{n} = (a_n+b_n)/2$ is rational.
If $m_{n}^{2}\leq 2$ then $a_{n+1} = m_{n}\leq\sqrt{2}$. But since $m_{n}$ is rational $a_{n+1}< \sqrt{2}$. In this case we also have $b_{n+1} = b_{n} > \sqrt{2}$ and $b_{n+1} = a_{n}+2^{-n} = 2a_{n+1}-b_{n+1}+2^{-n}$. Therefore, $b_{n+1} = a_{n+1}+2^{-(n+1)}$.
If $m_{n}^{2} > 2$ then $a_{n+1} = a_{n} < \sqrt{2}$ and $b_{n+1} = m_{n} > \sqrt{2}$ and $b_{n+1} = (a_{n+1}+a_{n+1}+2^{-n})/2 = a_{n+1}+2^{-(n+1)}$.
In both cases it is clear that $a_{n+1}$ and $b_{n+1}$ are rational.

A: Induction step: let $a_n<\sqrt{2}<b_n=a_n+2^{-n}$ and $a_n,b_n$ be rational. Then $m_n=\frac12(a_n+b_n)$ is also rational and thus $\not=\sqrt2$ since $\sqrt2$ is irrational. If $m_n<\sqrt2$ we have $(a_{n+1},b_{n+1})=(m_n,b_n)$ and $(a_{n+1},b_{n+1})=(a_n,m_n)$ if $m_n>
\sqrt2$. So $a_{n+1}<\sqrt2<b_{n+1}$ in any of the two cases. Moreover $b_{n+1}-a_{n+1}=b_n-m_n=\frac12(b_n-a_n)=2^{-(n+1)}$ in the first case and $b_{n+1}-a_{n+1}=m_n-a_n=\frac12(b_n-a_n)=2^{-(n+1)}$  in the second case.

A: Inductive Hypothesis for a given $n \in \Bbb{N}$ it is true that $a_n<\sqrt 2 < b_n=a_n+2^{-n}$.
Inductive Step We must prove that:
$a_{n+1}<\sqrt 2 < b_{n+1}$.
There are two cases:
- First case $m_n ^2 \leq 2$ (actually, since $m_n$ is rational, $m_n ^ 2 < 2 $). Then, by definition of $a_{n+1}$ and $b_{n+1}$, (using $ \sqrt 2 < b_n$ as part of the I. H.) we have:
$a_{n+1}=m_n<\sqrt 2 < b_n=b_{n+1}$ (recall that $b_{n+1}=b_n$ if $m_n ^2 \leq 2$), which is what we wanted.
- Second case $m_n ^2 > 2$. Then, by definition of $a_{n+1}$ and $b_{n+1}$, (using $a_n < \sqrt 2 $ as part of the I. H.) we have:
$a_{n+1}=a_n<\sqrt 2 < m_n=b_{n+1}$ (recall that $a_{n+1}=a_n$ if $m_n ^2 \gt 2$), which is what we wanted.
In any case, we get $a_{n+1}<\sqrt 2 < b_{n+1}$.
It only remains to prove that $b_n=a_n+2^{-n}$. I hope that the above arguments (separate into cases) help you to do that part.
Regards.


text:
Q: How would I access the PWA service worker that is embedded in wordpress? I have a site that I've added a service worker to for a PWA. The problem is that I need to embed the site into wordpress.
Wordpress has this superpwa plugin I am using and now I'm trying to use that superpwa-sw instead of my own. I've tried replacing the name of my service worker with the superpwa's service worker but I'm still unable to "load" it. SuperPWA works fine to install the app but I'd like to be able to access it if possible.
    <script>
      if('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
          navigator.serviceWorker.register('./superpwa-sw.js', {scope: '/'})
        })
      }
    </script>

I want to be able to detect if the PWA is installed or not by doing something like this:
    window.addEventListener("beforeinstallprompt", (e) => {
      // Prevent the default "add to home screen" banner from appearing on mobile
      e.preventDefault()
      showBanner
    })
    window.addEventListener('appinstalled', () => {
      dontShowBanner
    })

This all works fine when the site is visited without being embedded. Unfortunately, not using wordpress is not an option.
More context:
The wordpress site is being hosted on one server linked to one domain(wordpress.com) and the site is being hosted on another(somesite.com). The wordpress site accesses somesite.com when visiting wordpress.com/stuff by embedding it into a section of the page.


text:
Q: Java Hibernate @SafeHtml not allows url links I need to have XSS filter in my textfield, but i need to allow certain html tags for text formatting (bold, italic, etc), and i also need to allow url links like:

then with links!

So in my entity class i added whitelist:
@SafeHtml(whitelistType = WhiteListType.RELAXED,
        additionalTagsWithAttributes = {
                @SafeHtml.Tag(name = "a", attributes = { "href" })
})
private String body;

But it still gives me the following error:
may have unsafe html content

A: You have two problems one is that style attribute is not supported on the p tag and second problem is that the href attribute is missing the protocol which is required  by all the WhiteListTypes. See the list below for protocols which are supported by tag and attribute for Relaxed WhiteListType
Relaxed

*

*tag "a", attribute "href", protocols {"ftp", "http", "https", "mailto"}

*tag "blockquote", attribute "cite", protocols {"http", "https"}

*tag "cite", attribute "cite", protocols {"http", "https"}

*tag "img", attribute "src", protocols {"http", "https"}

*tag "q", attribute "cite", protocols {"http", "https"}

So in you case the text

then with links!

should be changed to

then with links!

and no, there is no easy way to add custom protocols :)
And the java code should be changed to
@SafeHtml(whitelistType = WhiteListType.RELAXED,
    additionalTagsWithAttributes = {
            @SafeHtml.Tag(name = "p", attributes = { "style" })
})
private String body;

Starting from Hibernate Validator 6 you can also provide the custom list of protocols. But sadly the @SafeHtml also marked as deprecated, so consider writing your own validator instead.
@SafeHtml(whitelistType = SafeHtml.WhiteListType.RELAXED,
    additionalTagsWithAttributes = {
            @SafeHtml.Tag(name = "p",
                    attributes = { "style" },
                    attributesWithProtocols = {
                        @SafeHtml.Attribute(name = "a", protocols = {"http", "https"})
            })
})
private String body;


text:
Q: AngularJS: Load page on link click I got 2 divs, first has links pointing to individual pages and another one to display the content of pages the links are pointing to. Here is how it looks:

Is there a way to prevent redirecting the page on link click and display the content of the URL they point to? I'm doing it this way for SEO purposes so each individual pages can also be crawlable on their own.
I've heard of ng-include but I want to be sure I'm heading the right direction so I reckon I should ask first before going with it.
Thank you in advance.

A: Use AngularJS Routing for this purpose.

Note: Must include angular-route.js


text:
Q: Duplicate table in SQLite on upgrading I'm new to Android development.
I made an app, using JSON and storing in SQLite, so to use the data offline.
I can store to my database, but every time I access it offline, the app shows a duplicate db.
I think the problem on upgrading the database is that it's not dropping the  table.
Myatabase
public class DBHandler extends SQLiteOpenHelper implements CityListener {
private static final int DATABASE_VERSION = 2;
private static final String DB_NAME = "CityDatabase.db";
private static final String TABLE_NAME = "dataku";
private static final String KEY_ID = "_id";
private static final String KEY_JUDUL = "_judul";
private static final String KEY_ISI = "_isi";

String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+"("+KEY_ID+" INTEGER PRIMARY KEY,"+KEY_JUDUL+" TEXT,"+KEY_ISI+" TEXT)";
String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

public DBHandler(Context context) {
    super(context, DB_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL(DROP_TABLE);
    onCreate(db);
}

My Fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.activity_posts_list, null);

    String url = "http://wisatake.com/test/dataku.php";

    feedListView= (ListView) v.findViewById(R.id.custom_list);
    feedListView.setVisibility(View.VISIBLE);
    handler = new DBHandler(getActivity());
    NetworkUtils utils = new NetworkUtils(getActivity());
    if(utils.isConnectingToInternet())
    {
        new DownloadFilesTask().execute(url);
    }
    else
    {
        ArrayList<FeedItem> feedList = handler.getAllCity();
        feedListView.setAdapter(new CustomListAdapter(getActivity(), feedList));
        feedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                Object o = feedListView.getItemAtPosition(position);
                FeedItem newsData = (FeedItem) o;

                Intent intent = new Intent(getActivity(), FeedDetailsActivity.class);
                intent.putExtra("feed", newsData);
                startActivity(intent);
            }
        });
    }
    return v;
}

A: i found the problem.
i didn't add primary key(ID) in db sqlite. maybe it duplicate if i dont add primary key in sqlite.


text:
Q: speed up our angular ionic hybrid app ,we trying to use app shell for initial loading , how to use app shell for ionic angar hybrid application We are using angular 13 ionic 5 trying to implement app- shell for initial loading for better user understanding. is there any way to implement app shell for ionic angular application.
We try to implement app shell in angular app it is work but for a hybrid angular ionic app is not working.
Kindly provide


text:
Q: How deny creating instance variables in Ruby I would like to deny creating instance variables in Ruby,to prevent unattended variables being created 'by mistake'.
My class:

class Test
  def initialize
    @a = 'Var A'
  end

  def make_new
    @b = 'Var B' <-- I would like to deny creation of any variables that were not defined during the init
  end
end

A: I don't claim this is a good idea, but just b/c it's kind of interesting, here is a solution that will throw an exception when a new ivar is created, but will also let you modify defined instance variables (unlike freezing the class). Just threw this together, there are undoubtably some issues w/ it, including the fact that it duplicates every method :)
module IvarBlocker
  def method_added(method)
    alias_name = "__#{method}_orig"
    return if method == :initialize || method_defined?(alias_name) || method.match(/__.*_orig/)

    alias_method alias_name, method
    define_method(method) do |*args|
      ivars_before = instance_variables.dup
      send(alias_name, *args).tap { raise "New Ivar assigned" if !(instance_variables - ivars_before).empty? }
    end
  end
end

Usage
class Test
  extend IvarBlocker

  def initialize
    @a = 1
  end

  def set_b
    @b = 2
  end

  def set_a
    @a = 6
  end
end

t = Test.new #=> #<Test:0x007f87f13c41e8 @a=1>
t.set_b #=> RuntimeError: New Ivar assigned
t.set_a #=> 6

A: You can freeze object instances at the end of initialize method:
class Test
  def initialize
    @a = 'Var A'
    freeze
  end

  def make_new
    @b = 'Var B' # I would like to deny creation of any variables that were not defined during the init
  end
end

t=Test.new
p t.instance_variable_get :@a
# "Var A"
t.make_new
#a.rb:24:in `make_new': can't modify frozen Test (RuntimeError)
#        from a.rb:30:in `<main>'
t.instance_variable_set :@c, 'Var C'
# a.rb:31:in `instance_variable_set': can't modify frozen Test (RuntimeError)
#        from a.rb:31:in `<main>'
class << t
  @d = 'Var D'
end
#a.rb:33:in `singletonclass': can't modify frozen Class (RuntimeError)
#        from a.rb:32:in `<main>'
p t.instance_variable_get :@d

A: There is a way - a hacky (but fun) way which is not meant for production (and is relatively slow). My sample implementation works for a single object only, but can be extended to support many objects.
Let's assume the following setup:
class Foo
  def initialize
    @a = :foo
  end
  def set_b; @b = 3; end
  def set_c; @c = 7; end
end

def freeze_variables_of(obj)
  frozen_variables = obj.instance_variables
  set_trace_func lambda {|event, file, line, id, binding, classname|
    if classname == obj.class
      this = binding.eval 'self'
      if this == obj
        (this.instance_variables - frozen_variables).each {|var| this.remove_instance_variable var}
      end
    end
  }
end

With the use of set_trace_func we can set a Proc which is called very often (usually more than once per statement). In that Proc we can check instance variables and remove unwanted variables.
Let's look at an example:
a = Foo.new
# => #<Foo:0x007f6f9db75cc8 @a=:foo>

a.set_b; a
# => #<Foo:0x007f6f9db75cc8 @a=:foo, @b=3>

freeze_variables_of a
a.set_c; a
# => #<Foo:0x007f6f9db75cc8 @a=:foo, @b=3>

We see that after doing the "freeze", set_c cannot set the instance variable (in fact the variable is removed at the very moment the set_c method returns).
In contrast to freezing the object (with a.freeze) (which I'd recommend for any real world application), this way allows you to modify all allowed instance variables while forbidding new ones.
This even works, if you directly assign instance variables (while Alex' method is probably faster, but relies on accessor methods).

A: There is no way to prevent creation of accidental instance variables defined that way. Why do you want to do this? What would you want such code to achieve?


text:
Q: StackExchange.Redis.RedisTimeoutException: Can I get help understanding this error message and where I should look for the root cause
StackExchange.Redis.RedisTimeoutException: Timeout performing GET (5000ms), next: GET ReviewStatSession|cuuchrwt1pattdmytjfveu55, inst: 3, qu: 0, qs: 218, aw: False, rs: TryParseResult, ws: Idle, in: 65536, in-pipe: 90112, out-pipe: 0, serverEndpoint:
redis-17006.predc30.production.int:17006, mc: 1/1/0, mgr: 9 of 10 available, clientName: PWEB184NTV, IOCP: (Busy=1,Free=999,Min=8,Max=1000), WORKER: (Busy=52,Free=32715,Min=8,Max=32767), v: 2.1.30.38891 (Please take a look at this article for some common client-side issues that can cause timeouts: https://stackexchange.github.io/StackExchange.Redis/Timeouts) at StackExchange.Redis.ConnectionMultiplexer.ExecuteSyncImpl[T](Message message, ResultProcessor1 processor, ServerEndPoint server) at StackExchange.Redis.RedisBase.ExecuteSync[T](Message message, ResultProcessor1 processor, ServerEndPoint server) at StackExchange.Redis.RedisDatabase.StringGet(RedisKey key, CommandFlags flags) at ReviewStat.RedisPageStatePersister.Load() at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at at StackExchange.Redis.ConnectionMultiplexer.T ExecuteSyncImpl[T](StackExchange.Redis.Message, StackExchange.Redis.ResultProcessor1[T], StackExchange.Redis.ServerEndPoint)() at StackExchange.Redis.RedisBase.T ExecuteSync[T](StackExchange.Redis.Message, StackExchange.Redis.ResultProcessor1[T], StackExchange.Redis.ServerEndPoint)()
at StackExchange.Redis.RedisDatabase.StackExchange.Redis.RedisValue StringGet(StackExchange.Redis.RedisKey, StackExchange.Redis.CommandFlags)()
at ReviewStat.RedisPageStatePersister.Void Load()()
at System.Web.UI.Page.System.Object LoadPageStateFromPersistenceMedium()()


text:
Q: Multiplication with zero So I have a function $f(x) = g(x) h(x)$ that I want to evaluate on a large discrete set $\Lambda$ expressed as a list. I have that $g$ is complicated and takes time to evaluate at each point in the list, but $h$ is very simple and is indeed, only non-zero for a small number of terms. I am currently using the Map function to evaluate the function $f$ on $\Lambda$, i.e. as Map[g(#)*h(#) &, L], where L corresponds to $\Lambda$.
Currently, this takes a long time since Map evaluates $g(x)$ over all points in the set even for values where $h(x)=0$ thus deeming $g(x)h(x) = 0$. Although, since $h(x)$ is zero for most $x$, it doesn't really need to compute $g(x)$ if $h(x)=0$.
I was wondering if there is a way to tell Mathematica that for $a*b$, if either $a$ or $b$ is equal to zero, then to set $a*b=0$, as to save on computation time.
Thank you for your help.

A: Depending on your data, you may define a tolerance eps and use the following function F instead:
eps = 100 $MachineEpsilon;
F = With[{val = h[#]},
    If[Abs[val] > eps, g[#] val, 0]
    ] &;
Map[F, L]

A: Something like this works:
g[x_] := {Pause[1]; x RandomReal[]}
f[x_] := If[x < 5, 0, x]
Map[With[{x = #, fe = f[#]}, If[fe == 0, 0, g[x] fe]] &, Range@10] // AbsoluteTiming
(* {6.02807, {0, 0, 0, 0, {11.9397}, {18.9161}, {14.929}, {28.8704}, {15.9467}, {11.3731}}}*)

A: Borrowing Henrik's thresholding idea, here's a sparse array approach:
SeedRandom[0];
lambda = RandomReal[{-400, 2}, 1000];
h = Exp;
g = Sin;
tol = 10^-10;

res = SparseArray[Threshold[h@lambda, tol], Automatic, 0.];
With[{nzp = Flatten@ res@ "NonzeroPositions"},
  res[[nzp]] *= g[lambda[[nzp]]]
  ];
res

The default tolerance is 10^-10, but I included tol so that it could be adjusted to each particular case.
Another way, using Map for g and h in case they're not listable:
res2 = With[{hvals =
    SparseArray[Threshold[h /@ lambda, tol], Automatic, 0.]},
  With[{nzp = hvals@"NonzeroPositions"},
   hvals*
    SparseArray[nzp -> g /@ Extract[lambda, nzp], Dimensions@hvals, 0.]
   ]]

res2 == res
(*  True  *)


text:
Q: Cannot create new instance of class for BaseAdapter I have two Classes, a Person Class that creates a new instance of a person, and a Stopwatch Class that Creates a new instance of a stopwatch (it takes in variables Button,Button,TextView, and Person).
in my Main function, i have two edit Text Boxes, a Button, and then a listview.  What I'm trying to do is fill in EditText's with First and Last name, then click save.  When saved I want to save that data to that particular instance of my person.  Then use that person to update the text of the Button within the stopwatch instance.  Each stopwatch instance should have a different person instance assigned to it so that each stopwatch has a different name.  As of right now, my onclick listener for the save button is not doing anything and I don't know why. Right now i have the getCount hardcoded to one until i am able to assign just one person to a stopwatch.
Sorry if This is a stupid question, I'm new to Java
Main Function:
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final EditText firstName = (EditText)findViewById(R.id.FirstName);
    final EditText lastName = (EditText)findViewById(R.id.LastName);
    ListView listView = (ListView)findViewById(R.id.listView);
    final Button save =  (Button)findViewById(R.id.SaveUser);

    BaseAdapter myAdapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return 1;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @SuppressLint("ViewHolder")
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.stopwatchview,parent,false);

            final TextView Screen = (TextView) convertView.findViewById(R.id.Clock_View);
            final Button start = (Button) convertView.findViewById(R.id.button_start);
            Button reset = (Button) convertView.findViewById(R.id.button_reset);
            final Person person = new Person();
            final Stopwatch stopwatch = new Stopwatch(Screen,start,reset,person);;
            Button save = (Button) findViewById(R.id.SaveUser);
            final EditText first = (EditText) findViewById(R.id.FirstName);
            final EditText last = (EditText) findViewById(R.id.LastName);

            assert save != null;
            save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    person.setName(first.getText().toString(), last.getText().toString());
                }
            });

            start.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (stopwatch.isTicking()) {
                        stopwatch.stop();
                    } else {
                        stopwatch.start();
                    }
                }
            });

            reset.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    stopwatch.reset();
                }
            });
            return convertView;
        }
    };
    listView.setAdapter(myAdapter);
}
}

Stopwatch Class:
import android.graphics.Color;
import android.os.Handler;
import android.os.SystemClock;
import android.widget.Button;
import android.widget.TextView;

public class Stopwatch {
    TextView text;
    Button start;
    Button reset;
    Person person;

public Stopwatch(TextView t, Button Start, Button Reset, Person p){
    text = t;
    start = Start;
    reset = Reset;
    person = p;

}

long starttime = 0L;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedtime = 0L;
int t = 1;
int secs = 0;
int mins = 0;
int milliseconds = 0;
Handler handler = new Handler();
Runnable callback;

public void start(){
    callback = updateTimer();
    start.setText("pause");
    starttime = SystemClock.uptimeMillis();
    handler.postDelayed(callback, 0);
    t = 0;
}

public void stop(){
    text.setTextColor(Color.BLUE);
    start.setText(person.firstName);
    timeSwapBuff += timeInMilliseconds;
    handler.removeCallbacks(callback);
    t = 1;
}

public void reset(){
    stop();
    starttime = 0L;
    timeInMilliseconds = 0L;
    timeSwapBuff = 0L;
    updatedtime = 0L;
    t = 1;
    secs = 0;
    mins = 0;
    milliseconds = 0;
    if(t==0){
        handler.removeCallbacks(callback);
    }
    text.setText("00:00:00");
}

public boolean isTicking(){
    if(t==0){
        return true;
    }
    return false;
}

//Update Timer
private Runnable updateTimer() {
    return new Runnable() {
        public void run() {
            timeInMilliseconds = SystemClock.uptimeMillis() - starttime;
            updatedtime = timeSwapBuff + timeInMilliseconds;
            secs = (int) (updatedtime / 1000);
            mins = secs / 60;
            secs = secs % 60;
            milliseconds = (int) (updatedtime % 1000);
            text.setText("" + mins + ":" + String.format("%02d", secs) + ":"
                    + String.format("%03d", milliseconds));
            text.setTextColor(Color.RED);
            handler.postDelayed(this, 0);
        }
    };
};

}

Person Class:
public class Person {
String firstName;
String lastName;
String initials;

public Person(){
    firstName = null;
    lastName = null;
    initials = null;
};

public void setName(String FirstName, String LastName){
    firstName = FirstName;
    lastName = LastName;
    setInitials(FirstName, LastName);
}

private void setInitials(String firstName, String lastName) {
    String firstLetter = firstName.substring(0,1);
    String lastLetter = lastName.substring(0,1);
    initials = firstLetter.concat(lastLetter);
}

}

A: The main problems is your BaseAdapter is never populated with data. So you accessing empty data. This because you don't properly using BaseAdapter.
First you define a collection of person data. This can be achieved using Array:
ArrayList<Person> mPersonList;

Then create your adapter by extending BaseAdapter like this:
public class MyBaseAdapter extends BaseAdapter {

    ArrayList<Person> mPersonList = new ArrayList()<>;
    LayoutInflater inflater;
    Context context;

    public MyBaseAdapter(Context context, ArrayList<Person> myList) {
        this.myList = myList;
        this.context = context;
        inflater = LayoutInflater.from(this.context);
    }

    @Override
    public int getCount() {
        return myList.size();
    }

    @Override
    public ListData getItem(int position) {
        return myList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        MyViewHolder mViewHolder;

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.layout_list_item, parent, false);
            mViewHolder = new MyViewHolder(convertView);
            convertView.setTag(mViewHolder);
        } else {
            mViewHolder = (MyViewHolder) convertView.getTag();
        }

    // get data in position
        ListData currentListData = getItem(position);

    // set data to view
        mViewHolder.edtFirstName.setText(currentListData.getFirstName());
    // add your other data to other view.

        return convertView;
    }

    private class MyViewHolder {
        EditText edtFirstName;
    // Add the other view here.

        public MyViewHolder(View item) {
            edtFirstName = (EditText) item.findViewById(R.id.FirstName);
        // add the other view here.
        }
    }
}

Fix you Person class by adding setter and getter to be used by your extended BaseAdapter:
public class Person {
  private String firstName;
  private String lastName;
  private String initials;

  public Person(){
    this("", "");
  };

  public Person(String FirstName, String LastName){
    firstName = FirstName;
    lastName = LastName;
    setInitials(FirstName, LastName);
  }

  private void setInitials(String firstName, String lastName) {
    String firstLetter = firstName.substring(0,1);
    String lastLetter = lastName.substring(0,1);
    initials = firstLetter.concat(lastLetter);
  }

  private void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  private String firstName() {
    return this.firstName;
  }

  //ADD the other setter and getter like setFirstName and firstName method.
}

Populate some data for PersonList for your BaseAdapter:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ...
    ...
    ArrayList<Person> mPersonList = new ArrayList<Person>();
    // this is a simple data
    Person person1 = new Person("John", "Keley");
    Person person2 = new Person("Chris", "Maloy");
    Person person3 = new Person("Andery", "Dreyfus");
    Person person4 = new Person("Portgas", "D. Ace");
    Person person5 = new Person("Bankai", "Zankupatto");
    mPersonList.add(person1);
    mPersonList.add(person2);
    mPersonList.add(person3);
    mPersonList.add(person4);
    mPersonList.add(person5);
}

Then add your adapter after you've add person data:
    // this should below after mPersonList data has been added.
    listView.setAdapter(new MyBaseAdapter(this, mPersonList));
...
For complete tutorial you can look at:
ListView using BaseAdapter - Android


text:
Q: Getting 5 beeps plus another 5 beeps on a ThinkPad T440p So, I am trying to repair a ThinkPad T440p for a family member, and I am getting the 5 beeps of death. It is a T440p with an i5 and Nvidia Graphics.
Basically, when I press the power button, it beeps 5 times, pauses, then beep another 5 times. I heard this could be a TPM issue?
Any help would be greatly appreciated!


text:
Q: Python telegram bot - can the bot send the first message in chat? Is it possible to get a bot to send the first message in the chat without running a command like "/Start"?
Maybe it possible to save the chat_id of the requested user in advance and send him a message in the future, thus allowing the bot to send a first message in chat according to a predefined condition that will trigger him?
I searched for an answer online but could not find one.
Can you send me a link to a tutorial that explains how to do this?
Thanks in advance
Yoav Giladi :)

A: One solution is to use a Telegram Bot deeplink to provide an entry point to the Chatbot that does not require the users typing the /Start command.
After the very first interaction you can the obtain the chat_id which can be stored for using it to initiate a message later:
context.bot.send_message(chat_id, text='Howdy')


text:
Q: Best Clothes Early in Fallout 4 In the early game, is the vault 111 suit the best thing to wear?
I've played probably 10 hours into Fallout 4, and I'm still wearing my vault clothes. They have high radiation resistance so I've been sticking armor on top. Is that the right thing to do, or should I change into something else?

A: The Vault Suit is the correct choice.
My first character was still wearing the vault suit at level 20, despite trying a number of alternatives. This is mainly due to the suit's radiation resistance.
Other undergarments are somewhat useful due to bonuses to SPECIAL attributes, but as soon as you run into some radiation you get toasted, whereas that same radiation would have barely registered with the vault suit on. Still, these other undergarments have situational uses. Undergarments that add to CHA can be a huge help when bartering or persuading. Undergarments that add to INT are good to put on before turning in quests.
The BOS Uniform grants 5 rad resist, so that might be a possibility as well. However, you can't upgrade the BOS Uniform. This means that it is quickly outclassed by the vault suit, which can be upgraded multiple times. You could also consider wearing headgear that has rad resists, like an Assault Gas Mask, but then you miss out on the attribute bonuses from a hat and glasses and look like a goon.
Later in the game you can get radiation resistance from your armor. By level 13, you can get Armorer 2 and Science! 1, allowing you to add the Leaded Misc mod to your armor. You can easily get 50 or more rad resist without a Vault Suit at this point. That's enough for almost any situation, so you can switch to different undergarments if you like. One easily obtained alternative is the Minuteman Outfit, which adds to AGI and PER. Preston is wearing one of these, and the clothing stand I built in Sanctuary Hills has two in stock every day.
More details on available clothing here, but that list doesn't look comprehensive at this time.

A: You can mod most other undergarments with the Lining perk!
For example, the Vault Suit has a Max Def of 20/25, but Military Fatigues can give you a Def of 110/115 (Max upgrade mod gives 110 but military fatigues naturally already have 5 energy defense so they stack to 115).
The Lining Perk is unlockable through Tinker Tom of the Railroad (at some point Tom is even selling these items). after unlocked you can still choose who ever you wanna side with. its acquired by side quest and it does not affect main story... also hats and other outfits are moddable this way.
The best part is this is Vanilla content - no requirements on third party mods.
Source

A: The vault suit is overall the best under-armor clothing in the entire game (Once it is fully upgraded). Boring but true.
I recommend getting the mod which allow you to wear armor over all clothing. It helps a lot with variety - now you can wear that useless tuxedo and have armor under or over it. The mod is available at NexusMods


text:
Q: SimpleDialog not displaying in Flutter I'm developing an app using Flutter. I need to show a dialog box once a certain condition is fulfilled. When it's fulfilled, the dialog box is not shown, but the screen is dimmed as if the dialog box is being shown.
showEndGamePopUp() {
    showDialog<void>(
      context: context,
      builder: (_) {
        return Container(
          child: SimpleDialog(
            backgroundColor: Colors.black,
            elevation: 2.0,
            title: Text(
              "$playerTurn wins!",
              style: TextStyle(
                color: Colors.white,
                fontSize: 20.0,
                height: 1.5,
              ),
            ),
            children: <Widget>[
              SimpleDialogOption(
                  onPressed: () => Navigator.pop(context),
                  child: Text("Play again"),
              ),
              SimpleDialogOption(
                  onPressed: () => exit(0),
                  child: Text("Exit"),
              ),
            ],
          ),
        );
      },
    );
  }

And I get the following exception: RenderBox was not laid out: RenderCustomPaint#3d792 relayoutBoundary=up3 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UP.

A: The Problem is you use Expanded
I fix your Code.Here it is.
showEndGamePopUp() {
    showDialog<void>(
      context: context,
      builder: (_) {
        return Container(
          child: SimpleDialog(
            backgroundColor: Colors.red,
            elevation: 2.0,
            title: Text(
              "wins!",
              style: TextStyle(
                color: Colors.white,
                fontSize: 20.0,
                height: 1.5,
              ),
            ),
            children: <Widget>[
              Row(children: <Widget>[
                Expanded(
                    child: SimpleDialogOption(
                  onPressed: () => Navigator.pop(context),
                  child: Text("Play again"),
                )),
              ]),
              Row(
                children: <Widget>[
                  Expanded(
                    child: SimpleDialogOption(
                      onPressed: () => print(0),
                      child: Text("Exit"),
                    ),
                  )
                ],
              ),
            ],
          ),
        );
      },
    );
  }

Just use Row wrap your Expanded.
If you like, you can use Column wrap Expanded.
Expanded must be placed directly inside flex widget.

A:     showEndGamePopUp(BuildContext context) {
        showDialog<void>(
        context: context,
        builder: (_) {
            return Container(
            child: SimpleDialog(
                backgroundColor: Colors.black,
                elevation: 2.0,
                title: Text(
                "wins!",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 20.0,
                    height: 1.5,
                ),
                ),

                children: <Widget>[
                new FlatButton(
                    onPressed: () => Navigator.of(context).pop(false),
                    child: new Text("Play again",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 20.0,
                            height: 1.5,
                        ))),
                new FlatButton(
                    onPressed: () {
                        Navigator.of(context).pop(true);
                    },
                    child: new Text("Exit",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 20.0,
                            height: 1.5,
                        )))
                ],
            ),
            );
        },
        );
    }


text:
Q: Feign Client prepends HTTP I use Spring Cloud in my microservice project with Eureka and Zuul. I want to communicate between my microservices using a Feign client. Say i have a microservice Microservice1 and Microservice2. In addition, i have the Eureka microservice and the Zuul microservice.
Zuul is configured as follows:
zuul:
ignoredServices: "*"
sensitiveHeaders: Authorization
routes:
    empty_calls:
        path: /
        serviceId: microservice1
    microservice1:
        path: /microservice1/**
        serviceId: microservice1
    microservice2:
        path: /microservice2/**
        serviceId: microservice2
host:
    connect-timeout-millis: 10000
    socket-timeout-millis: 60000

In my Microservice2, I have the following Feign client:
@FeignClient(name = "microservice1")
public interface Microservice1Client {

    @RequestMapping(value = "/test/this_is_a_test",
            method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    ResponseEntity<Boolean> addTestObject(@RequestBody List<String> userMails);

}

My problem is the following: I want the feign client to call my REST service via e.g. localhost:8080/microservice1/test/this_is_a_test. Instead, it calls "http://microservice1/test/this_is_a_test". I don't want to configure the feign client manually using the url attribute - it works automatically in other applications, but not for this specific configuration. Can anybody help me here?
Edit
The Eureka dashboard:


text:
Q: ASP.Net Identity Blazor: How to access ClientId and Client's RedirectUris from _Host.cshtml? I have an external application based on https://github.com/nextauthjs/next-auth-example which successfully redirect to my blazor Identity server. I would like to achieve the following:
(1) If the ClaimsPrincipal is null, that means the user is not logged in. RedirectToPage("/Account/Login", new {area = "Identity"});
(2) Otherwise, redirect back to the caller client application which is configured via service.AddInMemoryClients(clients). For example,
            // interactive client using code flow + pkce
            new Client
            {
                ClientId = "myapp",
                ClientSecrets = { new Secret("whatever".Sha512()) },

                AllowedGrantTypes = new [] { GrantType.AuthorizationCode, GrantType.ResourceOwnerPassword },

                RedirectUris = { "https://www.myapp.io/api/auth/callback/myapp" },
                FrontChannelLogoutUri = "https://myauth.io/signout-oidc",
                PostLogoutRedirectUris = { "https://www.myapp.io" },
                //This feature refresh token
                AllowOfflineAccess = true,
                AllowedScopes = {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    "myapp"
                },
                //Access token life time is  3600 seconds (1 hour)
                AccessTokenLifetime = 3600,
                //Identity token life time is 3600 seconds (1 hour)
                IdentityTokenLifetime = 3600
            },

And the HostModel:
[AllowAnonymous]
public class HostModel : PageModel
{
    public async Task<IActionResult> OnGetAsync()
    {
        if (!await _userManager.GetUserAsync(User))
        {
            _logger.LogWarning($"{nameof(HostModel)}.{nameof(OnGetAsync)} Invalid User!");
            return RedirectToPage("/Account/Login", new { area = "Identity" });
        }
        /*
        else if (!_signInManager.IsSignedIn(User))
        {
            For some reasons, this always appears as false!
            _logger.LogWarning($"{nameof(HostModel)}.{nameof(OnGetAsync)} User not signed in!");
            return RedirectToPage("/Account/Login", new { area = "Identity" });
        }*/
        _logger.LogWarning($"{nameof(HostModel)}.{nameof(OnGetAsync)} User signed in!");
        return RedirectToPage("XXX: How to retrieve the RedirectUris and use it here?");
    }
}

Or how can I configure the client to hit the /Identity/Account/Login endpoint directly?
export default NextAuth({
  // https://next-auth.js.org/configuration/providers
  providers: [
    IdentityServer4Provider({
      id: "myapp",
      name: "myapp",
      authorization: {
        params: { scope: "myapp" },
      },
      issuer: config.get('https://myidentityserver.com'),
      clientId: config.get('IdentityServer4_CLIENT_ID'),
      clientSecret: sha512(config.get('IdentityServer4_CLIENT_SECRET')),
    }),
<snip>


text:
Q: How to stop Div Moving out of the border Jquery draggable(); How to stop the div from moving out of the border div
Here is the code i got so far.

Drag me

Thank you,

A: You need to use containment. E.g.
$("#draggable").draggable({
  grid: [50, 20],
  containment: 'parent'
});

Edit:
Here's an example.
Remember, you're using a grid, so you won't reach the edges unless you calculate the width and height of your box to match that grid.


text:
Q: Automating Configuration items in xldeploy Currently, I am creating the Configuration items in xldeploy manually like adding infrastructure, environments and packages.
Please let me know is there any process or templates to create Configuration items automatically .

A: You could use the DevOps as Code functionality.


text:
Q: I need to upload an image with PHP and insert file names in database I have a PHP form that updates records in a database. It looks something like this.
//update a record
$query1 = 'UPDATE mytable SET name="'.$name.'", description="'.$desc.'",
 img="'.$img.'" WHERE id="'.$id.'" ';

mysqli_query($con,$query);

//get record set
$query2 = 'SELECT * FROM mytable WHERE id="'$id'"';
$result = mysqli_query($con,$query2);

echo  '<form action="my-update-page.php" method="post">';

//table heading row
echo '
';
  echo  '
';
  echo   'ID	';
  echo   'NAME	';
  echo   'description	';
  echo   'Image	';
  echo  '
';

//display data
while($row = mysqli_fetch_array($result))
  {

  echo '<input type="hidden" name="id" value="' . $row['id'] . '" />';
  echo  '
';
  echo   ''. $row['id'] . '	';
  echo   '<input type="text" name="name" value="'. $row['name'].'" />	';
  echo   '<textarea name="description">'.$row['description'].'</textarea>	';
  echo   '<input type="text" size="3" name="img" value="'. $row['img'].'"/>;
  echo   'Upload Image	';
  echo '
';

  }

//closing tag for table
echo '
';
echo '
<input type="submit" value="submit" /></form>';

I want my upload.php page to open in a popup where the user can upload the image. I'm pretty sure I can manage doing that. Where I get stuck is after the file is uploaded, I want the popup to close and file name to show in the form input.

A: Modify to reflect your names, but window.opener is the link to the other window. At that point, access any elements the same way.
window.opener.forms['myform'].elements['fileinput'].value = nameOfFile;

window.close();

As the comment above says, use AJAX to do the file post.


text:
Q: Push Notifications for iOS When I implement "Push Notifications" functionality in my application, in the settings of the phone the user can choose if he want to have the push notifications enabled or disabled.
Is it possible that I disable this functionality? My application has push notifications by default disabled and the user can subscribe to various kinds of events to get push through the app.
So this "general", enable/disable functionality is really a pain for the architecture of my app , my databases etc.
Also I support 4 different platforms of mobile devices, that don't have this functionality. So I cant have it only for 1 platform..
Is it possible not to be there?

A: You cannot prevent the user from disabling/enabling Push Notifications. Apple is pretty clear in regards to actions like this. They do not want a developer to be able to restrict any basic iOS functionality.
You say that your app has push notifications disabled by default. Why are you concerned about this? Also, handling push notifications in an app is actually somewhat easy and does not require much code at all.

A: you can not do it at app end but you can put a check on server side to send the notification only on those devices on which the applicable users are logged in.
try this it may help you.

A: If you use Apple's Push Notifications you cannot stop the user from disabling display of your notifications.

A: This should really be more of a minor inconvenience than a big problem.
If user had disabled notifications from outside your app (in device settings) you can simply perform the same actions as if he did it inside your app.
On how to check if notifications for your app are enabled or not check here: Determine on iPhone if user has enabled push notifications
As for not allowing the user to disable notifications within device settings: it's a no-go.


text:
Q: .toggleClass en solo 1 elemento aunque existan varios con la misma clase Estoy intentando crear un menú multinivel pero no sé cómo hacer que solo se añada la clase al elemento que está dentro del
 que he pulsado.
La idea final es pulsar la flecha que he creado con JS y que añada o quite una clase en el ul.sub-menu, pero solo en el ul.submenu que está al mismo nivel que el span de la flecha (este se crea como hijo del li que tiene la clase .menu-item-has-children
Este es el código:
HTML

          Sobre nosotros

El equipo

Nuestras instalaciones

El equipo

Nuestras instalaciones

Cómo trabajamos

Cómo trabajamos

Vídeos

Trabajos

Blog

Contacto

Pide presupuesto

El equipo

Nuestras instalaciones

Cómo trabajamos

JS
// CREAR ELEMENTO PARA ABRIR MENU EN MOVIL (FLECHA)
  $(".menu-item-has-children > a").append('');

 // ABRIR SUBMENU AL HACER CLICK EN FLECHA
    $(".btn-mostrar").click(function(){
        $(".sub-menu").toggleClass("mostrar");
    });

});

A: Intenta usando jQuery's .next() asi:
$(".btn-mostrar").click(function(){
    $(this).parent().next(".sub-menu").toggleClass("mostrar");
});

A: En programación, existe el concepto del this que en el caso de eventos (que es lo que nos ocupa) se refiere al elemento que lo ha disparado. De tal manera que el this en el caso de un evento del tipo click, hace referencia al elemento al que se pulsó con el ratón.
Basándonos en este principio, podemos hacer que tan solo se muestre el .sub-menu hermano del elemento al que hacemos click, que en tu caso es el .btn-mostrar:
$(".btn-mostrar").click(function(){
    $(this).siblings('.sub-menu').toggleClass("mostrar");
});

Con eso, ya te debería de aplicar la clase mostrar tan solo al submenú que corresponda.


text:
Q: PDF to Image using PDFBox 1.8.9 text overlapped I am trying to convert PDF to Image using PDFBox 1.8.9. The fonts are getting overlapped. I know this problem does not occur in PDFBox 2.0 SNAPSHOT. But it cannot be used in production until it is officialy released.
Below is the code:
PDDocument pdDocument = PDDocument.load(new File("test.pdf"));
List<PDPage> pages = pdDocument.getDocumentCatalog().getAllPages();
int pageCounter = 1;
for (PDPage page : pages) {
    BufferedImage bufferedImage = page.convertToImage();
    File imageFile = new File(String.format("/tmp/pdf-image-%s.jpg", pageCounter));
    ImageIO.write(bufferedImage, "jpg", imageFile);
    pageCounter++;
}

The font appears similar to PDF except overlapping?
When I try to convert PDF to Image using pdfbox-app-1.8.9.jar through command line, the Image is generated with a different font. Does PDFBox has any option to specify a custom font using .ttf? In that case, how can I specify?
Actual PDF:

Converted Image using above code:

Converted Image using commandline:

A: PDFBox substitutes font for Helvetica and Times New Roman etc., when it is not found on the server. After installing the above fonts on my Linux machine, the problem got solved.


text:
Q: Does creating local alias for a variable add overhead? Consider following cases
void func(const A& a)
{
    //Case 1:
    const int& val = a->b->c->d;
    func1(val);
    func2(val);

    //Case 2:
    func1(a->b->c->d);
    func2(a->b->c->d);

    //Case3:
    int val = a->b->c->d;
    func1(val);
    func2(val);
}

w.r.t readability, Case3 is most straightforward
w.r.t to speed, For a decent compiler, Are all the above cases equivalent? If not which of them are fastest and slowest?
Assume all the pointers are raw pointers and they point to objects in heap.
Update: Assume the argument is a const one as shown above and so func1 and func2 may take the arguments either by value or by const reference.

A: Assuming both functions take their argument by value, Case 3 is at least as fast as Case 1 which is at least as fast as Case 2.
As ruakh mentioned in the comments, there's some complex dataflow analysis required before optimization occurs.
If the function parameters are references, then the final memory load of the value might never take place.  Then Case 1 would be fastest.
And if those are macros rather than functions, all bets are off.

A: in the first scenario you make a reference in val to a->b->c->d, therefor from the compiler's pov val is a dereferenced pointer.
wrt speed the third one is the fastest as it simply creates a copy of the value than uses that one.
the problem with the first two methods is that you have to dereference the pointers to get the value so you have to do
case 1
lea eax,[ebp+a]
push eax

case 2
lea eax, [ebp+a]
lea ebx, [eax]
....

case 3
mov eax [ebp+val]
push eax

and you can clearly see that the third one is the fastest


text:
Q: How to reduce loading time of models made with three.js editor? I created a 3D model made of 160 objects (cubes with different textures) using the three.js editor, then I exported the model and used THREE.ObjectLoader() to import it in a scene I'm working on (as explained here https://threejs.org/docs/#api/en/loaders/ObjectLoader).
However I noticed that loading the file and display the model on screen takes quite some time. What can I do to reduce this waiting time?
I thought maybe it'd be a good idea to merge some of the geometries of the model, but I can't figure out how to do it on a model created using the three.js editor.


text:
Q: Math with previous row in SQL, avoiding nested queries? I want to do some math on the previous rows in an SQL request in order to avoid doing it in my code.
I have a table representing the sales of two entities (the data represented here is doesn't make much sense and it's just an excerpt) :
YEAR    ID      SALES             PURCHASE         MARGIN
2009    1       10796820,57       2662369,19       8134451,38
2009    2        2472271,53       2066312,34        405959,19
2008    1        9641213,19       1223606,68       8417606,51
2008    2        3436363,86       2730035,19        706328,67

I want to know how the sales, purchase, margin... have evolved and compare one year to the previous one.
In short I want an SQL result with the evolutions pre-computed like this :
YEAR    ID    SALES         SALES_EVOLUTION    PURCHASE      PURCHASE_EVOLUTION  MARGIN        MARGIN_EVOLUTION
2009    1     10796820,57   11,99              2662369,19    117,58              8134451,38     -3,36
2009    2      2472271,53   -28,06             2066312,34    -24,31               405959,19    -42,53
2008    1      9641213,19                      1223606,68                        8417606,51
2008    2      3436363,86                      2730035,19                         706328,67

I could do some ugly stuff :
SELECT *, YEAR, ID, SALES , (SALES/(SELECT SALES FROM TABLE WHERE YEAR = OUTER_TABLE.YEAR-1 AND ID = OUTER_TABLE.ID) -1)*100 as SALES_EVOLUTION (...)
FROM TABLE as OUTER_TABLE
ORDER BY YEAR DESC, ID ASC

But I have arround 20 fields for which I would have to do a nested query, meaning I would have a very huge and ugly query.
Is there a better way to do this, with less SQL ?

A: Old skool solution:
SELECT c.YEAR, c.ID, c.SALES, c.PURCHASE, c.MARGIN
,      p.YEAR, p.ID, p.SALES, p.PURCHASE, p.MARGIN
FROM       tab AS c -- current
INNER JOIN tab AS p -- previous
ON         c.year = p.year - 1
AND        c.id   = p.id

If you have a db with analytical functions (MS SQL, Oracle) you can use the LEAD or LAG analytical functions, see http://www.oracle-base.com/articles/misc/LagLeadAnalyticFunctions.php
I think this would be the correct application:
SELECT     c.YEAR, c.ID, c.SALES, c.PURCHASE, c.MARGIN
,          LAG(c.YEAR, 1, 0) OVER (ORDER BY ID,YEAR)
,          LAG(c.ID, 1, 0) OVER (ORDER BY ID,YEAR)
,          LAG(c.SALES, 1, 0) OVER (ORDER BY ID,YEAR)
,          LAG(c.PURCHASE, 1, 0) OVER (ORDER BY ID,YEAR)
,          LAG(c.MARGIN, 1, 0) OVER (ORDER BY ID,YEAR)
FROM       tab AS c -- current

(not really sure, haven't played with this enough)

A: Using sql server (but this should work for almost any sql), with the table provided you can use a LEFT JOIN
DECLARE @Table TABLE(
        [YEAR] INT,
        ID INT,
        SALES FLOAT,
        PURCHASE FLOAT,
        MARGIN FLOAT
)

INSERT INTO @Table ([YEAR],ID,SALES,PURCHASE,MARGIN) SELECT 2009,1,10796820.57,2662369.19,8134451.38
INSERT INTO @Table ([YEAR],ID,SALES,PURCHASE,MARGIN) SELECT 2009,2,2472271.53,2066312.34,405959.19
INSERT INTO @Table ([YEAR],ID,SALES,PURCHASE,MARGIN) SELECT 2008,1,9641213.19,1223606.68,8417606.51
INSERT INTO @Table ([YEAR],ID,SALES,PURCHASE,MARGIN) SELECT 2008,2,3436363.86,2730035.19,706328.67

SELECT  cur.*,
        ((cur.Sales / prev.SALES) - 1) * 100
FROM    @Table cur LEFT JOIN
        @Table prev ON cur.ID = prev.ID AND cur.[YEAR] - 1 = prev.[YEAR]

The LEFT JOIN will allow you to still see values from 2008, where an INNER JOIN would not.

A: You can do it like this:
SELECT t1.*, t1.YEAR, t1.ID, t1.SALES , ((t1.sales/t2.sales) -1) * 100 as SALES_EVOLUTION
 (...)
FROM Table t1 JOIN Table t2 ON t1.Year = (t2.Year + 1) AND t1.Id = t2.Id
ORDER BY t1.YEAR DESC, t1.ID ASC

Now, if you want to compare more years, you'd have to do more joins, so it is a slightly ugly solution.


text:
Q: 'overlay' is not an exported object from 'namespace:sp' I have some code showing this error, but, I haven't called "overlay", maybe it's a library function that is calling it
Code:
d.mle=likfit(P, ini.cov.pars = c(1,30), cov.model = 'matern', kappa = 0.5)
d.mle

Xb = c(1, size, size, 1)
Yb = c(1, 1, size, size)
bordas = cbind(Xb, Yb)
polygon(bordas)
Ap = matrix(apply(bordas, 2, range))
gr <- expand.grid(x = seq(Ap[1, ], Ap[2, ], by = 1), y = seq(Ap[3, ], Ap[4, ], by = 1))
require(splancs)
gi <- polygrid(gr, borders = bordas) # delimita a area para interpolação
points(gi, pch = "+", col = 2)
KC  = krige.control(obj = d.mle, type.krige = "ok", lam = 1)
d.k = krige.conv(P, loc = gr, krige = KC) #Realiza a interpolação por krigagem

valores_preditos = d.k$predict
Ze = matrix(valores_preditos, size, size) # Transforma os valores preditos em matriz
plot(Ze)
plot(image(X, Y, Ze, col = gray((0 : 4) / 4), breaks = c(a., b., c., d., e., f.)))

A: If you do this:
??overlay

... you should get a list of all the functions in packages that mention the word "overlay". When I do it, I see two functions with that name but I strongly suspect that it is the raster-package's version that is expected by the code you are using. So do this:
install.packages('raster')
library(raster)
#re-run code


text:
Q: CopyAsync method don`t replace existing file. UWP. Application-storage Now I am working on edit operation in my app. So in edit operation there is  an ability to change image and in the same time name of the file that keep image of the contact can not be renamed(during one session of operation image files will be changing but all this file will take same name).
And I used overload of CopyAsync method (docs to this method here) that as I have understand must to replace file to the existing file with the same name.
I get imageFile variable by FileOpenPicker. Code below runs every time I have choosed image by FileOpenPicker. And when I re-choose image at the result Image UI control show me previous chosen image. I expect that Image will view last image that I have choosed but this does not occurred.
    public BitmapImage Image { set; get; }

    //Copy of the file that saved in temporary storage
    StorageFile fileForView = await imageFile.CopyAsync
       (ApplicationData.Current.TemporaryFolder,
       fileName,
       NameCollisionOption.ReplaceExisting);

    Image = new BitmapImage(new Uri(fileForView.Path));

Maybe I understand logic of CopyAsync method not correctly if I am in this case please show me how make my plan working with this method if it is possible. Otherwise offer your solution cause I have no idea now how to do this.
Also I tried to do this with CopyAndReplaceAsync method. But still no result. I do it in this way:
         if (null != await ApplicationData.Current.TemporaryFolder.TryGetItemAsync(fileName))
        {
            StorageFile storageFile = await ApplicationData.Current.TemporaryFolder.GetFileAsync(fileName);

            await storageFile.CopyAndReplaceAsync(imageFile);
        }

A:
I expect that Image will view last image that I have choosed but this does not occurred.

The above CopyAsync method is correct, and I have tested with the following code, it works well.
private async void ListOption_ItemClick(object sender, ItemClickEventArgs e)
{
    FileOpenPicker openPicker = new FileOpenPicker();
    openPicker.ViewMode = PickerViewMode.Thumbnail;
    openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
    openPicker.FileTypeFilter.Add(".jpg");
    openPicker.FileTypeFilter.Add(".jpeg");
    openPicker.FileTypeFilter.Add(".png");

    StorageFile file = await openPicker.PickSingleFileAsync();
    if (file != null)
    {
        StorageFile fileForView = await file.CopyAsync(ApplicationData.Current.TemporaryFolder, file.Name, NameCollisionOption.ReplaceExisting);
        Image = new BitmapImage(new Uri(fileForView.Path));
        TestImg.Source = Image;
    }
    else
    {

    }
}


text:
Q: Gridview not populating by datatable
Below is the code where The four columns("Challan Number","Proposal Number","CTS Number" and "Amount") is obtained from Sql-Database, and the ("Land" and "Ward") values are obtained from respective methods. The values obtaines are correct but still the "ChallanGridview" is not getting populated.
  The datarow "dr1" gets populated with the correct required values, but the "ChallanGridview" doesn't shows anything.

public void FillChallanGrid()
{
    string query = string.Empty;
    string cs = ConfigurationManager.ConnectionStrings["ConStrg"].ConnectionString;
    query = CtrlChallenSearch1.GetChallanQuery();
    using(SqlConnection con=new SqlConnection(cs))
    {
        SqlDataAdapter da = new SqlDataAdapter(query,con);
        DataSet ds = new DataSet();
        da.Fill(ds,"entry");
        int x = ds.Tables["entry"].Rows.Count;
        DataTable dt = new DataTable();
        dt.Columns.Add("Challan Number");
        dt.Columns.Add("Proposal Number");
        dt.Columns.Add("CTS Number");
        dt.Columns.Add("Amount");
        dt.Columns.Add("Land");
        dt.Columns.Add("Ward");

        for(int i=0;i<x;i++)
        {
            DataRow dr = ds.Tables["entry"].Rows[i];
            DataRow dr1 = dt.NewRow();
            dr1["Challan Number"] = dr["ReceiptNo"].ToString();
            dr1["Proposal Number"] = dr["ProposalNo"].ToString();
            dr1["CTS Number"] = dr["CTSNo"].ToString();
            dr1["Amount"] = dr["Amount"].ToString();
            dr1["Land"] = GetLand(dr["ProposalNo"].ToString());
            dr1["Ward"]=GetWard(dr["ProposalNo"].ToString());
            dt.Rows.Add(dr1);
        }
        ChallanGridView.DataSource = dt;
        ChallanGridView.DataBind();
    }
}

private object GetLand(string ProposalNumber)
{
    string retvalue = string.Empty;
    if (ProposalNumber != "" || ProposalNumber != null || ProposalNumber != string.Empty)
    {
        string[] splittedvalue = ProposalNumber.Split('/');
        retvalue = splittedvalue[1];
    }
    return retvalue;
}

private object GetWard(string ProposalNumber)
{
    string retvalue = string.Empty;
    string[] splittedvalue = new string[3];
    splittedvalue = ProposalNumber.Split('/');
    retvalue = splittedvalue[0];
    return retvalue;
}

protected void Button1_Click(object sender, EventArgs e)
{
    FillChallanGrid();
}

A: Its solved, I just deleted the present gridview and added another fresh one,
don't know how and why, but the error was gone.
btw thnks  Asif.Ali!


text:
Q: Hibernate Configuration without configuration file Here is how im trying to get the hibernate SessionFactory. This is called via
a simple java application. All the configurations are already added into properties.
private SessionFactory buildSessionFactory() {
        Configuration configuration = new Configuration();
        configuration.setProperties(properties);
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    }

But then i get the exception
eb 13, 2015 2:03:47 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Feb 13, 2015 2:03:47 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.7.Final}
Feb 13, 2015 2:03:47 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Feb 13, 2015 2:03:47 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Feb 13, 2015 2:03:47 PM org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator initiateService
WARN: HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections
Exception in thread "main" org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:209)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)

My properties are as following
final Properties properties = new Properties();
properties.put("connection.url", TEST_CONNECTION_URL);
properties.put("connection.username", TEST_USERNAME);
properties.put("connection.password", TEST_PASSWORD);
properties.put("connection.driver_class", "org.postgresql.Driver");
properties.put("dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.put("show_sql", "true");
properties.put("connection.pool_size", "1");
properties.put("current_session_context_class", "thread");

A: You should use this source
Configuration cfg = new Configuration()
    .addClass(org.hibernate.auction.Item.class)
    .addClass(org.hibernate.auction.Bid.class)
    .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
    .setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")
    .setProperty("hibernate.order_updates", "true");

A: I've not configured the Properties in simple java, but when I look at my hibernate.properties file, it's defined as hibernate.dialect=respectiveDialect. Also the error which you posted defines hibernate.dialect is null, so probably it should be
properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");


text:
Q: Save high score at other view controller I click on a button, and get the points, I click at another button and the game is over. The score is saved. But Now I want to make it possible to get a high score. How is it possible to get the high score seen on the second view controller?

A: Let your first view controller be ViewController and the second one be ViewController_2. And let there be a array called scores in ViewController that you set when the button is clicked. Now, you need another variable in ViewController_2 of type Int, let it be score_2, which score's HighScore.
Here's how ViewController_2 should look like:
class ViewController_2: UIViewController {
      var score_2:Int;
      override func viewWillAppear(){
        //ScoreLabel.text="High Score : \(score_2)"
      }
    }

Here's how ViewController should look like :
class ViewController: UIViewController {
  var scores:[Int];

  @IBAction func foo(sender:Button) {
    let score:Int=getScore()
    scores.append(score)
  }

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    var destination=segue.destinationViewController as ViewController_2
    destination.score_2=maxElement(self.scores)
 }
}

Read about segues, It will surely help you.

A: The best way to save a highscore is through NSUserDefaults. This will allow you to save something such as a highscore and then call for it anytime within your app.
let highscore = label.text;
NSUserDefaults.standardUserDefaults().setObject(highscore, forKey: "Highscore")
    NSUserDefaults.standardUserDefaults().synchronize()

In this case I have whatever is in the label is then saved as your new highscore. You will want to implement a way to make sure that this score has to be higher then your previous highscore in order to be saved.
if you want to call it to another view controller all you have to do is:
        NewLabel.text = NSUserDefaults.standardUserDefaults().stringForKey("Highscore")

I hope this helps


text:
Q: Smallest Circumcircle of Three Triangles with Equilateral Constraint What is the minimum diameter of the circumcircle about an equilateral triangle formed by the center points of three congruent equilateral triangles that do not overlap?
The diagram is the best solution I've found so far.

Let the triangles have side 1.  Applying the law of sines to ABC gives angle θ ≈ 14.5°.  Triangle EDB now yields the target side x ≈ 0.809 and the circumcircle ≈ 0.934.  Is EFG equilateral?
Here's another configuration:

Applying the law of sines to ADC again gives θ ≈ 14.5° and x ≈ 0.809. Is there something better?
This problem came up in wood turning when arranging painter's pyramids to support small bowls.  Painter's pyramids are tetrahedrons used to support objects while finishing.  An equilateral triangle configuration of the supporting tips has the greatest stability.  Isosceles and scalene configurations sacrifice stability for smaller bowl support.

A: By the sine law applied to triangle $ABC$ one gets $\sin\theta=1/4$, so that $\cos\theta=\sqrt{15}/4$. From triangle $BED$ one thus obtains:
$$
EF=2{1\over\sqrt3}\sin(30°+\theta)=
{2\over\sqrt3}\left({1\over2}{\sqrt{15}\over4}+{\sqrt{3}\over2}{1\over4}\right)
={1+\sqrt{5}\over4}.
$$
On the other hand one has $\angle BAC=30°-\theta$, so that $\angle EAG=150°-\theta$. By the cosine rule applied to $AEG$ one then gets:
$$
EG^2=\left({1\over\sqrt{3}}\right)^2+\left({1\over2\sqrt{3}}\right)^2
-2{1\over\sqrt{3}}{1\over2\sqrt{3}}\cos(150°-\theta)
={3+\sqrt{5}\over8}=\left({1+\sqrt{5}\over4}\right)^2.
$$
So $EG=EF$ and triangle $EFG$ is equilateral.


text:
Q: Better continuity between sites This is sort of a two-part question.  I'd be surprised if this hasn't been asked in some form already, but according to the faq, that's "OK and deliberately allowed."
On StackOverflow proper, I have a respectable amount of rep1.  Certainly not as much as the heavy hitters, who must have neither jobs nor family, and seem to tend to live near London, but enough that I feel that people at least give my answers a fair read.
Here on meta (and on ServerFault, etc.), I'm a veritable neophyte.
I assume that there are two basic reasons for keeping the rep/badges separate among the sites:
Just because someone has expertise in one domain does not guarantee that that person is knowledgeable in other domains.
While I understand this argument, I don't feel it's complete.  If someone is conscientious enough to construct good, well-thought-out answers that are helpful enough to receive substantial votes and to be accepted answers, then it is a good indicator that that person will continue that behavior.  A person not known to give poor answers on topics he/she knows little about will not likely start doing so just because the site has a different color scheme.  That is, a person with good answers on SO will not likely spew crap on SF, SU, MSO, etc.  If the community thinks a person is worth listening to, then that should carry some weight in other places that significant portions of the community may visit.
And after all, there is a fair amount of overlap in the knowledge domain of the SO/SF, etc. family of sites.  I'm a developer by day, but I administer my own home network by night.  So there.
A rep reset allows MMORPG rep whores who've "won" StackOverflow to play again on its sister sites.
I don't mean that to be pejorative at all.  Earning rep and badges is fun, and a big part of what keeps many of us coming back.  It provides a sense of accomplishment, and of recognition.  And I understand the attraction of having a whole new set of goals to obtain.  Nonetheless, it would be nice to have some continuity between these very similar playgrounds we play in.
So, the two parts of my question:

*

*Shouldn't there be some recognition of rep from sister sites?  Perhaps a mention of a user's overall rep, as well as their rep count for the specific site.  Perhaps I'd be listed as:
 P Daddy  123 / 3866
Where 123 is my reputation here (it really is), and 3866 is my total reputation on the /M?S[OFU]?/ family of sites.

*With or without that, there is a definite disconnect among the sites.  If I receive a comment or answer on one site, it would be incredibly helpful if I could be notified on one of the other sites.  I spend most of my time on SO, and would love to keep track of activity on the other sites without having to check all of them all the time.
Also, when I read a post that I find to be of high quality, I sometimes like to see what else that user has posted.  But unless I explicitly check the sister sites, I can only see that user's activity on the particular site I'm on.  Let's spread the love!  It might even bring more traffic to the sister sites.
I apologize for my long-windedness.  I tend to be that way.  There ought to be a badge for it!
1: Around 3600 as of this writing.

A: If you want to see combined rep score across the SOFU, check out their, or your own, account tab. You'll see all of the linked accounts and their reputations. Just add the numbers up and do the math. And math is fun. Unless you're checking for cooked books. And then it's super fun.
But it also sounds like you think having more than one site to check is ridiculous. Maybe it would be better to have it all in one big stewing pot of questions and answers. No, it wouldn't. They're different markets and audiences.
Sounds like you're also interested in following some people because their answers interest you.
Speaking of quality, the level of discourse here on Meta is certainly not the same you'd find in the rest of the trilogy. Reputation is a weird beast, but not something you should signal as a hard set indicator of quality.

A: This is an ancient request, but, for a long while now we've had...

*

*Network profiles. Yours is here. https://stackexchange.com/users/16612/p-daddy

*A +100 rep bonus on every site in the network (that you have an account on) provided you have at least 200 rep on any one Stack Exchange site.

*A global notification inbox for all sites on the upper left.
(:

A: There have been many requests for a SO-family page (or view), make sure and search for these and upvote them.

A:
If someone is conscientious enough to construct good, well-thought-out answers that are helpful enough to receive substantial votes and to be accepted answers, then it is a good indicator that that person will continue that behavior. A person not known to give poor answers on topics he/she knows little about will not likely start doing so just because the site has a different color scheme. That is, a person with good answers on SO will not likely spew crap on SF, SU, MSO, etc

This probably was true when all the sites were technical. Now that there are religion sites on the network, where some high-rep SO people like to troll, this is probably significantly less desirable.

A: I'm disappointed to see the comments on P Daddy questions because I thought what he pointed out was pretty much right.
I use to be on SO, with not much rep, ~90.
It doesn't really matters to me, I just want to be able to help people or ask questions when I have some.
However, like P Daddy, I also found it very annoying that just because I change website I cannot do the 3 basics action (vote up, flag, and post comment).
More details

Another thing I've notice in the current system. Recently, I saw there is a programmer website which make me enthusiasm, however it's a bit annoying to start over again. I even saw questions that has been moved from SO to the programmer one, that's kinda sad that I cannot upvote an answer that I know is good. I am actually a software engineer and I've been asking and replying question mostly on SO, I would like to be able to do the basic on the programmer website too.
Which leads me to the main question
Would it be possible to have your rep following everywhere at least for the first 50 rep points?
Sorry if my actual answer is a question...