Order of evaluation in v != std::exchange(v, predecessor(v))

Question: I keep finding more idioms that lend themselves to std::exchange.
Today I found myself writing this in an answer:
do {
    path.push_front(v);
} while (v != std::exchange(v, pmap[v]));

I like it a lot more than, say
do {
    path.push_front(v);
    if (v == pmap[v])
        break;
    v= pmap[v];
} while (true);

Hopefully for obvious reasons.
However, I'm not big on standardese and I can't help but worry that lhs != rhs doesn't guarantee that the right-hand side expression isn't fully evaluated before the left-hand-side. That would make it a tautologous comparison - which would by definition return true.
The code, however, does run correctly, apparently evaluating lhs first.
Does anyone know

whether the standard guarantees this evaluation order
if it has changed in recent standards, which standard version first specified it?

PS. I realize that this is a special case of f(a,b) where f is operator!=. I've tried to answer my own query using the information found here but have failed to reach a conclusion to date:

https://en.cppreference.com/w/cpp/language/eval_order
https://en.wikipedia.org/wiki/Sequence_point
Order of evaluation in C++ function parameters
What are the evaluation order guarantees introduced by C++17?
Comment: @rturrado And yes, the double `pmap[v]` can be circumvented by adding a named variable. Alas, there is no way to constrain the scope of said variable. Re-writing as a for-loop (which is the usual) requires either making the push operation a side effect of the condition (which is objectively worse because that operation doesn't already exist with well-known semantics, unlike `std::exchange`) or ... duplicating that outside of the loop body... It's catch-22
Comment: [FWIW](https://godbolt.org/z/9bPr8Koza).
Comment: Mmm... might be well formed if `operator !=` is a member https://timsong-cpp.github.io/cppwp/n4868/expr.call#8 - It's certainly not more complex than the standard's own example
Comment: I do not see any wording that mandates that the left side of `!=` be sequenced before the right. C++17 added sequencing for some operations, but `!=` does not appear to be among them.
Comment: @rturrado I like to think that the loop is a lot clearer with the "atomic" (as in, single-statement) exchange. But yeah, it appears to be safer without. Which IMHO is the non-obvious part. The only reason I had the danger sensors going off is because I've learned painful  C++ lessons in the past. But I expect the average programmer to have the same, completely intuitive expectation of what that code should do.
Comment: @SebastianRedl I agree. But only IFF that evaluation order isn't specified. As an off-topic prompt, do you have an elegant alternative suggestion? The reason that I came up with this version is that all other incarnations of this kind of loop that I've seen over many years are significantly worse.
Comment: *Hopefully for obvious reasons.* No way! You can never generalise, but clearer is always better (and especially safer). Ah, OK! Unless you meant the double `pmap[v]` :)
Comment: Thanks @n.m. I did do some checks myself, however the question is indeed focused on the standard guarantees. I [fixed the implementation defined behaviour in the answer that prompted this](https://stackoverflow.com/posts/74600853/revisions)
Comment: Maybe `std::exchange` is the wrong tool, here. Have you considered something like: https://godbolt.org/z/MjqcrKWz3 ?
Comment: @Bob__ Yeah. The appeal `std::exchange` is that it is standardized, with _well-known  semantics_. Although one can come up with bespoke primitives, they won't really be as generally applicable - or it will never be as intuitive. (FP ecosystems like Haskell are bigger here, largely because immutability everywhere makes it easier to have "obvious" semantics). For comparison the iterations that I posted here: https://fosstodon.org/@sehe/109422130042322033
Comment: Isn't that `do { path.push_front(std::exchange(v, pmap[v])) while (v != pmap[v])`?
Comment: @JeffGarrett Gosh. I think it might be indeed. Downside is that `pmap[v]` is evaluated twice, which might be significant. But the elegance is wort a lot. It's subtle in that it's the condition seems "too late" (the exchange has already been performed). This is why I stopped looking at this solution direction. However, it's actually fine, because when `v == pmap[v]` it becomes idempotent by definition. Not bad!
Comment: @JeffGarrett Sadly it can't work out ([_obviously_](https://stackoverflow.com/questions/74601619/order-of-evaluation-in-v-stdexchangev-predecessorv/74607694#74607694:~:text=requires%20either%20making%20the%20push%20operation%20a%20side%20effect%20of%20the%20condition%20(which%20is%20objectively%20worse%20because%20that%20operation%20doesn%27t%20already%20exist%20with%20well%2Dknown%20semantics%2C%20unlike%20std%3A%3Aexchange)%20or%20...%20duplicating%20that%20outside%20of%20the%20loop%20body)) because it omits a node from the path sometimes: http://coliru.stacked-crooked.com/a/d1d91fb0f13b7df2
Comment: Indeed. Compared to next instead of previous. Then I don't have a better one. :)
Answer: C++17 introduced rules on sequences. What was UB before is now well defined. This applies to arguments to function calls as well as a select assortment of operators:

sequenced before is an asymmetric, transitive, pair-wise relationship
between evaluations within the same thread.

If A is sequenced before B (or, equivalently, B is sequenced after A), then evaluation of A will be complete before evaluation of B
begins.

The built-in != however is not sequenced (see link above). A function call would be sequenced but the order of evaluation is not guaranteed:

In a function call, value computations and side effects of the
initialization of every parameter are indeterminately sequenced with
respect to value computations and side effects of any other parameter.

(emphasis added)
To my reading, even if you wrote a wrapper function, your compiler would not be required to evaluate v first, then std::exchange(v, pmap[v]) and finally equal(..). And reversing the evaluation order, I believe, would change semantics in your example.
So sadly, as nice as std::exchange is, in this case, it is not guaranteed to do what you need it to.
Comment: @bitmask different calling conventions have different preferences for order of evaluation. One of the historically most popular is stack-based cdecl, which prefers right to left.
Comment: Ha. I had [that quote](https://en.cppreference.com/w/cpp/language/eval_order#:~:text=In%20a%20function%20call%2C%20value%20computations%20and%20side%20effects%20of%20the%20initialization%20of%20every%20parameter%20are%20indeterminately%20sequenced%20with%20respect%20to%20value%20computations%20and%20side%20effects%20of%20any%20other%20parameter.) copied to comment just before you realized and started editing. Kinda sad. It looks like this is the state of affairs ¯\\_(ツ)_/¯
Comment: @bitmask  A long time ago, [Hyman Rosen](https://stackoverflow.com/users/197411/hyman-rosen) wrote a [paper](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0431r0.htm) to mandate a strict right-to-left order of evaluation. That paper unfortunately went nowhere.
Comment: Edit: Sorry I misread a point. Corrected answer.
Comment: @sehe Yes, my brain somehow parsed the word "indeterminately" as "determinately". :)
Comment: It's unclear to me why the committee didn't follow through with sequencing and make it mandatory to be done in order. What possible optimisation could there be in allowing the compiler to choose evaluation order? Oh well, I'm not a compiler dev, so what do I know.
Answer: If != calls an overloaded comparison operator that takes the left argument (v) by reference, the order of evaluation here does not really matter: binding a reference (directly) does not access the object denoted by the initializer. The actual comparison (in the body of the operator function) takes place after both operands are evaluated ([intro.execution]/11):

When calling a function [...], every value computation and side effect associated with any argument expression [...] is sequenced before execution of every expression or statement in the body of the called function.

In other words, the comparison is guaranteed behave as you expect here.

This does not hold if evaluating the left side involves reading the value of v, as in the case of the built-in != operator, or an overload taking it by value (or requiring a conversion to bind a reference).
In that case, it becomes significant that the two operands are unsequenced ([intro.execution]/10):

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.

(The != operator does not have any special sequencing properties.)
There is potential for UB here:

If a side effect on a memory location is unsequenced relative to either another side effect on the same memory location or a value computation using the value of any object in the same memory location, and they are not potentially concurrent, the behavior is undefined.

However, [intro.execution]/11 applies:

For each function invocation or evaluation of an await-expression F, each evaluation that does not occur within F but is evaluated on the same thread and as part of the same signal handler (if any) is either sequenced before all evaluations that occur within F or sequenced after all evaluations that occur within F.

Summarized by a footnote:

In other words, function executions do not interleave with each other.

Which means the read of v on the left and its modification on the right (which occurs within std::exchange) can't conflict, and are effectively indeterminately sequenced: there's no UB, but no guarantee of consistent results either.

C++17 made some changes to the rules of evaluation order, but none are relevant here: this answer holds pre-C++17 as well.
Comment: Nice sources. It looks like c++17 made it unspecified rather than UB. That's an important difference. Is there a reason you call it UB?
Answer: Regardless of whether or not this works, it is almost completely unreadable code -- and remember that we write code mostly for humans, not compilers!
As a general rule, using conditionals that have side effects are often hard to read and understand because our brains are not equipped to do two things at once: Understand whether the condition is true or false, and also keep track of what changes. Do one thing at a time if you want others to easily understand what is happening. In your case, you are adding a third dimension to it: when something changes; using conditionals in which you have a function call that changes something, and comparing the changed result against something else is just impossible to read :-)
If you absolutely must use this idiom, separate the three parts:
do {
    path.push_front(v);
} while ([&v,&pmap]() mutable
         {
           auto old_v = v;
           v = pmap[v];
           return v != old_v;
         } ());

This code is equivalent, of course, but I think it is far easier to read. Although I will claim that it is still harder to read than your alternative code without using std::exchange() :-)
Comment: I also wished that the condition in the trailing `while` would be in scope of the body of the loop, because then one could have moved the declaration of `old_v` into the body of the loop and referenced it from the `while` condition. That would also have avoided the lambda function. But that too just is what it is :-)
Comment: `[&]{ auto old_v = std::exchange(v, pmap[v]); return v != old_v; }()` is a bit terser.
Comment: Thank you +1.  I came up with [several versions not dissimilar to this one](https://fosstodon.org/@sehe/109422130042322033) (though I like them all a bit better than the form presented here). Love that you unironically wrote an immediately invoked lambda in the condition of a do-while loop in c++ and called it "easier to read" :=P My version was a Very Bad Idea in C++. Readability wasn't the bad part. You can see [which version I went with](https://stackoverflow.com/questions/74601619/order-of-evaluation-in-v-stdexchangev-predecessorv/74607694#comment131684717_74601619).
Comment: (By the way I like your reasoning about what makes code understandable. I'm *not* sure what you refer to with "if you absolutely must use _this idiom_" - it seems you kept only the requirements/behavior, and yeah, that's a given of course)
Comment: @sehe "this idiom" = "the `do`...while loop in which you do some work in the `while` condition". I wished that that could be done using a compound statement rather than having to declare then immediately invoke a lambda, but that's just how it is :-)


Far Cry 4 emblem meaning?

Question: What is the emblem in the top right corner of the screen next to the rupees when you're looking at the map? I've looked all over and can't find it but I have noticed that it changes frequently.
Answer: Are you referring to the loot bag symbol? The amount of items in your loot bag may differ.

Far Cry 4 emblem meaning?


How does Regulator invention work?

Question: In Tesla vs Lovecraft how does the regulator perk work? It states that it shuffles the perk offerings for new perks. How does this work and how can I use it?
Answer: For each level in this upgrade, you get to press "shuffle" button in the perk selection screen. It gives you two new choices to choose from.

How does Regulator invention work?


Vim and Notepad++ show different indentation

Question: Previously I mainly used Notepad++, and used it to develop many SQL scripts. In Notepad++, the indent are fine. Now I switched to Vim, but found many lines indented well in Notepad++, are not indented correctly in Vim.
e.g in Notepad++, it shows
   declare @a int
   declare @b int
   declare @c int

But when open in Vim, it shows
  declare @a int
       declare @b int
 declare @c int

If I fix it in Vim, then when I open it using Notepad++, the format is messed up. Why does it happen, and how to fix it?
Comment: You're probably indenting with some combination of spaces and tabs, and then Vim has a different tab width set.
Comment: Marius gave the correct answer already. You might want to look into `:help 'listchars'` to get a better visual feedback of such whitespace mixing.
Comment: [Tabs are evil](http://www.emacswiki.org/emacs/TabsAreEvil)
Comment: @mouviciel: Linking to an emacs page on a Vim question. Priceless. :)
Comment: @bitmask - I am more open-minded about vim vs. emacs than about spaces vs. tabs :)
Answer: Marius gave the correct answer in comment, I suggest using
set listchars=tab:»·,trail:·
set list

in your .vimrc. It will display tabulations and trailing spaces at the end of lines.
You might also want, but this is a matter of personal reference, to add the following to make sure, that every every time you use Tab, you actually insert the same number of spaces. In my example, a tabulation corresponds to 4 spaces, but you can use something else.
set shiftwidth=4             " used by >>, << and tab.
set tabstop=4                " number of space characters used when displaying TAB
set expandtab                " replace TAB by spaces
set softtabstop=4            " will erase 4 spaces at once when using BS in the begining of lines only

Finally, to apply these new settings to an existing file, you might want to run on your file.
:%retab

Be aware that different editors tend to by default, display different width whenever Tab is used, this can be useful if different people want their code to be laid out differently, but this is also tends to break the indentation when not carefully used.
I think the best solution is still to use tab for indentation, spaces for alignment, but this is hard to maintain. See an example there. The dumb and fullproof solution is to use spaces every where, and this is the set up I have just described.


Longest Prefix Match Routing Table

Question: I have to build a smallest routing table using longest prefix matching with an address pool of 1024 addresses.  32 goes to A, 48 to B, 48 to C, 128 to D.
What I have so far is this:
192.168.100.X/27  A (X is supposed to be 25 + B mask + C mask?)
192.168.100.Y/    B (Y is supposed to be 25 + C mask?)
192.168.100.25?/  C
192.168.100.0/25  D

The way I understand it, D needs 128 addresses going in.  So (2^32)-(2^25) = 2^7 = 128.  So the subnet mask(the number after / ) is 25.
So how do I get 48?  48 is not a power of 2.
What does it mean to be "smallest"?  Does it just mean that there is minimal overlap of address ranges?
Can anyone help me out and correct any misunderstandings I might have on this topic?
Answer: A: 32 = /27
B: 48 = /27 + /28

C: 48 = /27 + /28

D: 128 = /25

2x/28 3x/27 1x/25 which is a total of 256 addresses.
Which leaves 768 adresses remaining, which usually are in your route table but not further defined by a longer prefix match - the higher the prefix number, the longer the prefix is.
With the suggestion below, this leaves 768 ip's free, as a coherent block. If you would, instead, assign A B C and D randomly from the 1024 addresses it would mean that you are severely limiting yourself for any future assignments towards new customers due to the gaps and holes you create in the block, effectively waisting IP space.
So your routing table would contain the following:
192.168.100.0/22 - default route defining the 1024 addresses.

192.168.100.0/25 - routed towards D (128)

192.168.100.128/27 - routed towards B (32)

192.168.100.160/28 - routed towards B (16+32=48)

192.168.100.176/28 - routed towards C (16)

192.168.100.192/27 - routed towards C (32+16=48)

192.168.100.224/27 - routed towards A (32)

The slash 22  is what you'd normally announce to your peers and transits externally, instead of announcing numerous longer prefixes. As the slash 22 covers all of them, there is no need to. And when the traffic reaches your internal network, the longer prefixes take preference.
If I had to guess what is meant by smallest it is probably referring to the above, or by keeping all the subnets within a single slash 24 block.

Longest Prefix Match Routing Table


Can I trade my Gen 1 Gameboy Pokemon all the way up to Sun/Moon?

Question: I recently rediscovered my old Pokemon Red game complete with my original Pikachu that I trained while I was a kid. What I'd like to do is try to trade it to my Sun game that I've just recently purchased using the intermediary gens and hardware as required.
I'm curious if it's even possible to get my Gen 1 Pikachu up to Sun. Any games, hardware, or software is fair game for this little project.
Answer: No. This is only possible with the Virtual Console version of the first generation games.
The Pokémon data format changed significantly in 3rd generation, so the two were incompatible. The GBA link cable and Gameboy link cable functionalities are fundamentally incompatible.


How to return the value of a variable to the previous class in Flutter?

Question: I pass isSendEmail boolean variable to another AboutPageWidget widget, in this widget I change the value of this variable and I want it to return to screen 1, how to do that, how to get the value of isSendEmail variable on screen 1?
screen 1
Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    AboutPageWidget(isSendEmail: isSendEmail),
                    const SizedBox(
                      height: 42,
                    ),
                    isSendEmail
                        ? SetNewPasswordFields(
                            newPasswordCubit: newPasswordCubit,
                          )
                        : const EmailFieldWidget(),
                  ],
                ),

screen 2
class AboutPageWidget extends StatefulWidget {
  AboutPageWidget({
    Key? key,
    required this.isSendEmail,
  }) : super(key: key);

  bool isSendEmail;

  @override
  State<AboutPageWidget> createState() => _AboutPageWidgetState();
}

class _AboutPageWidgetState extends State<AboutPageWidget> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [
            Expanded(
              flex: 1,
              child: Align(
                alignment: Alignment.centerLeft,
                child: IconButton(
                  onPressed: () => widget.isSendEmail
                      ? setState(
                          () => widget.isSendEmail = !widget.isSendEmail,
                        )
                      : _onBackPressed(context),

Answer: Navigater has a .then method so you can do
Navigator.of(context).push(nextscreen).then(result=>{
  // Result will contain the data you passed back
});

and on the next screen
Navigator.pop(variable);

Comment: I like this solution, if you're sharing state between screens I'd recommend this approach, if it's between regular widgets then my solution will be enough.
Answer: Unless you want your code to be really messy, It'd be much better to use simple state management. Provider should come in handy.
Answer: You must define a callback in the screen2 then listen to it on screen.
For example:
Screen1:
Column(
    mainAxisAlignment: MainAxisAlignment.start,
    children: [
    AboutPageWidget(
        isSendEmail: isSendEmail,
        isSendEmailChanged: (value) => setState(() => isSendEmail = value);
    ),
    const SizedBox(
        height: 42,
    ),
    isSendEmail
        ? SetNewPasswordFields(
            newPasswordCubit: newPasswordCubit,
            )
        : const EmailFieldWidget(),
    ],
),

Screen2:
class AboutPageWidget extends StatefulWidget {
  AboutPageWidget({
    Key? key,
    required this.isSendEmail,
    required this.isSendEmailChanged,
  }) : super(key: key);

  ValueChanged<bool> isSendEmailChanged;
  bool isSendEmail;

  @override
  State<AboutPageWidget> createState() => _AboutPageWidgetState();
}

class _AboutPageWidgetState extends State<AboutPageWidget> {
    @override
    Widget build(BuildContext context) {
      return Column(
        children: [
          Row(
            children: [
              Expanded(
                flex: 1,
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: IconButton(
                    onPressed: () => widget.isSendEmail
                        ? widget.isSendEmailChanged(!widget.isSendEmail)
                        : _onBackPressed(context),

Then inside _AboutPageWidgetState whenever you want to emit that isSendEmail has changed, just call widget.isSendEmailChanged with the new value.
For more complex states, I'd recommend using Provider or some other state management solution.
Comment: That is, this ValueChanged means that when any variable with the bool type is changed, then its value will be saved here?
Comment: And how to change the value in widget.isSendEmailChanged? Just through the setState method?
Comment: Yup, that's what ValueChanged does, it's just a typedef that resolves to `void Function(T value)`, where the T generic will be the type you pass in `bool` in this case
Comment: I've updated the screen2 code with how to change the value, just replacing the setState() method call with `widget.isSendEmailChanged(!widget.isSendEmail)`
Comment: Thank you very much, everything works, now I will use this option!


form send again after reload

Question: I have a normal form on my page. After I sent the form, I can reload and it will send the same a second time. I don't want that something like this happen.
How can I fix the problem? I don't want to use Header("location"), because the user should see a message like = "Successfull". And I had often problems with Header("location").
Here is my Code:

<?php
    $article_id = $_GET['post'];
    if(isset($_REQUEST['submit'])){

        $article_id = $_GET['post'];
        $name = $_POST['name'];
        $nachricht = $_POST['nachricht'];
        $aufgabe = $_POST['aufgabe'];
        $random = $_POST['random'];

        $successfull = FALSE;
        $error_message_empty = "";
        $counter = 0;

        if(empty($name)){
            $successfull = FALSE;
            $error_message_empty = $error_message_empty . "
Name
";
            $counter++;
        }

        if(empty($nachricht)){
            $successfull = FALSE;
            $error_message_empty = $error_message_empty . "
Nachricht
";
            $counter++;
        }

        if(empty($aufgabe)){
            $successfull = FALSE;
            $error_message_empty  = $error_message_empty . "
Spamschutz
";
            $counter++;
        }
        else{
            $sql = "SELECT * FROM captcha WHERE captcha_id='".$random."'";
            $result = mysqli_query($db, $sql);
            while($row=mysqli_fetch_assoc($result)){
                if(!($row['captcha_solution'] == $aufgabe)){
                    $successfull = FALSE;
                    $error_message_empty  = $error_message_empty . "
Spamschutz
";
                    $counter++;
                }
            }
        }

        if($counter != 0){
        }
        else{
            $successfull = TRUE;
        }

        if($successfull == TRUE){
            $eintrag = "INSERT INTO comments (comment_author, comment_date, comment_message, comment_post_id) VALUES ('$name', NOW(), '$nachricht', '$article_id')";
            $eintragen = mysqli_query($db, $eintrag);
            header('Location: index.php');  /* Here is the header -------------------------------------------*/
        }

        if(!(empty($error_message_empty))){
            $error_message_empty = "
".$error_message_empty;
            $error_message_empty = $error_message_empty . "
";
        }
    }

?>

        <?php
            $select = $_GET['post'];
            $sql = "SELECT * FROM posts WHERE post_id='".$select."'";
            $result=mysqli_query($db,$sql);

            while($row=mysqli_fetch_assoc($result)){
                $sql2 = "SELECT * FROM categories";
                $result2=mysqli_query($db,$sql2);

                while($row2=mysqli_fetch_assoc($result2)){
                    if($row['post_categorie'] == $row2['categorie_id']){
                        echo "
Der ausgewählte Beitrag befindet sich in der Kategorie: $row2[categorie_name]
";
                    }
                }
            }
        ?>

        <?php
            $sql = "SELECT * FROM posts WHERE post_id='".$select."'";
            $result = mysqli_query($db, $sql);
            $counter = 1;
            while($row=mysqli_fetch_assoc($result)){
                echo "
";
                    echo "$row[post_title]";
                    echo "
";
                    $d = date_create($row['post_date']);
                    $datum = $d->format('j.m.Y \u\m H:i \U\h\r');
                    echo "geschrieben von $row[post_author] am $datum";
                    echo "
";
                    echo "
";
                    echo "
$row[post_message]
";

                    echo "
";
                        $counter2 = 1;
                        for($i = 1; $i <= 4; $i++){
                            if($row['post_image_'.$i] != "0"){
                                if($counter2 % 2 == 0){
                                    echo '';
                                    $counter2 = 0;
                                }
                                else{
                                    echo '';
                                }
                            }
                            $counter2++;
                        }
                    echo "
";

                    if($counter != mysqli_num_rows($result)){
                        echo "
";
                    }
                    $counter++;
                echo "
";
            }
        ?>

            Hinterlasse doch ein Kommentar

            Alle unten aufgelisteten Felder müssen ausgefüllt werden.
            <?php
                if(!(empty($error_message_empty))){
                    echo "
";
                        echo "Folgende Felder wurden nicht korrekt ausgefüllt:
";
                        echo $error_message_empty."
";
                        echo "Nach der Behebung der oben aufgelisteten Fehler, versuchen Sie es erneut.";
                    echo "
";
                }
                else if(!(empty($error_spam))){
                    echo "
";
                        echo $error_spam;
                    echo "
";
                }
                else if(isset($successfull)){
                    if($successfull == TRUE){
                        echo "
";
                            echo "Der Kommentar wurde erfolgreich erstellt!";
                        echo "
";
                    }
                }
            ?>
            <form class="contact-formular" action="index.php?post=<?php echo $article_id ?>" method="POST">
                Name:
<input name="name" type="text"  maxlength="30" value="<?php if(isset($_POST['name'])){ echo $_POST['name'];}?>">

                Nachricht:
<textarea name="nachricht"><?php if(isset($_POST['nachricht'])){ echo $_POST['nachricht'];}?></textarea>

                Captcha:

                <?php
                    $sql = "SELECT * FROM captcha";
                    $result = mysqli_query($db, $sql);
                    $random = rand(1, 3);
                    while($row=mysqli_fetch_assoc($result)){
                        if($random == $row['captcha_id']){
                            echo "";
                            echo "<input type='hidden' name='random' value='$random' />";
                        }
                    }
                ?>

<input name="aufgabe" type="text"  maxlength="30">

                <button class="contact-formular-button" name="submit" type="submit">Kommentar abschicken</button>
            </form>

            <?php
                $select = $_GET['post'];
                $sql = "SELECT * FROM comments WHERE comment_post_id='".$select."' ORDER BY comment_date DESC";
                $result=mysqli_query($db,$sql);
                $number = mysqli_num_rows($result);

                if(empty($number)){
                }
                else{
                    echo "
";
                    echo "Bereits erstelle Kommentare
";
                    while($row=mysqli_fetch_assoc($result)){
                        echo "
";
                        $d = date_create($row['comment_date']);
                        $datum = $d->format('j.m.Y \u\m H:i \U\h\r');
                        echo "Geschrieben von $row[comment_author] am $datum

";
                        echo "$row[comment_message]
";
                        echo "
";
                    }
                }
            ?>

And now i get an error message: Cannot modify header information - headers already sent by (output started at /users/skeptar/www/Website/index.php:18)
I dont know how to fix that.
Comment: header("Location: ..") would be the correct solution for a situation like this. To show a success message, you can just create a seperate page that shows the message.
Comment: *"And i had often problems with Header("location")"* - Let me guess... headers already sent.
Comment: With problems i mean, it often dont work. I tested it local but on a webspace it didnt worked.
Comment: Probably because you may be outputting before header. Add error reporting to the top of your file(s) right after your opening PHP tag
for example `<?php error_reporting(E_ALL); ini_set('display_errors', 1);` then the rest of your code, to see if it yields anything, which could be the reason. Otherwise, use a meta method where you can redirect within a specified amount of seconds and with a message to show up until it does redirect.
Comment: However, the code you posted isn't what needs to be worked with. We need to see your PHP for it, not the HTML form.
Comment: Okay thanks for the answer! I will answer this evening.
Comment: I posted the Code in my question
Comment: If you had problems with header, add `exit;` after the header. I.e.: `header('Location: index.php'); exit;` that will stop further execution of any code below that. Many times, that fixes the problem.
Comment: Nope in this case not. I get this error code: ` Cannot modify header information - headers already sent by (output started at /users/skeptar/www/Website/index.php:18) in ` is that enough info?
Comment: That's because you have output before the header. You can't have anything above it. If you have a form, or included file, or possibly a BOM (byte order mark), that will also cause the headers already sent. You can try doing this though `<?php ob_start(); $article_id = $_GET['post'];` rest of your code. That sometimes fixes it.
Comment: Too many things for me to explain to you. You have a lot to learn and I won't be able to continue commenting like this. You have an answer below. You can also read the following and read it attentively. http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php Good luck.
Answer: You can, after success or unsuccess form submission, use:
header('Location: success.php');

or you can use PGR pattern:
PGR Pattern
Comment: Cool graphic. Now where's the icon for *"Don't put anything above this, otherwise you'll get a `headers already sent...` warning"*? - OP stated: *"And i had often problems with Header("location")"*
Comment: @Fred-ii-, wikipedia is an open-source plataform where anyone can help...you should improve that article, justo follow the link above the image.
Comment: *Hm...*, interesting and a good idea; I might just do that. *Cheers*
Comment: btw thanks for the answer! i try to understand the image + wikipedia ^^

form send again after reload


Packet tracer UI zoomed in (double the size)

Question: I've an issue with some of the programs, packettracer among them, having a zoomed in feel to them and it is eating up screen real estate. Unfortunately I have no idea how to switch to default nor what exactly caused it.
From picture below the icons are bigger than usual, even pixelated. I maximized window to show the extent of it (close, minimize and maximize buttons are visible once mouse is hovering at the menu bar).
Here's an example of what I see:
Compared to what it should look like:
Please ignore the launcher size --- it is irrelevant to the problem.
Program in question, packettracer was downloaded from here and installed from command line.
Running Ubuntu 16.04.3 LTS with 1920x1080 resolution
Any help is greatly appreciated!
Edit: wording
Comment: Is this a HiDPI system?
Comment: 96 dpi, not HiDPI, if I'm not wront
Answer: Might be a DPI issue as @muru pointed out. Thank you, btw. When resolution is changed to 1600x900 everything is OK and bigger (better for the eyes)
Answer: Also had this issue recently where the icons in packet tracer were over zoomed and pixelated when running in 1920x1080 (only looked right running at 1600x900).
I believe your issue is due to the environment variable, 'QT_DEVICE_PIXEL_RATIO=auto' being set in /etc/profile during installation of packet tracer. When running 'env | grep QT_DEVICE_PIXEL_RATIO' the variable was set at 2.
For me, commenting this out and rebooting resolved the issue.
Comment: Thanks for the input, wills117!
Comment: Issue persisted on 18.10. Changing the `QT_DEVICE_PIXEL_RATIO` to `1` and reboot fixed the issue for me.

Also, on Cisco Packet Tracer 7.2 `libpng12` library is missing, which can be downloaded from [here](https://packages.ubuntu.com/xenial/amd64/libpng12-0/download).
Answer: Had the problem that QT_DEVICE_PIXEL_RATIO resets to auto after reboot. This can be fixed by going to the /home/user and adding the line QT_DEVICE_PIXEL_RATIO=1 to the file .bashrc


Use CSS rule on Mouse hover

Question: I have a dial that moves automatically, and I would like to figure out a way to have it move only when the mouse hovers over the div. I have read that it may not be possible to do this in javascript, but I am hoping some one here might have a solution.
Here is what I have so far.
https://jsfiddle.net/r0w71wkv/
#logo {
    display: inline-block;
    position: relative;
}
#logo .speedometer {
    width: 80px;
    height: 80px;

}
#logo .needle {
    width: 5px;
    height: 80px;
    background: #324A90;
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
    border-top-left-radius: 100%;
    border-top-right-radius: 100%;
    display: inline-block;
    left: 110px;
    position: absolute;
    top: 10px;
    -webkit-animation:move 5s infinite;
    transform:rotate(0deg);
    transform-origin:bottom;
}
@-webkit-keyframes move {
    0% {
        transform:rotate(-180deg);
    }
    50% {
        transform:rotate(90deg);
        }
    100% {
        transform:rotate(-180deg);
    }
}

Answer:
:hover Psudeoclass
Only active when the element preceding it is being hovered.

Using :hover:
#logo .needle:hover {
    -webkit-animation:move 5s infinite;
    animation:move 5s infinite;
}

Then get rid of the -webkit-animation that you have currently. This will play the move animation only when you hover over the .needle element in #logo.
Also, you don't need to prefix animation much anymore: http://caniuse.com/#search=css%20animation
Here's  a fiddle: https://jsfiddle.net/r0w71wkv/5/.
I might note that you could be better off first setting the width and the height of the #mainwrap div, and then using #mainwrap:hover .needle, because that way the user doesn't have to hover directly over the needle. This would like: https://jsfiddle.net/r0w71wkv/6/.
Comment: I have tried using .needle:hover, but I just lose the animation all together. Same when I lose the webkit.
Comment: @user2168066 Try using https://jsfiddle.net/r0w71wkv/7/. I think the problem is that you have to hover *exactly* over the needle with the other approach, when this in fact defines an 80px by 80px area where you can hover to play the animation.
Comment: Ok I see now, the problem was having to hover directly over the specific div, thanks for the help.

Use CSS rule on Mouse hover


Doctrine : only one row is returned

Question: I am getting crazy with that. The request is easy
Symfony 2.7
Position : my object Repository
<code>    $qb = $this->getEntityManager()->createQueryBuilder()
        ->select('hascotctp')
        ->from('ACCUEILBundle:' .$className, 'hascotctp');
    $qb->where($qb->expr()->eq('hascotctp.numcot', ':numcot'))
       ->setParameter('numcot', $cotisation->getNumcot());
    $qb->orderBy('hascotctp.dateff');

    $result = $qb->getQuery()->getResult();
</code>
Normally there are 2 records in the table but, unfortunatly there is only one inside $result array : the first one.
second record wanted !
I go inside Symfony debug bar to check database requests and I found it :
<code> SELECT t0_.NUMCTP AS NUMCTP_0, t0_.FINDATEFF AS FINDATEFF_1, t0_.NUMCOT AS NUMCOT_2,
   t0_.DATEFF AS DATEFF_3
 FROM ttrhascotctp t0_
 WHERE t0_.NUMCOT = 199
 ORDER BY t0_.DATEFF ASC
</code>
this request returns 2 records.
So what is going on with Doctrine ? (or with me ?)
I replace getResult with infamous getArrayResult(). Now I have the 2 records but of course not as a collectgion of objects.
Answer: Perhaps the second record has problems when trying to create an object from it. Is it possible to get it directly? For example, if you add an additional condition:
<code>$qb->andWhere($qb->expr()->eq('hascotctp.id', ':secondId'))
   ->setParameter('secondId', SECOND_ID_HERE);

# Does it contain only the second entry?
$result = $qb->getQuery()->getResult();
</code>
Another possible reason is caching or fetching records from a previously loaded list. Although it's unlikely.
Does this strange behavior occur specifically for these two records, or for any other criteria too?
You can learn about some specific of getResult() behavior by looking at the Doctrine HYDRATE_OBJECT mode documentation.

Doctrine : only one row is returned


How get across the library in the French chateau?

Question: I'm playing Uncharted 3 and I'm stuck in the library of the French chateau. I need to help Sully move some beam, but I can't see how to get across.
I tried jumping on either side of the room or tried climbing, but it doesn't seem to work.  Drake said something about lifting the chandelier, but I don't see anything I can interact with.
So how do I get to the other side of the library?
Answer: You climb to the side opposite of Sully.  Once there jump to the hanging chandelier and use it to jump to the opposite side of the room.  On that wall there is a crank that you can operate using the triangle button that will raise the chandelier and allow you to use it to jump across again.
Comment: Didn't notice there was a gap in the middle I could jump through, thanks for the tip!


How are Pokestops chosen?

Question: After playing the game for a little while, I've noticed that Pokestops are chosen seemingly at random locations on the map. A few of them are even in inaccessible places; an abandoned church building, inside of an airforce base, etc. How are these locations chosen as Pokestops?
Comment: My guess is that Niantic has for the most part used the portal database build by the Ingress community and for some of them they've used their own Fieldtrip application's database.
Comment: VTO, The question would be about Design and Development had it asked why or how the developers chose to implement the Pokestop feature. Asking what requirements are needed for a landmark to be chosen as a Pokestop is just as valid as [How does incense work?](http://gaming.stackexchange.com/questions/272667/how-does-incense-work?rq=1) or [How do gyms work?](http://gaming.stackexchange.com/questions/272556/how-do-you-properly-utilize-gyms?rq=1)
Comment: I'm retracting my VTC as while this may have an element of game design, it seems to be more about asking how the mechanic itself works.
Answer: Pokémon GO's database is based on Niantic's portal database for Ingress, which is currently not accepting new requests for more locations while they review the process.
If you want to see every current PokéStop, download and register for Ingress, then go to https://www.ingress.com/intel
There are some plugins you can download to facilitate the discovery of Stops and Gyms based on that information (and even help updating the ones that still aren't registered as either).
Keep in mind that, while every PokéStop and Gym are based on Ingress Portals, not every Portal will be a PokéStop or Gym.
Comment: People might wonder how that database was created so as an addition to the answer: Portals for Ingress were created by the players themselves. They were asked to submit portals at locations that are significant landmarks, mostly cultural or artistic things. Niantic then reviewed these submissions and if they agreed that it was significant enough it became a portal. Due to being unable to review the increasing amount of submissions and I think also because there are enough portals already Niantic disabled the portal submission ability at some point
Comment: Not all locations in Ingress is converted over to Pokémon Go, the once I have seen missing is where a lot of points are close together in Ingress, guessing there is a minimum distance between multiple PokéStops
Comment: Yet, in the particular small tourist city where I live(population 15,000) there are no pokestops.. even our major tourist attraction.. I really think their locations need a second or even third look. Not that anyone here can help.. just venting.
Comment: Looks like they've added a form to request PokeStops and gyms https://support.pokemongo.nianticlabs.com/hc/en-us/requests/new?ticket_form_id=319928
Comment: @VianEsterhuizen Are you sure that's not a form for reporting issues with PokéStops (e.g. dangerous locations)? [Another page about reporting issues with PokéStops or Gyms](https://support.pokemongo.nianticlabs.com/hc/en-us/articles/221968408-Reporting-PokéStop-or-Gym-Issues) on Niantic's website says quite clearly "we are currently not accepting submissions for new PokéStops or Gyms."
Comment: Which is why I recommended utilizing the plugins to separate what's used in PoGo. While not a 100% reference, it's definitely better than nothing.
Comment: Indeed, the name and picture on every PokéStop and Gym you've seen were submitted by an Ingress agent. I suspect we won't be seeing new PoGo location submission for quite a while - Niantic seems to have their hands full with other new features and keeping the servers up.
Comment: Since Niantic&Nintendo and Google have partnered up on the creation of the app, you'd think they would use landmarks and business locations to determine these locations with proximity limitations (say 400-500m) and have the entire map prepopulated by the massive database that is Google Maps and then have a "Pokestop location request" in order to add more points on the map.
Comment: @Thunderforge You may be right. I just saw a couple articles on the it being for requests but I see what you mean. I could be wrong.

How are Pokestops chosen?


Need help with a certain integrating technique

Question: How do I integrate this?
$$\frac{\text{d}P}{\text{d}t} = \frac{(r(t) - B)}{z} \cdot P(t) + c\cdot w$$
The t is just the top limit in the integral.
Let me be more specific. I have this:
$$\frac{dP}{dt} = g(t)P(t) + k$$ where $k$ is a constant and $g(t)$ is any function of $t$, is to put all $P(t)$ on the same side and multiply as such:
\begin{eqnarray*}
\frac{dP}{dt} - g(t)P(t) &=& K\\
e^{\int^t-g(s)ds}\frac{dP}{dt} - g(t)e^{\int^t-g(s)ds}P(t) &=& Ke^{\int^t-g(s)ds}\\
\frac{d}{dt}\Big(e^{-\int^t g(s)ds}P(t)\Big) &=& Ke^{\int^t-g(s)ds}
\end{eqnarray*}
Comment: What is the lower limit?
Comment: Which function is $g$?
Comment: I edited my post to be more specific
Comment: Check most recent update
Comment: So you just actually need help solving this differential equation using an integration factor?
Comment: Correct. I am not sure what to do at this point, and any help would be very much appreciated.
Answer: (Assuming you just want to solve the differential equation that you stated).
Note: it was stated in the comments that it may be assumed that $r(t)=at$
$g(t)=\frac{at-B}{z}$
$\dfrac{dP}{dt} = g(t)P(t) + k \iff \dfrac{dP}{dt}-gP=k$
Use $e^{-\int g dt}=e^{-\int\frac{at-B}{z}dt}=e^{\frac{Bt-\frac{a}{2}t^2}{z}}$ as your integrating factor.
Then $e^{\frac{Bt-\frac{a}{2}t^2}{z}}\dfrac{dP}{dt} -\frac{at-B}{z}e^{\frac{Bt-\frac{a}{2}t^2}{z}} P=ke^{\frac{Bt-\frac{a}{2}t^2}{z}}$
Or equivalently, $\dfrac{d}{dt}\left(e^{\frac{Bt-\frac{a}{2}t^2}{z}}P \right)=ke^{\frac{Bt-\frac{a}{2}t^2}{z}}$,
From here you would need to integrate on both sides, but that doesn't seem like a walk in the park (the expression on the right hand side could in fact only be expressed in terms of error functions).
Comment: Thank you for the help! But how do I integrate? that was my question from the beginning
Comment: @JacksonHart The thing is, we don't really know much about your function $g$, in fact, not even every general function $g$ is integrable. So I'm not sure if it is possible to work this out further (if you would give me a specific function $g$ I could do it, but that's not the case here).
Comment: If you scroll to the very very top I added the function. You can see what I called "g"
Comment: @JacksonHart Ah ok, the text is slightly confusing because later on you say that $g$ is any general function of $t$. Are $B$ and $z$ constants?
Comment: yes but r(t) is not
Comment: @JacksonHart Since $r(t)$ is still a general function of $t$, I think there isn't really a point in working this out further then still, I'm afraid.
Comment: Oh wow my mistake. I can assume r(t) = -a*t
Comment: @JacksonHart That changes everything. Give me a moment.
Comment: It looks good for the most part, though r(t) = neg(a*t) I think you thought it was positive
Comment: Would changing it to what it should be, negative(a*t) help things?
Comment: @JacksonHart I think I misread. But only a few signs would change (plusses would become minusses and vice versa). That wouldn't make a difference. Since your function $r$ is a linear function of $t$, you will always end up with a factor $e^{t^2}$, which is a non-integrable function (if you exclude error functions).
Comment: would i still use the same integrating factor/
Comment: becuase the diffeq would become + instead of minus
Comment: @JacksonHart Yes, you would. You use this technique since this is a first order differential equation. The fact that this is so, is not dependent on the constants. http://en.wikipedia.org/wiki/Linear_differential_equation#First_order_equation
Comment: right, but wouldnt it be dP/dt + g(t)P(t)
Comment: What I'm trying to say is that, no matter what the function $g(t)$ is, (so also no matter what sign it has) this remains a first order linear diff eq.
Comment: Right, I understand. I was not sure if this change would result in a solution not involving the error function
Comment: Woudlnt the exp cancel? Just the part that comes to outside would still be there?
Comment: I just realized something. We do not need to use integrating factor since I can express g(t) in terms of -at correct?
Comment: @JacksonHart No and no. It is still a function of $t$. Last thing I'm gonna say about it.


Android UX - when to use Tabs and when to use Navigation Drawer?

Question: I'm looking for guidelines regarding when to use Tabs vs. when to use a Navigation Drawer(sidebar).
For example, as of these days, Facebook and Dropbox, which are extremely popular (+100M users), use tabs and do NOT use the sidebar. See screenshots below.
Many other Android apps, including Google's, do use the sidebar.
It feels like both tabs and the sidebar belong to the same navigation concept but have a different implementation.
So, If my app includes 3-4 main views, what should I use? Tabs or Sidebar?
Thanks.
Answer: Per the Material Design Guidelines on top-level view strategies, three main strategies are:

Focus on a single view with embedded navigation. By putting all the necessary navigation directly inline with other app content, you make it extremely visible to the user. This can be appropriate when the app's navigation model is very simple. However, presenting a large number of navigation paths in this manner can reduce the space available to display content. These pathways could be distributed throughout the screen rather than co-located in a predictable and convenient location.
Use in-context navigation if:

Your app has a strong primary view, and no or few alternate ones.
Your users can complete the most common tasks easily within the main view.
You expect users will use your app very infrequently and will appreciate well-exposed paths.

Use tabs to switch between a small number of equally important views. If your app has only a handful of functional areas, each with shallow hierarchies, using tabs increases the awareness of these peer top-level views. It also accelerates switching between them, bringing them into view with just a click or a swipe. However, displaying the tabs takes up significant space on smaller displays, and is efficient only for a small number of peers with succinct labels.
Use tabs if:

You expect your app's users to switch views frequently.
You have a limited number of top-level views.
You want the user to be highly aware of the alternate views.

Manage more complex structure through a left navigation drawer. The left nav panel can display large numbers of navigation targets concurrently. It is particularly useful when your app has a single, natural "home", and the drawer can then act as an index of less frequently visited destinations. If your app requires cross-navigation directly from a lower-level screen to other important sections of your app, the ability to swipe in the side nav panel from any point in your app can make that context switch more efficient for the user. However, because it is a less obvious affordance, it may take the user time to familiarize themselves with the contents.
Use a navigation drawer if:

Your app has a large number of top-level views.
You want to enable quick cross-navigation between views which aren't directly related.
You have particularly deep navigation branches and want to accelerate returning to the top of the app.
You want to reduce the visibility and user awareness of less frequently visited destinations.

Therefore it seems like tabs would be the best fit if you have 3-4 main views of near equal importance.
Comment: You could improve that answer a lot by commenting on single parts of the quote independently, and not just on the whole thing
Comment: Updated link for Material Design guidelines on Top-level navigation strategies: http://www.google.com/design/spec/patterns/app-structure.html#app-structure-top-level-navigation-strategies.
Comment: Thanks @Troy - I've updated my answer with the new link.
Comment: @ianhanniballake link is broken
Answer: The issue with tabs is the space that you can show them on mobile devices. It's really good if you know that you only have say three items to show, but when it comes to future proofing, there's not enough space to go width wise without paginating. The way in which I see it is the use of tabs should be for the immediate usage in the journey and the draw is for other less frequent journeys from the where the user is. As long as you don't have heaps of interactions available to the user they will home in on what you have displayed as important. So you could just use the draw as it would potentially be the only interaction (in icon form) on that given page.


How to eliminate empty rows from an HTML table formed from a google form girdbox question

Question: I have been trying to build an easy to read order form for our EMS supply at the station. I have gotten to the point where it builds the table based on all answers, but I would like to eliminate some of the extra questions from showing up and would prefer there to only be the items that are needed in the rest of the table.
     function Mail(){
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var responses = ss.getSheetByName("Form Responses 3");
      var lastRow = responses.getLastRow();
      var values = responses.getRange("A"+(lastRow)+":AT"+(lastRow)).getValues();
      var headers = responses.getRange("A1:AT1").getValues();
      var message = composeMessage(headers,values);
      var messageHTML = composeHtmlMsg(headers,values);
      if (values =!'')
      Logger.log(messageHTML);
      MailApp.sendEmail(Session.getEffectiveUser().getEmail(),'New Order', message,{'htmlBody':messageHTML});
    }

    function composeMessage(headers,values){
      var message = 'New Order :\n'
      for(var c=0;c<values[0].length;++c){
        message+='\n'+headers[0][c]+' : '+values[0][c]
      }
      return message;
    }

    function composeHtmlMsg(headers,values){
      var message = 'New Order :

   data	Values
'
      for(var c=0;c<values[0].length;++c){
        message+='
'+headers[0][c]+'	'+values[0][c]+'
'
      }
     return message+'
';
    }

`
data    Values

Timestamp   Tue Nov 05 2019 21:58:30 GMT-0800 (PST)
Request for:    Station 1
Needs:  Medications
[Adenosine] 3
[Albuterol]
[Amiodarone]
[Aspirin]
[Atropine MDV]
[Atropine PLS]
[Atrovent]
[Benadryl]
[Bicarb]
[Calcium]
[Charcoal]
[D10]
[D50]
[Dopamine]
[Epi 1:1,000]   2
[Epi 1:10,000]
[Glucagon]
[Glucose]
[Lidocaine]
[Narcan]
[Nitro Paste]
[Nitro Spray]
[NS 100ml]
[NS 250ml]
[Saline for Inhilation]
[Tylenol]
[Ventolin]
[Zofran ODT]
[Zofran Vial]
Further Needs?  Done
[IO Blue]
[IO Pink]
[IO Yellow]
[Defib Pads]
[Chest Seals]
[4x4 QuickClot]
[Rolled Gauze QuickClot]
[OB Kits]
[Stethoscope]
[BP Cuff - Adult]
[BP Cuff - Peds]
[BP Cuff - Thigh]
[Pressure Infuser]

Comment: Above I have one of my responses and I would like it to only have the lines:
Request for: Station 1-7
and then the items that have been selected: 2 Epi 1:1,000 and 3 Adenosine

I have tried to figure out how to eliminate rows that have no result, but to no avail. Any suggestions?

Thank you for your time
Comment: Is there any chance you could post the plain HTML this generates in your answer to better assist us visualising / providing an answer?
Comment: Honestly I dont know how to do that... If you scroll down on my function above it shows the current values that fill the table.
Comment: Why not test for `values[0][c]` having a value, if yes, then insert the the html msg; if no, skip and go to next value.
Answer: Blank cells are retrieved as a String, "". So the test is === "" or conversely !=""
A re-worked composeHtmlMsg() might look like this;

function composeHtmlMsg(headers,values){
    var message = 'New Order :

data	Values
'
    for(var c=0;c<values[0].length;++c){
        if (values[0][c] != ""){
            message+='
'+headers[0][c]+'	'+values[0][c]+'
'
        }
    }
  return message+'
';
}


Are $L^2$ and total variation-linked norms equivalent on this function space?

Question: Let $K > 0$. Let $\mathcal{C} = \mathcal{C}^1([0,K], [-1,1] )$ be the space of $C^1$  functions $f : [0, K] \rightarrow [-1,1]$, such that $f(0)=0$. Let's use the norm:
$$||f||_2 = \sqrt{\int_0^K f(t)^2 d t}$$
and also the total variation:
$$||f||_T = \int_0^K |f'(t)| d t$$
Question: are there constants $a$ and $b$ such that:
$$||f||_T \leq a ||f||_2 \qquad \text{and} \qquad ||f||_2 \leq b ||f||_T$$
for all functions $f \in \mathcal{C}$ ?

Discrete analogous question:
Let $N > 0$ and $\mathcal{D}$ be the space of all sequences $(y_n)_{0 \leq n \leq N}$, with $-1 \leq y_n \leq 1$ for all $n$, and $y_0 = 0$. We use the norms:
$$||(y_n)||_2 = \sqrt{\sum_{n=0}^N y_(n)^2}$$
and
$$||(y_n)||_T = \sum_{n=1}^N |y(n)-y(n-1)|$$
Are there constants $c$ and $d$ such that:
$$||(y_n)||_T \leq c ||(y_n)||_2 \qquad \text{and} \qquad ||(y_n)||_2 \leq d ||(y_n)||_T$$
for all sequences $(y_n) \in \mathcal{D}$ ?
Note:

Ideally, the constants $a$, $b$ should be independant of $K$. The same for the discrete case.

If not true in general on $\mathcal{C}$, would it be possible to find such inequalities on a subspace $\mathcal{C}^*$ of functions that have a limited bandwidth in high frequencies? (let's say the spectrum has no or few composant of frequency $f \geq f_0$; in my audio application: $f_0$ is $20 000$ Hz).
Comment: For the first one, consider $\sin (nx), n=1,2,\dots$ For the second one, consider $f$ a constant.
Comment: have a look at Poincare inequality and Sobolev inequalities which provide various integral norm estimates for the gradient and the original function.
Comment: @zhw. I forgot to mention (now edited, fixed in the question) the condition $f(0)=0$. So $f$ constant is necessarily the $0$ constant.
Answer: For the second inequality:
$$\int_0^K f(t)^2\,dt = \int_0^K \left  (\int_0^t f'(s)\,ds\right)^2\,dt$$ $$ \le \int_0^K \left  (\int_0^t |f'(s)|\,ds\right)^2\,dt\le \int_0^K   \|f\|_T^2\,dt = K\|f\|_T^2.$$
Take square roots to see $\|f\|_2 \le \sqrt K \|f\|_T.$
Comment: That wasn't a good hint after all. I was thinking $\|f\|_T= (\int_0^K(f'(t))^2\,dt)^{1/2}.$ I changed my hint to just the one equality. This will give you the inequality, but with a constant depending on $K.$
Comment: Things only get larger if you put absolute values on the integrand. Then for each $t$ the square of the integral is $\le \|f\|_T.^2$ I'll let you work on it, and then if you don't get it i'll add more.
Comment: @Basj My answer in now a more complete solution.


Pig UDF not being able to filter words

Question: I have a file with tweets i want to extract all tweets with my filters however i get an error
public class TweetFilter extends FilterFunc {
    static List<String> filterList;

    TweetFilter() {
        filterList.add("sick");
        // Many More Filters
    }

    public Boolean exec(Tuple input) throws IOException {
        if (input == null || input.size() == 0)
            return null;
        try {
            String str = (String) input.get(0);
            if (filterList.contains(str)) {
                return true;
            } else {
                return false;
            }

        } catch (Exception e) {
            throw new IOException("Caught exception processing input row ", e);
        }
    }
}

B = FILTER A BY UDF.TweetFilter($0);

Error : could not instantiate 'UDF.TweetFilter' with arguments 'null'
Answer: If that is the entire code then your filterList will be null resulting in a NullPointerException when calling filteList.add("sick").
To resolve this, modify the line
 static List<String> filterList;

to
List<String> filterList = new LinkedList<String>();

Also, make your constructor public.
Could not instantiate is usually the error message you get when something goes wrong when calling the UDF's constructor.
Comment: Yes this is my complete code how do i resolve this NullPointerException
Comment: Thanks for your quick response. Ever after you suggestions i am facing the same error.
Answer: You should register the jar which contains your filter before trying to call it from your pig script, if you haven't done so already
Try adding:
register myudfs.jar;

As explainded in de UDFManual http://wiki.apache.org/pig/UDFManual

Pig UDF not being able to filter words


Refrigerator should be away from LPG cylinder. Why?

Question: In India (and probably other parts of the world) there's general advice regarding refrigerator positioning. It is suggested that we keep the refrigerator away from the Liquified Petroleum Gas (LPG) cylinder. Can anyone explain what exactly is the risk if it's kept in close proximity?
Update - This question is not about a LPG refrigerator. The LPG cylinder is connected separately to a hob or burner and the refrigerator is a regular electric one.
Recently at an acquaintance's residence, a suspected gas leak from the cylinder, caused an explosion and ripped off the doors of a 2-door refrigerator. There weren't any other signs of damage or burns as extensive as what happened to the refrigerator. We're trying to figure out how the gas leak outside a sealed refrigerator caused this.
Comment: In the US the LPG cylinder, if present, is kept outside the house - only a pipe comes inside. I'd speculate that the advice may stem from LPG (ammonia-cycle) refrigeration, where there's a flame in the fridge itself as part of the refrigeration cycle. Then again, perhaps it stems from avoiding an electric compressor switch that might throw sparks.
Comment: Could it have anything to do with the fact that as LPG is consumed the bottle can get very cold on the outside? If this was near to the refrigerator coils could they freeze up?
Answer: If you are talking about a Refrigerator that runs on LP gas the tank needs to be away from the fridge because the fridge has an open flame inside, on a hot day it is possible that the LP tank can vent and release some gas, also when filling or changing tanks their is a small loss of gas, the open flame could ignite the gas and this is the reason the fridge should be separated.
Comment: even "regular" electric refrigerators can cause sparks on relay contacts, creating an ignition source.
Comment: My question was more about "regular" electric refrigerators. And the LPG cylinder is connected to a hob or burner for cooking.
Comment: In any case the tank should never be located inside a home. As I already mentioned the relief valve in the tank can vent the gas. Refrigerators use open contacts not explosion proof. The compressor is normally sealed, the fan motors are usually TFEC totally enclosed fan cooled, but those contacts arc on closing and opening in the press ace of the gas this could cause an explosion the same as an open flame.
Answer: As Ed touched on, LP gas canisters must be outside because they have a pressure relief valve that will vent petroleum gas.  It is designed to protect the tank from exploding from overpressure.
Venting petroleum gas indoors would be Very, Very Bad - and would either cause a gas explosion, demolishing the house and killing everyone inside, or could migrate to the low areas of the house and cause asphyxiation.  Or both, one then the other.
There is also the normal risk of a fitting leak when changing the tank, which could happen anytime.
The tank must be outside.  Hence, not next to the fridge.


How to write SQL for combination of AND?

Question: Please check the attached table.

I need to write a query to get documents which have both tage_id of say 32 and 26.
Something like select * from doc_tags where tag_id = 32 or tag_id = 26 is not going to work as I will get both documents with 32, 26, and ( 32, 26 ).
I need documents which only have tag id 32 **and 26 not individual.**
NOTE
I can't use the document_id as a reference.
Comment: What do you mean by `type`
Comment: hello, which  output require?
Comment: tag_id= 32 & 26  record output require?
Comment: so as long as I can get the documents which have tags 32 and 26 would do the job
Comment: What DBMS is being used?
Comment: Postgresql.....
Comment: If as you say you can't reference the document_id , then you won't be able to tie together the different instances of tag_id to identify documents having both 26 and 32. It might be helpful to know why you think you can't reference the document_id .
Comment: ... your accepted answer DOES reference the document_id by the way.
Answer: select * from doc_tags dt1
where (
    select count(distinct tag_id) from doc_tags dt2
    where dt2.document_id = dt1.document_id and tag_id in (26, 32)
) = 2 and dt1.tag_id in (26, 32)

or
with data as (
    select *,
        count(distinct tag_id) over (partition by document_id) as matches
    from doc_tags where tag_id in (26, 32)
)
select * from data where matches = 2

Comment: I get document with tag 25 and 27 too!
Comment: Yes @MrH, I have no idea how you wanted to filter the final results.
Comment: Thank you. Now I need to convert this to Elixir Ecto :). Thanks again
Comment: @shawnt00, your CTE will not work correctly because you have no group by for the count. So you need a group by, and specify maybe document_id in there and then join it up eg `;with data as (
    select document_id, count(distinct tag_id) as matches
    from doc_tags where tag_id in (26, 32)
  group by document_id
)
select b.* from data a
join doc_tags b on a.document_id = b.document_id
where matches = 2 and tag_id in (26, 32)`
Comment: @Jacques. Yeah, that was too hastily edited. If you look at edit history you'll see it was previously written to return all tags.
Answer: I'd count the number of different tags the document has between those two:
SELECT   document_id
FROM     doc_tags
WHERE    tag_id IN (26, 32)
GROUP BY document_id
HAVING   COUNT(DISTINCT tag_id) = 2

Answer: If it is only going to be between 2 documents, you can do this
Select *
from doc_tags a
join doc_tags b on a.document_id = b.document_id
where a.tag_id = 26 and b.tag_id = 32

Answer: Try this type of SQL query:
select *
from doc_tags
where tag_id in (32,26)

Comment: Nope, it will return based on `or` not `and` I need to return documents which have 32 and 26
Answer: DECLARE @RESULT TABLE(doc_name VARCHAR(255))

INSERT INTO @RESULT
       SELECT document_id
       from doc_tags
       WHERE tag_id =26 AND document_id IN
            (SELECT document_id
             from #tmp
             WHERE tag_id =32)

SELECT *
FROM doc_tags
WHERE document_id in (SELECT doc_name
                      FROM @RESULT)

Answer: SELECT * FROM doc_tags WHERE tag_id = 32 and tag_id = 26

The above will only return tag_id's 32 and 26
Answer: SELECT
  d1.*
FROM
  doc_tags AS d1
INNER JOIN
  doc_tags AS d2
ON
  d1.documentid = d2.documentid AND
  (
    d1.documentid = 26 AND d2.documentid = 32 OR
    d1.documentid = 32 AND d2.documentid = 26
  )
WHERE
  d1.id <> d2.id

Answer: You can also use min()/max() function :
SELECT document_id
FROM doc_tags dt
WHERE tag_id IN (26, 32)
GROUP BY document_id
HAVING MIN(tag_id) <> MAX(tag_id);

Answer: select * from doc_tags where tag_id not in (32, 26)

Comment: There are better ways of doing this. use `not in (32, 26)` is probably the best one


android.view.InflateException: Binary XML file line #0: Binary XML file line #0:

Question: I am new in android studio and I would like a little help, I'm sorry for my bad English, it's not my native language.
When wanting to enter an activity in my application. This is over, here is the code:
W/System.err: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kefagothstudios.cleaner/com.kefagoth.cleaner.ui.RubbishCleanActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.ferdi.cleaner.widget.textcounter.CounterView

this is the activity that fails
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:counter="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

<RelativeLayout
    android:id="@+id/layout_container"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="fill_parent"
        android:layout_height="@dimen/header_height"
        android:background="@color/yellow_background"
        android:orientation="vertical"
        android:visibility="visible">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true">

            <com.ferdi.cleaner.widget.textcounter.CounterView
                android:id="@+id/textCounter"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="\ 250"
                android:textColor="@color/white"
                android:textSize="52.0sp"
                counter:autoStart="false" />

            <TextView
                android:id="@+id/sufix"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/margin_right"
                android:layout_marginTop="10.0dip"
                android:layout_toRightOf="@+id/textCounter"
                android:text="KB"
                android:textColor="@color/white"
                android:textSize="@dimen/text_size_middle" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/sufix"
                android:layout_marginLeft="@dimen/margin_right"
                android:layout_marginTop="10.0dip"
                android:layout_toRightOf="@+id/textCounter"
                android:text="Freeable"
                android:textColor="@color/white"
                android:textSize="@dimen/text_size_middle" />
        </RelativeLayout>
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/progressBar"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/header"
        android:background="?android:windowBackground"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <fr.castorflex.android.circularprogressbar.CircularProgressBar
            android:id="@+id/progressBar2"
            android:layout_width="50.0dip"
            android:layout_height="50.0dip"
            android:indeterminate="true"
            android:visibility="gone"
            counter:cpb_colors="@array/gplus_colors" />

        <com.ferdi.cleaner.views.RotateLoading
            android:id="@+id/rotate_loading"
            android:layout_width="88.0dip"
            android:layout_height="88.0dip"
            android:layout_gravity="center" />

        <TextView
            android:id="@+id/progressBarText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="4.0dip"
            android:singleLine="true"
            android:text="@string/scanning"
            android:textAppearance="?android:textAppearanceSmall" />
    </LinearLayout>

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/memory_ads_container"
        android:layout_below="@+id/header"
        android:clipToPadding="false"
        android:divider="@null"
        android:dividerHeight="4.0dip"
        android:fadingEdge="none"
        android:fastScrollEnabled="true"
        android:fitsSystemWindows="true"
        android:focusable="true"
        android:layoutAnimation="@anim/listview_layout_animation"
        android:listSelector="@android:color/transparent"
        android:padding="12.0dip"
        android:scrollbarStyle="outsideOverlay"
        android:scrollbars="none"
        android:visibility="gone" />

    <TextView
        android:id="@+id/empty"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:text="@string/empty_cache"
        android:textAppearance="?android:textAppearanceLarge"
        android:visibility="gone" />

    <FrameLayout
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/memory_ads_container"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_gravity="fill_horizontal|bottom|center"
        android:layout_marginBottom="@dimen/button_height"
        android:visibility="visible">

        <com.google.android.gms.ads.AdView
            android:id="@+id/adsView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            ads:adSize="BANNER"
            ads:adUnitId="@string/banner" />
    </FrameLayout>

    <LinearLayout
        android:id="@+id/bottom_lin"
        android:layout_width="fill_parent"
        android:layout_height="@dimen/button_height"
        android:layout_alignParentBottom="true"
        android:layout_margin="@dimen/button_margin"
        android:background="@android:color/transparent"
        android:orientation="vertical"
        android:visibility="visible">

        <Button
            android:id="@+id/clear_button"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="@drawable/btn_normal_green"
            android:gravity="center"
            android:text="Clean Junk"
            android:textAllCaps="true"
            android:textColor="@color/white"
            android:textSize="@dimen/text_size_large" />
    </LinearLayout>
</RelativeLayout>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:app1="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout_container2"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/backgroud_layout"
    android:orientation="vertical"
    android:visibility="gone">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:orientation="vertical">

        <FrameLayout
            android:layout_width="192.0dip"
            android:layout_height="192.0dip"
            android:layout_centerInParent="true"
            android:layout_gravity="center">

            <FrameLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

                <com.ferdi.cleaner.views.HoloCircularProgressBar
                    android:id="@+id/clean_done_holoCircularProgressBar"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    app1:marker_progress="0.0"
                    app1:marker_visible="false"
                    app1:progress="1"
                    app1:progress_background_color="@color/circle_progress_background"
                    app1:progress_color="@color/circle_progress"
                    app1:stroke_width="6.0dip" />

                <ImageView
                    android:id="@+id/clean_done_iv_bg"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center"
                    android:layout_margin="16.0dip"
                    android:background="@drawable/circle_floating_bg"
                    android:rotation="-30.0"
                    android:visibility="visible" />

                <ImageView
                    android:id="@+id/clean_done_iv_done"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center"
                    android:layout_margin="40.0dip"
                    android:src="@drawable/ic_cleaning"
                    android:visibility="visible" />
            </FrameLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_centerInParent="true"
                android:layout_gravity="center"
                android:gravity="center">

                <ImageView
                    android:id="@+id/clean_up_rocket"
                    android:layout_width="112.0dip"
                    android:layout_height="112.0dip"
                    android:layout_gravity="center" />
            </LinearLayout>
        </FrameLayout>

        <TextView
            android:id="@+id/clean_up_done_tv_notice"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16.0dip"
            android:layout_marginRight="16.0dip"
            android:layout_marginTop="32.0dip"
            android:gravity="center"
            android:text="@string/boost_notice"
            android:textColor="@color/white"
            android:textSize="12.0sp"
            android:visibility="gone" />

        <FrameLayout
            android:id="@+id/clean_up_done_icon_container"
            android:layout_width="144.0dip"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:paddingTop="32.0dip">

            <TextView
                android:id="@+id/clean_up_tv_done"
                android:layout_width="wrap_content"
                android:layout_height="48.0dip"
                android:layout_alignParentLeft="true"
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="32.0dip"
                android:background="@drawable/button_done_selector"
                android:gravity="center"
                android:minWidth="64.0dip"
                android:paddingBottom="8.0dip"
                android:paddingLeft="32.0dip"
                android:paddingRight="32.0dip"
                android:paddingTop="8.0dip"
                android:text="DONE"
                android:textColor="@color/phoneboost_text_top_color_white_blue"
                android:textSize="16.0sp"
                android:typeface="sans"
                android:visibility="gone" />
        </FrameLayout>
    </LinearLayout>
</RelativeLayout>

my application stops and I do not understand why, I would like an idea of why it stops, in advance thank you very much
Comment: com.ferdi.cleaner.widget.textcounter.CounterView    this view is not inflate
Answer: One issue that I definitely see is 'Android won't be able to identify app1 namespace'.
<com.ferdi.cleaner.views.HoloCircularProgressBar
                    android:id="@+id/clean_done_holoCircularProgressBar"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    app1:marker_progress="0.0"
                    app1:marker_visible="false"
                    app1:progress="1" app1:progress_background_color="@color/circle_progress_background"
                    app1:progress_color="@color/circle_progress"
                    app1:stroke_width="6.0dip" />

But since the inflateException mentions the issue with com.ferdi.cleaner.widget.textcounter.CounterView as well, there seems to be another issue with the attribute definition of the counter view. Please verify the same.


Subclassing Decimal in Python

Question: I want to use Decimal class in my Python program for doing financial calculations. Decimals to not work with floats - they need explicit conversion to strings first.
So i decided to subclass Decimal to be able to work with floats without explicit conversions.
m_Decimal.py:
# -*- coding: utf-8 -*-
import decimal

Decimal = decimal.Decimal

def floatCheck ( obj ) : # usually Decimal does not work with floats
    return repr ( obj ) if isinstance ( obj, float ) else obj # this automatically converts floats to Decimal

class m_Decimal ( Decimal ) :
    __integral = Decimal ( 1 )

    def __new__ ( cls, value = 0 ) :
        return Decimal.__new__ ( cls, floatCheck ( value ) )

    def __str__ ( self ) :
        return str ( self.quantize ( self.__integral ) if self == self.to_integral () else self.normalize () ) # http://docs.python.org/library/decimal.html#decimal-faq

    def __mul__ ( self, other ) :
        print (type(other))
        Decimal.__mul__ ( self,  other )

D = m_Decimal

print ( D(5000000)*D(2.2))

So now instead of writing D(5000000)*D(2.2) i should be able to write D(5000000)*2.2 without rasing exceptions.
I have several questions:

Will my decision cause me any troubles?
Reimplementing __mul__ doesn't work in case of D(5000000)*D(2.2), because the other argument is of type class '__main__.m_Decimal', but you can see in decimal module this:

decimal.py, line 5292:
def _convert_other(other, raiseit=False):
    """Convert other to Decimal.

    Verifies that it's ok to use in an implicit construction.
    """
    if isinstance(other, Decimal):
        return other
    if isinstance(other, (int, long)):
        return Decimal(other)
    if raiseit:
        raise TypeError("Unable to convert %s to Decimal" % other)
    return NotImplemented

The decimal module expects argument being Decimal or int. This means i should convert my m_Decimal object to string first, then to Decimal. But this is lot of waste - m_Decimal is descendant of Decimal - how can i use this to make the class faster (Decimal is already very slow).

When cDecimal will appear, will this subclassing work?
Comment: Do keep in mind that multiplying a Decimal by a float will render a reduced-accuracy Decimal, which is why this operation is not implemented in the first place.
Comment: Not sure, why you'd have to convert? `isinstance` properly takes subclassing into account... `isinstance(d, m_Decimal)` implies `isinstance(d, Decimal)`.
Comment: Your operation will surely cause problems with the purpose of decimals. Don't use them if you don't need them or if you don't understand their purpose; I reccomend you check the IEEE 754 standard.
Answer: Currently, it won't do what you want at all.  You can't multiply your m_decimal by anything:  it will always return None, due to a missing return statement:
    def __mul__ ( self, other ) :
        print (type(other))
        return Decimal.__mul__ ( self,  other )

Even with the return added in, you still can't do D(500000)*2.2, as the float still needs converting to a Decimal, before Decimal.mul will accept it.  Also, repr is not appropriate here:
>>> repr(2.1)
'2.1000000000000001'
>>> str(2.1)
'2.1'

The way I would do it, is to make a classmethod, fromfloat
    @classmethod
    def fromfloat(cls, f):
        return cls(str(f))

Then override the mul method to check for the type of other, and run m_Decimal.fromfloat() on it if it is a float:
class m_Decimal(Decimal):
    @classmethod
    def fromfloat(cls, f):
        return cls(str(f))

    def __mul__(self, other):
        if isinstance(other, float):
            other = m_Decimal.fromfloat(other)
        return Decimal.__mul__(self,other)

It will then work exactly as you expect.  I personally wouldn't override the new method, as it seems cleaner to me to use the fromfloat() method.  But that's just my opinion.
Like Dirk said, you don't need to worry about conversion, as isinstance works with subclasses.  The only problem you might have is that Decimal*m_Decimal will return a Decimal, rather than your subclass:
>>> Decimal(2) * m_Decimal(2) * 2.2

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    Decimal(2) * m_Decimal(2) * 2.2
TypeError: unsupported operand type(s) for *: 'Decimal' and 'float'

There are two ways to fix this.  First is to add an explicit conversion to the m_Decimal's mul magicmethod:
    def __mul__(self, other):
        if isinstance(other, float):
            other = m_Decimal.fromfloat(other)
        return m_Decimal(Decimal.__mul__(self,other))

The other way, which I probably wouldn't recommend, is to "Monkeypatch" the decimal module:
decimal._Decimal = decimal.Decimal
decimal.Decimal = m_Decimal

Answer: In my opinion you shouldn't use floats at all. Floats are not the right tool for a financial application. Anywhere you are using floats you should be able to use str or Decimal to ensure you are not losing precision.
For example.
User input, File input - obviously use str and convert to Decimal to do any math
Database - use decimal type if it is supported, otherwise use strings and convert to Decimal in your app.
If you insist on using floats, remember that python float is equivalent to double on many other platforms, so if you are storing them in a database for instance, make sure the database field is of type double
Comment: >Anywhere you are using floats you should be able to use str or Decimal to ensure you are not losing precision.
The problem is this:
i am writing a platform which will support external modules written by other programmers. I use PyQt and dynamically generated forms. I developed my own widget for editing decimals, and here appears the question about the value it keeps. I want to use decimals, but for user (programmer) modules it's not intuitive to write every time:
    myvar = decimalEditWidget.value + decimal.Decimal ('2.2')
So i wanted to make this conversion transparent
Answer: Use cdecimal or decimal.py from 2.7 or 3.2. All of those have the from_float
class method:

class MyDecimal(Decimal):
    def convert(self, v):
        if isinstance(v, float):
            return Decimal.from_float(v)
        else:
            return Decimal(v)
    def __mul__(self, other):
        other = self.convert(other)
        return self.multiply(other)

Subclassing Decimal in Python


Snakemake unknown number of output files / defining wildcards based on intermediate files

Question: to speed up a my workflow I would like to do something similar to snakemake-unknown-output-input-files-after-splitting-by-chromosome
SAMPLE = "sample_a"

rule all:
    expand("results/{sample}-final-combined.bam", sample=SAMPLE)

rule exclude_blacklist:
    input:
        region_file = "data/{sample}.bed",
        blacklist = "data/blacklists/universal_blacklist.bed"
    output:
        "results/{sample}_blacklist-excluded.bed"
    shell:
        """
        bedtools intersect -v -a {input.region_file} -b {input.blacklist} > {output}
        """

rule target_regions_by_chrom:
    input:
        region_file ="results/{sample}_blacklist-excluded.bed",
    output:
        temp("results/{sample}_{chrom}.bed")
    script:
        "scripts/split_region_by_chrom.py"

rule simulate_reads:
    input:
        "results/{sample}_{chrom}.bed"
    output:
        "results/{sample}_{chrom}.bam"
    script:
        "scripts/simulate_reads.py"

rule combine_regions_again:
    input:
        files = expand("results/{sample}_{chrom}.bam", sample=SAMPLE, chrom=get_chroms())
    output:
        "results/{sample}-final-combined.bam"
    script:
        "scripts/combine_bams.py"

The workflow should take a .bed file with unfiltered regions, exclude problematic regions from a blacklist, split the filtered .bed file by chromosome and then simulate reads for these regions (for simplicity I spare you the details), generating .bam files. Ultimately these .bam files should be combined again to an output file.
The main problem is how to solve the unknown number of chromosomes beforehand. If I take the input .bed file, I get some errors, because some files will be empty. I thought about using an input function (here get_chroms()) to recover the chromosome from the output .bed file ("results/{sample}_blacklist-excluded.bed") after excluding the blacklisted regions, but this leads to errors during the creation of the DAG because the file is not existent.
Does anybody have any suggestions how to solve these problems:

split a .bed file by chromosome, while not knowing the present chromosomes
defining a wildcard based on an intermediate file in the workflow

Any help would be greatly appreciated!
Answer: The Dynamic Files feature of Snakemake is probably what you need:

Dynamic files can be used whenever one has a rule for which the number
of output files is unknown before the rule was executed.

You should wrap the "results/{sample}_{chrom}.bed" with dynamic() modifier in both input and output counterparts:
rule target_regions_by_chrom:
    output:
        dynamic("results/{sample}_{chrom}.bed")

rule simulate_reads:
    input:
        dynamic("results/{sample}_{chrom}.bed")

Comment: After solving some follow-up wildcard error, this was the easiest solution.
Answer: It used to be that you can use `dynamic decorator for input/output. But this has now been depracated. Instead you should do that with Data-dependent conditional execution feature of Snakemake which uses checkpoints to see how many jobs you need to execute after you split the files.


Prove that f is not continuous anywhere in $[0, 1]$, if $f(x) = 0$ when x irrational, and $f(x) = 1$ when $x$ rational

Question:
I know because rational and irrational numbers are dense in R, then for any $x$, you can always find both a sequence of Rationals and a sequence of Irrationals that converge to $x$
Qustions:
1)Why do we choose sequence of rational numbers for irrational x(sequence converges to irrational x)
2)Why in the first case $1 = \lim f(x_n)$ and in the seond $0 = \lim f(y_n)$
Answer: 1) We choose a sequence of rational numbers because the function is $1$ at all rational numbers, thus $\lim_{n\to\infty} f(x_n)=1$ (more on that below).
It would also be possible to prove discontinuity using the $\epsilon-\delta$ definition, but this particular textbook chose the convergent sequences way of doing it.
2) In the first case, for every value of $n$, the value $f(x_n)$ is equal to $1$, which means that $$\lim_{n\to\infty} f(x_n)=\lim_{n\to\infty} 1 = 1.$$ A similar case can be made for $0=\lim f(y_n)$, as $f(y_n)=0$ for all values of $n$.
Comment: @DanielYefimov I suggest you first try to do the proof yourself. After all, that's the only way we learn anything in math: my trying it on our own. (if you fail, you can still post a question and someone, maybe even me, will answer it. But try it yourself, first!)
Comment: Great, everything is clear right now! Thank you!

P.S if you have posibility can you please show the proof using $\epsilon - \delta$ definition?
Answer: 1) because it helps to prove the desired discontinuity
2) because both sequences are constant ones !


C DLL does NOT Work in C# but Does work in C++

Question: I don`t understand this code below, that it is working with my c++ but it just does not want to work with c#.
Can you please help me to understand what is wrong here and i think i have to say that i am absolutely new to C#.
    My_Lib.h
    extern "C"  __declspec(dllexport) void __cdecl get(char** buffer);

    My_lib.c
    void get(char** buffer)
    {
    *buffer = (char*)calloc(6, sizeof(char));
    assert(*buffer);

    buffer[5] = '\0';

    *buffer = "Hello";
    }

in my C#----->
public static class NativeMethods
    {
        [DllImport("My_C_Lib.dll", CallingConvention = CallingConvention.Cdecl)]

        unsafe public static extern void get(char** buffer);
    }
 //////////////////// Main()///////
        unsafe
            {
                char* my_buf;

                NativeMethods.get(&my_buf);

                string s = new string(my_buf);

                Console.WriteLine(s);
            }

NOTE: Actually my DLL does Work when i call this c function from c++ but as i said above NOT in C#, there is no Errors but string s variable in C# prints some undefined sibols, but DLL "works"
thanks in advance!!!
Comment: Marshaling calls to unmanaged code that uses raw pointers and allocators, and uses string encodings that are not natively supported in C#, is **really hard to get right**. It is not a task for beginners.  Hire an expert, or start with an easier problem. This is not a site for tutoring people on complex subjects; do some reading up on interop and marshaling.
Comment: `char` in C# is not the same thing as `char` in C. Don't use raw pointers in C#, use [PInvoke](https://learn.microsoft.com/en-us/cpp/dotnet/how-to-call-native-dlls-from-managed-code-using-pinvoke).
Comment: thank you, can you please show me how to use PInvoke in this case
Comment: Also note that you have a memory leak here.
Comment: the bible on pinvoke is adam nathans book https://www.amazon.com/NET-COM-Complete-Interoperability-Guide/dp/067232170X
Answer: The code is nearly correct, but...

C DLL does NOT Work in C# but Does work in C++

In C and C++ char is a 8-bit data type. In C# char is a 16-bit data type.
This means that C# expects that the pointer returned by the get() function is expected to be a "wide string", while in C++ expects an "ANSI string".
I simply changed one single line in your program:
*buffer = "H\0e\0l\0l\0o\0\0\0";

... and it works!
You may of course also use the "wide string" functions of the modern C compilers:
void get(wchar_t** buffer)
{
    *buffer = L"Hello";
}

By the way
There is another error in your program:
*buffer = (char*)calloc(6, sizeof(char));
...
*buffer = "Hello";

This makes no sense:
The second line (*buffer = "Hello";) will not copy the string to the memory allocated by calloc, but it will write the address of the string "Hello" to the variable buffer and the value (address) returned by calloc is overwritten (and lost).
Answer: Your best bet is to change the PInvoke signature of your C function to taking a ref IntPtr:
[DllImport("My_C_Lib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void get(ref IntPtr buffer);

To call this, you'll need to instantiate an IntPtr and pass it by reference to the C function (this is analagous to declaring a char * in C and passing it by address):
IntPtr ptr;
get(ref ptr);
// ptr is now an unmanaged pointer to the allocated string

Now, you need to convert the pointed-to string to a managed string. To do this you must make a copy of the string.
string str = Marshal.PtrToStringAnsi(ptr);

Be sure you understand the distinctions between ANSI and Unicode strings and make sure you call the appropriate PtrToString...() variant.
Note that the .NET runtime will not manage the allocated ptr for you since it was allocated by unmanaged code. You must free it yourself using whatever the appropriate mechanism is for your DLL (ideally, the DLL should provide a corresponding free function since it is the one who allocated the memory in the first place).
For robustness, add appropriate error / null pointer checking. Make sure get() succeeded and that ptr is not IntPtr.Zero.
To avoid leaks, if there is any possibility of any code throwing an exception between the time get() returns and the time you free the pointer, the try/finally construct is your friend.

(Aside: Note that get is a Contextual Keyword in C# and thus while you can use it as an identifier, you may prefer not to in order to avoid confusion.)