Replace specific character on list in Python with on loop

Question: I'm a newbie in coding and I tried to do my own hangman game when I encounter a big bug that I cannot solve.
I gotta be honest, I'm not too familiar when it comes to modify list so that might be why I cannot solve this. The following piece of code is a function that takes some parameters and tries to return the modified blankSpaces as a not-so-blank-spaces, so for example if the user tries to guess with ther word "o", but the word is not on the list of the original word, lets say for example "love", the blankSpaces for love would be something like "_ _ _ _", so I'm trying to do that if the letter "o" is inside the original word I would take the position of the original word and replace it on the blankSpaces to return something like "o_" because its on the original string:
def revealWord(blankSpaces, letterToReveal, wordPosition, actualString):
countChar = len(actualString)
dividedString = list(actualString)
chara = letterToReveal
joinWord = []

y = 0
while y < countChar:
    y += 1
    if letterToReveal == dividedString[y - 1]:
        print("matched")
        joinWord = dividedString[y - 1]

joinWord = " ".join(blankSpaces)
return joinWord

so, for me when I try to guess the word I get something like this
your word kinda looks like this:
this is the output:
_ _ _ _
try to guess typing a single letter, you have 6 attempts remaining
What is your letter?
 -o
You guessed right! Your letter -o- is #1 time/s in the original word
matched
your word now looks like this: --- _ _ _ _ ---
try to guess typing a single letter, you have 6 attempts remaining
What is your letter?
 -

See? It doesn't modify anything...
Attaching the entire code for better context
import random

wordsdb = ["water", "airplane", "love"]

def keep_playing(currentLives, wordSlctd, blankSpaces):
    print("try to guess typing a single letter, you have {} attempts remaining" .format(currentLives))
    charToGuess = input("What is your letter? \n -")
    check_if_char(blankSpaces, wordSlctd, charToGuess, currentLives)

def hangItUp(hp, wordSlctd, blankSpaces):
    hp -= 1
    print("Your character is not on the string. Hanging him up!")
    print("{} attempts remaining " .format(hp))
    if hp <= 0:
        userResponse = input("Game Over! Waiting for your response...")
        if userResponse == "try again":
            print("restarting the game.")
        else:
            print("Bye bye...")
    else:
        keep_playing(hp, wordSlctd, blankSpaces)
    return hp

def revealWord(blankSpaces, letterToReveal, wordPosition, actualString):
    countChar = len(actualString)
    dividedString = list(actualString)
    chara = letterToReveal
    joinWord = []

    y = 0
    while y < countChar:
        y += 1
        if letterToReveal == dividedString[y - 1]:
            print("matched")
            joinWord = dividedString[y - 1]

    joinWord = " ".join(blankSpaces)
    return joinWord

def check_if_char(blankSpaces, ogWord, selectedChar, currentLives):
    countChar = len(ogWord)
    wordSplitted = list(ogWord)
    wordCount = wordSplitted.count(selectedChar)
    matchedIndexes = []
    revealedWord = ogWord

    if selectedChar in wordSplitted:
        x = 0
        while x < countChar:
            x += 1
            if selectedChar == wordSplitted[x - 1]:
                matchedIndexes.append(x)

        print("You guessed right! Your letter -{}- is #{} time/s in the original word" .format(selectedChar, wordCount))
        revealedWord = revealWord(blankSpaces, selectedChar, matchedIndexes, ogWord)
        print("your word now looks like this: --- {} ---" .format(revealedWord))
        keep_playing(currentLives, revealedWord, blankSpaces)
    else:
        print("your actual word: --- {} ---" .format(revealedWord))
        print("your current word: --- {} ---" .format(blankSpaces))
        currentLives = hangItUp(currentLives, revealedWord, blankSpaces)
        keep_playing(currentLives, revealedWord)

def hangman_game():
    lives = 6
    theSelectedWord = random.choice(wordsdb)
    countTheBlankSpaces = len(theSelectedWord)
    theBlankSpaces = []

    for i in range(countTheBlankSpaces):
        theBlankSpaces.append("_")

    print("your word kinda looks like this: {} " .format(" ".join(theBlankSpaces)))
    keep_playing(lives, theSelectedWord, theBlankSpaces)

hangman_game()

Answer: You can simplify your logic by keeping list of guessed letters. Thus, you don't need blankSpaces, letterToReveal, wordPosition and actualString variables. You can also use guessed letters list for checking victory condition.
import random

WORDS = ["water", "airplane", "love"]

def revealed_word(word, guessed_letters):
    result = []
    for letter in word:
        if letter in guessed_letters:
            result.append(letter)
        else:
            result.append('-')
    return result

def hangman_game(lives, word):
    guessed_letters = []

    while lives and len(guessed_letters) < len(set(word)):
        print(f"your word kinda looks like this: {revealed_word(word, guessed_letters)}")
        print(f"try to guess typing a single letter, you have {lives} attempts remaining")
        guess = input("What is your letter? ")
        if guess in guessed_letters:
            print("you already guessed this letter, try another one")
        elif len(guess) == 1:
            if guess in word:
                print(f"You guessed right! Your letter -{guess}- is #{word.count(guess)} time/s in the original word")
                guessed_letters.append(guess)
            else:
                lives -= 1
                print("Your character is not on the string. Hanging him up!")
                print("{} attempts remaining ".format(lives))
        else:
            print("please enter one letter only")

    action = input("Game Over! Waiting for your response...")
    if action == "try again":
        print("restarting the game.")
        hangman_game(lives=6, word=random.choice(WORDS))
    else:
        print("Bye bye...")

hangman_game(lives=6, word=random.choice(WORDS))

Sample output:
your word kinda looks like this: ['-', '-', '-', '-', '-', '-', '-', '-']
try to guess typing a single letter, you have 6 attempts remaining
What is your letter? a
You guessed right! Your letter -a- is #2 time/s in the original word
your word kinda looks like this: ['a', '-', '-', '-', '-', 'a', '-', '-']

Answer: I believe the issue is that you are simply returning a series of blank spaces every time because of this:
joinWord = " ".join(blankSpaces)
return joinWord

You are trying to format it later in the 'check_if_char' function:
revealedWord = revealWord(blankSpaces, selectedChar, matchedIndexes, ogWord)
print("your word now looks like this: --- {} ---".format(revealedWord))

This makes it so the output will always have the blank spaces in that print statement.
Try updating your loop like this.
    while y < countChar:
        y += 1
        if letterToReveal == dividedString[y - 1]:
            print("matched")
            blankSpaces[y - 1] = letterToReveal
    joinWord = " ".join(blankSpaces)
    return joinWord

Now you are modifying the index of the letter in the blankSpaces list so it actually contains the letter you want to reveal. Now when you .join() the list looks how you want!


ValueError: Error when checking target: expected dropout_82 to have 3 dimensions, but got array with shape (7, 7500)

Question: Hi I must implement a cnn, I'm new with Keras and Tensorflow so I'm apologizing if I'm making a mistake.
This is what I do:
the dataset is an numpy array (23, 4800000), #number of audio tracks x #number of samples.
So I splitted the dataset in train (10, 4800000), validation (7, 4800000) and test (6, 4800000)
The convolution process along the columns, so I must reshape the input in:
X = np.expand_dims(train, axis=2)
Y = np.expand_dims(valid, axis=2)

The code for first part cnn is:
cnn = Sequential()
cnn.add(Conv1D(40, 80, input_shape=(4800000, 10)))
cnn.add(MaxPooling1D(pool_size=2))
cnn.add(Conv1D(40, 8000))
cnn.add(MaxPooling1D(pool_size=20))
cnn.add(Flatten())

cnn.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv1d_1 (Conv1D)            (None, 4799921, 40)       32040
_________________________________________________________________
max_pooling1d_1 (MaxPooling1 (None, 2399960, 40)       0
_________________________________________________________________
conv1d_2 (Conv1D)            (None, 2391961, 40)       12800040
_________________________________________________________________
max_pooling1d_2 (MaxPooling1 (None, 119598, 40)        0
_________________________________________________________________
flatten_1 (Flatten)          (None, 4783920)           0
=================================================================
Total params: 12,832,080
Trainable params: 12,832,080
Non-trainable params: 0
_______________________________

cnn.compile(loss='mean_squared_error', optimizer='adam')
cnn.fit(X,Y)

And the error is:
ValueError: Error when checking input: expected conv1d_3_input to have shape (None, 4800000, 10) but got array with shape (4800000, 10, 1)

I don't really understand what it means, please someone could help me?
So during these days I tried to simplify my work.
X_train, X_valid = (7,7500,1), 7 number of tracks, 7500 samples and 1 channel
y_train, y_valid = (7,7500), for each one of 7 tracks correspond a value of probability in any sample.
model = Sequential()

model.add(Conv1D(40, 80, activation='relu', input_shape=(7500,1)))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.5))
model.add(Conv1D(40, 800 ,activation='relu'))
model.add(MaxPooling1D(pool_size=20))
model.add(Dropout(0.5))
model.compile(loss='mean_squared_error',
              optimizer='sgd',
              metrics=['accuracy'])
model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv1d_112 (Conv1D)          (None, 7421, 40)          3240
_________________________________________________________________
max_pooling1d_93 (MaxPooling (None, 3710, 40)          0
_________________________________________________________________
dense_6 (Dense)              (None, 3710, 40)          1640
_________________________________________________________________
dropout_81 (Dropout)         (None, 3710, 40)          0
_________________________________________________________________
conv1d_113 (Conv1D)          (None, 2911, 40)          1280040
_________________________________________________________________
max_pooling1d_94 (MaxPooling (None, 145, 40)           0
_________________________________________________________________
dropout_82 (Dropout)         (None, 145, 40)           0
=================================================================
Total params: 1,284,920
Trainable params: 1,284,920
Non-trainable params: 0

model.fit(X_train, y_train, batch_size=50, epochs=1, validation_data=(X_valid, y_valid))

ValueError: Error when checking target: expected dropout_82 to have 3 dimensions, but got array with shape (7, 7500)

I think It concern at y_train and y_valid, but if I expand the dimension the error change with this
ValueError: Error when checking target: expected dropout_86 to have shape (None, 145, 40) but got array with shape (7, 7500, 1)

Comment: The `input_shape` doesn't include the batch size: https://stackoverflow.com/a/48141688/712995
Comment: if you have an input shape of `(4800000, 10)` you will build a network which classifies/regresses 10 audio samples at a time -- is this what you want ?
Comment: Yes, I need to do convolution and pooling along the sample-series (4800000) for each track (10).
Comment: No sorry, I need to do convolution and pooling along the sample-series (4800000) for each track (10). I'm getting confused sorry
Answer: Just as the error message puts, the shapes of your input data do not match the expected, because you have expanded the wrong dimension.
In this case, the shape of your original training data is (23, 4800000), and becomes (23, 4800000, 1) after expanding dimensions with
X = np.expand_dims(train, axis=2)

but the expected shape of input data is (None, 4800000, 10), None here means vairable-length.
What you should do is just reshaping data with
X = np.expand_dims(train, axis=0)

Comment: Sorry I missed one operation, I've done the transpose of train and then I expanded the dimension of the train-set.

    train.shape = 10,4800000)

    train = train.T

    train.shape(4800000,10)

    X = np.expand_dims(train, axis=2)

    X.shape = (4800000, 10, 1)

So you mean extending the dimension to have (1, 4800000, 10)?


Does anyone know the name of the book concerning math?

Question: I want to find a book, and I have the picture of the table of contents.Does anyone know the name of the book? Thank you very much.
Comment: It seems to be an anthology of papers. That may make identifying the book harder than reading the papers directly. Most if not all will be available via Google Scholar, especially if you use Scihub to bypass paywalls.
Comment: @J.G. I tried to search some papers on Google Scholar, but the advantage of the book is that it translates the papers into English, but on Google Scholar the papers are written in Russian.
Comment: I concur with @Fred's inference of which book it was. I just searched two chapter titles, in quotation marks to form a two-quotation search string, on Google Books; it was the top result. I hope that strategy helps you find other books in the future.
Answer: https://ieeexplore.ieee.org/document/5311923
Control Theory: Twenty-Five Seminal Papers (1932-1981)
Author :Tamer Basar
Publisher: Wiley-IEEE Press
Pages: 532
Copyright Year: 2001
Online ISBN: 9780470544334
DOI: 10.1109/9780470544334.ch4
Comment: Thank you very much! That's exactly what I want.


Does not work ng-select

Question: Why the data does not appear in SELECT? When I click on the opening list there is empty, although it must store information. Where could I make a mistake?
Component.ts:
...
spr_wellpads: Array<ComboboxItem>;
loading: boolean = false;
...
constructor(
private servSprWellpad: SprWellpadService
)
...

    ngOnInit() {
...

        this.loading = true;
        this.servSprWellpad.getSprWellpads().subscribe(
            result => {
                this.loading = false;
                this.spr_wellpads = result.spr_wellpads.map(r => ({
                    value: r.spr_oilfields_id.toString()
                }));
            },
            error => {
                this.toastManager.error(getErrorTextFromJSON(error.json()), 'Error')
            });
    }
...

html:
<ng-select [(ngModel)]="sprWellpad.spr_oilfields_id" [options]="spr_wellpads"
                        [notFoundMsg]="'Not is not found'"
                        [allowClear]="true"></ng-select>

Answer: As ng-select options accepts [{ id : your_id , name : your_value }] pairs , and you were passing the [{ value : your_value }]
You need to change this :
this.spr_wellpads = result.spr_wellpads.map(r => ({
    value: r.spr_oilfields_id.toString()
}));

To :
this.spr_wellpads = result.spr_wellpads.map(r => ({
    id : r.spr_oilfields_id,
    name: r.spr_oilfields_id.toString()
}));

WORKING EXAMPLE

Does not work ng-select


Is there a way to make sure that a certain character is in a string?

Question: I have a BYOL (Build your own Lab) for my Computer Science class. This lab is due in 3 days, and I need a bit of help on one of the parts. I would like to know how to determine if the user has input a special character (@, #, !, *, $, c, %, etc) and I want to know how to close the string if that character is not included in the string. I am using an if...then loop to close strings when the user's input is not in the correct format. (Ex: I asked them to input their SSN, so it must be in the format XXX-XX-XXXX, otherwise it will close the string.) I need to ask them for their E-Mail address and want the answer to include "@". All help is appreciated.
Here is my code, because I do not know how to post it separately.
public static void main (String[]args)
   {
   String answer;
   do {
      Scanner word=new Scanner(System.in);
      Scanner input=new Scanner(System.in);
      System.out.print("Oh No! It appears that Dwayne \"The Rock\" Johnson has stolen your Credit Card and SSN Info!");
      System.out.print("\nPlease input some information for us to secure your personal Info.");
      System.out.print("\n\nPlease enter your Social Security Number: (XXX-XX-XXXX) ");
      System.out.print("\nPlease be aware that you must input the information in the correct format (Without the parentheses at the begining and end) ");
      String ssn=input.nextLine();
      if (ssn.length()!=11)
         System.out.println("\nYou have entered the incorrect format! (XXX-XX-XXXX)" );
      if (ssn.length()!=11)
         System.exit(0);

      System.out.print("\nPlease enter your Credit Card Number:(XXXX-XXXX-XXXX-XXXX) ");
      String ccn=input.nextLine();
      if (ccn.length()!=19)
         System.out.println("\nYou have entered the incorrect format! (XXXX-XXXX-XXXX-XXXX)");
      if (ccn.length()!=19)
         System.exit(0);

      System.out.print("\nPlease enter your Credit Card Expiration Date: (MM/YY) ");
      String exp=word.nextLine();

      System.out.print("\nPlease enter your CVV (Card Verification Value): (XXX) ");
      String back=word.nextLine();
      if (back.length()!=3)
         System.out.println("\nYou have entered the incorrect format! (XXX)");
      if (back.length()!=3)
         System.exit(0);

      System.out.print("\nPlease enter your E-Mail Address: ");
      String mail=word.nextLine();

      System.out.print("\nPlease enter your American Phone Number: (+1(XXX) XXX-XXXX) ");
      String phone=word.nextLine();
      if (phone.length()!=16)
         System.out.println("\nYou have entered the incorrect format! (+1(XXX) XXX-XXXX)");
      if (phone.length()!=16)
         System.exit(0);

      System.out.print("\nPlease enter your home address: ");
      String home=word.nextLine();

      System.out.print("\nPlease enter your First Name: ");
      String name=word.nextLine();

      System.out.print("\nPlease enter your Middle Initial (X): ");
      String mid=word.nextLine();
      if (mid.length()!=1)
         System.out.println("\nYou have entered the incorrect format! (X)");
      if (mid.length()!=1)
         System.exit(0);

      System.out.print("\nPlease enter your Last Name: ");
      String last=word.nextLine();

      System.out.print("\nPlease enter your Date of Birth: (MM/DD/YYYY) ");
      String dob=word.nextLine();
      if (dob.length()!=10)
         System.out.println("\nYou have entered the incorrect format! (MM/DD/YYYY)");
      if (dob.length()!=10)
         System.exit(0);

      System.out.println("\n\n\t\t\t\tThank you, you have secured your information");
      System.out.println("\nIf you have any comments or concerns, please contact us at these locations:");
      System.out.println("\n\n\t+1(555) 555-5555");
      System.out.println("\n\firstname.lastname@example.com");
      System.out.println("\n\n\t\t\t\t\t\tThank you, and have a wonderful day!");
      System.out.println("\n\t\t\t\t\t\t\tThe Scammer Preventer™ Team");
      System.out.println("\n\n\n\t\t\t\t\tDo you have more information to input? Yes or No: ");
      answer=input.next();
      }
      while (answer.equalsIgnoreCase("\n\nYes"));

   }
}

Comment: Please only post the part of your code relevant to the question.  What does it mean to "close the string"?
Comment: sorry, (I'm new to Java) I just need to understand how to close the entire program if the email address does not include the "@"
Comment: Also kindly don't post sentences like "This lab is due in 3 days" this is not related to your question, posting like this will not give your question high priority.
Comment: okay, thank you for the advice
Answer: if (!mail.contains("@")) {
  System.exit(0);
}

This answer may also help: https://stackoverflow.com/a/1795436/1317559
Comment: Thank You. This helped me a lot.
Comment: No problem, added a link also.


How i put search at modal Pop Up?

Question: This is what it looks like when I call the pop up browse form form modal
this is what it looks like when I enter input search result
please help to solve this problem. Thank you

Controller

on this form i use partialview to call modal form
            ViewData["CurrentFilter"] = SearchString;
            var Items = new List<ExpandoObject>();
            this.iFA = FA;
            this.nSP = SP;
            this.iFA2 = FA2;
            this.isItems = isItem;
            this.nSearch2 = SearchString;
            dtBrowse = new DataTable();
            if (iFA2==0)
            {
                dtBrowse = RefreshData(true);
            }
            else
            {
                dtBrowse = RefreshData(false, iFA2, TxtCategory,SearchString);
            }
            int i = 0;

            nSP = SP;
            ViewBag.iFA2 = FA2;
            ViewBag.Category = AddItemToComboBox(dtBrowse);
            isItems = isItem;
            nSearch2 = SearchString;
            return PartialView("_BrowsePartial",dtBrowse);

View

@using System.Reflection
@using System.Data
@model DataTable

<form asp-action="BrowseTrans" method="get">

Browse

                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

                            <input type="text" value="@ViewData["CurrentFilter"]" class="form-control" name="SearchString" placeholder="Search…">

                                <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none" /><circle cx="10" cy="10" r="7" /><line x1="21" y1="21" x2="15" y2="15" /></svg>

                            By Category

                            <select id="ddlCurr" asp-items="@(new SelectList(ViewBag.Category, "Category", "Category"))" name="TxtCategory" class="form-control">
                            </select>

                                        @for (int c = 0; c < Model.Columns.Count; c++)
                                        {
                                            @Model.Columns[c].Caption
                                        }

                                    @foreach (DataRow dr1 in Model.Rows)
                                    {

                                            @for (int c = 0; c < Model.Columns.Count; c++)
                                            {
                                                if (c == 0)
                                                {

@dr1[c].ToString()

                                                }
                                                else
                                                {

@dr1[c].ToString()

                                                }

                                            }

                                    }

                    <button type="button" class="btn me-auto" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Add Team</button>

</form>

Javascript

this is a javascript function script when calling a modal form
$(function () {
    var PlaceHolderElement = $('#PlaceHolderHere');
    $('button[data-toogle="ajax-modal"]').click(function (event) {
        var url = $(this).data('url');
        $.get(url).done(function (data) {
            PlaceHolderElement.html(data);
            PlaceHolderElement.find('.modal').modal('show');
        })
    })

    PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {

        var form = $(this).parents('.modal').find('form');
        var actionUrl = form.attr('action');
        var sendData = form.serialize();
        $.post(actionUrl, sendData).done(function (data) {
            PlaceHolderElement.find('.modal').modal('hide');
            location.reload();
        })
    })
})

Answer: You can try to remove the <form asp-action="BrowseTrans" method="get">,and add id to search input <input type="text"  class="form-control" id="SearchString" name="SearchString" placeholder="Search…">.Then when enter key press,pass search data and get data with ajax.Then replace data in <tbody
 with the data in ajax success.
js:
var element = document.getElementById('SearchString');
        element.addEventListener("keyup", function (event) {
            if (event.keyCode === 13) {
                search()
            }
        });
        function search() {
             $.ajax({
                type: "GET",
                 url: 'BrowseTrans?SearchString=' + $("#SearchString").val() + "&&TxtCategory=" + $("#ddlCurr").val(),
                 success: function (data) {
                     //get data from action here
                     //replace html in
 with data
                 },
                 error: function (result) {
                     alert("error occured");
                 }
             });
        }

How i put search at modal Pop Up?


Closing a card on Gmail Add-on

Question: I would like to programmatically close the add-on after clicking a button.
Is is possible to close the addon programmatically?
Thank you
Comment: Did you do any research or testing? What happens if you [pop every Card?](https://developers.google.com/apps-script/reference/card-service/navigation)
Answer: As of now, there is no provision for closing the GMail add on programatically. User has to click on the add on icon on the side bar to close it.

Closing a card on Gmail Add-on


Is it possible to use /summon a tipped arrow in bedrock?

Question: I am trying to summon an arrow of instant damage 2 in Minecraft bedrock edition, and I cannot figure a way to do it. Is it possible to do this in bedrock? If so, how?
Comment: Duplicate of [How do you add NBT tags to commands in Minecraft Pocket/Bedrock Edition?](https://gaming.stackexchange.com/questions/334102/how-do-you-add-nbt-tags-to-commands-in-minecraft-pocket-bedrock-edition)
Answer: Unfortunately I don't think that you can summon arrows with potion effects in MCBE. In Java, you would use NBT but this doesn't exist in Bedrock Edition.


Any experience installing wall-hung toilets?

Question: My architect is recommending the Catalano Zero 55 Toilet:

I'm more a fan of Toto toilets. They have a wall-hung model called the Aquia, which is somewhat less graceful looking:

Does anybody have any experience with how these actually function?
Comment: Be sure that installation is done by a qualified person - if such unit is not attached to a strong enough construction *or* the attachment itself is not strong enough you face serious risks of having it fallen off and broken and its pieces causing severe injuries (pottery is extremely hard and will have extremely sharp edges). That's not what you care that much in case of floor-mounted toilet, but it's extremely important in case of wall-mounted one.
Comment: I'm pretty sure that these come with a mounting framework that's concealed in the wall and floor; they're not just cantilevered off the drywall.
Comment: Okay, but that framework must be attached properly as well and the person doing that must be qualified enough to not fasten it with tiny screws to some weak drywall framework and declare it done - any negligence can have dire consequences here.
Comment: I mean... if you look at the [spec sheet (PDF)](http://www.ceramicacatalano.it/schede/pdf/zero55sospesi.pdf) there's an L-shaped framework it connects to... it's not depending on support from the wall at all. Although of course you are right that a bad installer WILL find a way to install it badly.
Comment: That L-shaped thing extends forward to suspiciously big distance (big waste of metal). I'd rather believe it's some imaginary set of lines to illustrate how in general the toilet should be positioned rather than an actual construction.
Answer: The main difference between this bowl and the "standard" one is that the waste goes out the back and then down rather than straight down:

(the red arrow I've added to this cross section).
In the UK all toilets (wall or floor mounted) tend to have this arrangement.
As far as everyday operation is concerned they're the same as the "standard" as it's the action of the water rather than gravity on the waste that flushes it away.
Comment: @Joel Spolsky: I'm in very eastern Europe and I've never seen a live "standard" (with "flush down" inner pipe) toilet in my whole life - only "flush back" models are used here and we have state standards and codes that regulate how "flush back" toilets should be manufactured and they flush just fine until you throw a whole ununwinded roll of toilet paper or a whole newspaper into it which I guess would clog any kind of toilet.
Comment: Does that mean they're not as good at flushing as a standard toilet?
Answer: We replaced all three toilets in our house about four years ago - two with Duravit/Geberit wall-mounted toilets, and one with an American Standard low-flow.  I would whole-heartedly recommend the wall-mounted toilets, but there are a few considerations:
Cons:

The tank is inside the wall.  (Duh.)  In the case of Geberit tanks, this means that the wall must be built of 2x6 studs instead of 2x4; that required a bit of a last-minute remodel for us, so it's a good thing to know going in.
Forget about 10,000 Flushes or anything similar.  It's a major pain to remove/replace the access panel to put any kind of water treatment in there, and it's a lot easier to block the flush mechanism by careless placement than in a standard tank.  The first time you find yourself twisted into a pretzel, with your arm stuck in a wall up to the elbow, fishing around in hyper-chlorinated water trying to find the bleach tab you dropped in there so blithely... you'll question your life choices.

Pros:

Since the tank is tall and thin, you tend to get a noticeable gravity assist on the flush - much more oomph per gallon, so to speak.
It's much, much easier to clean under and around.
It looks awesome.
Unlike a standard toilet, you get to choose (albeit only once, at installation) your preferred seat height.  Our Geberits are the most comfortable toilets I've ever sat on, simply because I chose a seat height that fit my own legs.


Returning value from one column or, if not found, search it in another

Question: I have a column with phone numbers and another one in which I use LOOKUPV to look up the same phone numbers in another file (I use this file to look up some missing numbers, but I don`t have all of them). In a third column, I want to use a function to treat these phone numbers (they need to be formatted in a certain way), but my problem is that in some cases I have lines in which the phone number in column A is present and the number in column B is not, or vice versa. I want to use a function which looks up a number in both columns and returns only one phone number. How can this be done? Example:

Phones 1
Phones 2
Answer

12345678

12345678

55577788
55577788

88899900
88899900
88899900

Thank you!
Answer: You can use the if function to check which column is not empty and return it's value.
=if(A2="",B2,A2)

Or
=if(LEN(A2)=0,B2,A2)

Answer: Assume the data starts in cell A2, put this in cell C2:
=if(and(A2="",B2=""),"error",if(A2="",B2,A2))

If you have the ID in col A and the phone numbers in B and C, then something like:
=iferror(vlookup(D2,A2:C10,2,0),vlookup(D2,A2:C10,3,0)

This assumes that both B2 and C2 will not be empty.


Redshift large 'in' clause best practices

Question: We have a query in which a list of parameter values is provided in "IN" clause of the query. Some time back this query failed to execute as the size of data in "IN" clause got quite large and hence the resulting query exceeded the 16 MB limit of the query in REDSHIFT. As a result of which we then tried processing the data in batches so as to limit the data and not breach the 16 MB limit.
My question is what are the factors/pitfalls to keep in mind while supplying such large data for the "IN" clause of a query or is there any alternative way in which I can deal with such large data for the "IN" clause?
Comment: Is it possible to break your query into smaller parts?
Comment: Can you please clarify more on the part of breaking the query?
Comment: are you providing the in clause literally - i.e. generating the very large sql select statement and then submitting it? and - does this need to run as a single select statement or can you run multiple sql steps?
Comment: hi - did my answer work for you if so mark it as such - if not, please let me know why not.
Answer: If you have control over how you are generating your code, you could split it up as follows
first code to be submitted, drop and recreate filter table:
drop table if exists myfilter;
create table myfilter (filter_text varchar(max));

Second step is to populate the filter table in parts of a suitable size, e.g. 1000 values at a time
insert into myfilter
values({{myvalue1}},{{myvalue2}},{{myvalue3}} etc etc up to 1000 values );

repeat the above step multiple times until you have all of your values inserted
Then, use that filter table as follows
select * from master_table
where some_value in (select filter_text from myfilter);
drop table myfilter;

Comment: Hi Jon, isn't redshift quite slow in terms of insertions?
Won't this approach slow down the whole process?
Comment: Yes it will be slower, however I cannot think of a faster alternative for very large in clauses.
Answer: Large IN is not the best practice itself, it's better to use joins for large lists:

construct a virtual table a subquery
join your target table to the virtual table

like this
with
your_list as (
    select 'first_value' as search_value
    union select 'second_value'
    ...
)
select ...
from target_table t1
join your_list t2
on t1.col=t2.search_value

Comment: I am not sure whether I can go by this approach as the data we pass on in "IN" clause is retrieved after fetching it from some other table and performing a couple of operations/validation on them. This processing part is written in Java currently.
Reason, I am reluctant to move this processing part to sql is that it will increase the query complexity immensely which will impact the query's understandability.
Comment: @GaganMaheshwari if I understand this correctly, there's no problem and you can generate this subquery in Java - instead of just sending the list send the subquery
Comment: Can you elaborate more on generating the subquery in Java?
Comment: @GaganMaheshwari If you say you have the processing part in Java I assumed you mean you have a Java app that is talking to Redshift back and forth, and you're composing the "IN" query in Java and send it to Redshift for execution. Then you're free to use this list to construct the query the way above, not just "IN" with the list.


Bulma tiles not defaulting to horizontal

Question: According to the Bulma docs on tiles (https://bulma.io/documentation/layout/tiles/) I would expect the following to produce two horizontal rows of two images each. Instead, it produces a line of four vertical images, with the first and second and third and fourth somewhat closer to each other.

I was able to get the behavior I wanted by forcing display: flex on the is-parent div (which is the class I would expect, actually, rather than display: block, which is what Bulma sets), but my understanding is that Bulma tiles should lay out horizontally by default. Am I wrong, or doing something wrong?
Many thanks.
Answer: The correct way of doing this is to define two divs with class is-ancestor:

Comment: Thanks for the answer! I think you're right that that's how it's intended to be set up; but it still produces two groups of vertically-aligned images for me. At least the workaround works well enough for now!
Comment: That is exactly what this does. Wasn't this what you asked for?
Comment: No; I was looking for two horizontally-aligned rows of two images each; basically a square. This produces a single vertical column of images (or technically two vertically-aligned rows stacked on top of each other).


Compare two pairs of columns from one dataframe to detect mismatches and show the value from another column in the same row

Question: I´m trying to solve the following problem. I have a dataframe like the following:
 id <- c("1", "2", "3", "4")
 ref <- c("A", "G", "C", "T")
 alt <- c("T", "C", "G", "A")
 ref1 <- c("A", "C", "T", "T")
 alt1 <- c("T", "G", "A", "A")
 df <- data.frame(id, ref,  alt, ref1, alt1)

I need to compare the values in ref/alt column pair and see if it matches to ref1/alt1 values for each row of the dataframe. If it doesn´t match I want that r return the id value for the same row.
I was having trouble to find a simple code to do that and I´ll appreciate a suggestion!
Thanks in advance
dput() output of df:
structure(list(id = c("1", "2", "3", "4"), ref = c("A", "G",
"C", "T"), alt = c("T", "C", "G", "A"), ref1 = c("A", "C", "T",
"T"), alt1 = c("T", "G", "A", "A")), class = "data.frame", row.names = c(NA,
-4L))

Answer: You can use ifelse as follow:
library(tidyverse)

matches <- df %>%
   mutate(check = ifelse(alt==alt1 & ref==ref1, "Yes", "No")) %>%
   filter(check=="Yes")

unique(matches$id)

Comment: This works, but to fully answer the question you would want to filter for "No", not "Yes". At the same time the `ifelse()` part can be skipped. Whenever you do a comparison statement and that will return a `logical` (`TRUE`/`FALSE`), and that is usually more useful further down the line, than using a `character` variable. In this case it makes the `filter()` more simple. `df %>% mutate(check = alt == alt1 & ref == ref1) %>% filter(!check) %>% pull(id)` does the trick.
Answer: A tidyverse solution.
libary(tidyverse)

df %>%
  mutate(ref_check = ref == ref1,
         alt_check = alt == alt1,
         both_ceck = ref_check & alt_check) %>%
  filter(!both_ceck) %>%
  pull(id)

And a base R solution.
df[df$ref != df$ref1 & df$alt != df$alt1, ]$id


Count all items inside a collection entry

Question: I have the collection:
<code>    {'_id':'1',
     'n1':'a',
     'f4':'4rrf'},

    {'_id':2
     'k545':'aad5',
     '1dd':'1s',
     '1yh':'sxaa',
     '6uu':'jt',
     }]
</code>
Where all the entries are nested at the same level as '_id', I would like a query that count all the entries per '_id', with the following output:
<code>{'_id':1,
 'count':2},
{'_id':2,
 'count':4
}
</code>
Answer: Use Aggregation Framework which has a array $size operator which you can use:
<code>> db.mycollection.aggregate([{$project: { count: { $size:"$_id" }}}])
</code>
Comment: sadly it crashes:
"errmsg" : "The argument to $size must be an array, but was of type: string",


Wrong 1st argument type. Found: android.webkit.WebViewClient, required: android.app.Activity

Question: When I tried to implement Chrome Custom Tabs using shouldOverrideUrlLoading() in webViewClient() I am getting the following error:

Wrong 1st argument type. Found: 'android.webkit.WebViewClient', required: 'android.app.Activity'

Here is my code - I am using this GitHub repository https://github.com/GoogleChrome/custom-tabs-client.
The error is coming from my usage of the this keyword.
I am in Fragment, not in Activity
mWebView.setWebViewClient(new WebViewClient() {

    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().build();
        CustomTabActivityHelper.openCustomTab(this, customTabsIntent, Uri.parse(url), new WebviewFallback());

        Toast toast = Toast.makeText(getApplicationContext(),
        "This is a message displayed in a Toast" + url, Toast.LENGTH_SHORT);

        toast.show();
        return true;
    }

}

Comment: CustomTabActivityHelper is not found. How to resolve it?
Answer: You are using this is within the context of an anonymous class (new WebViewClient()), so this is referring a type of WebViewClient.
Since you're using a fragment, you can replace this with getActivity():
CustomTabActivityHelper.openCustomTab(getActivity(), customTabsIntent, Uri.parse(url), new WebviewFallback());

Comment: You don't need `.this` after `getActivity()`.
Comment: Thanks for the answer, if i am inside a fragment, what should i use ?
Comment: `CustomTabActivityHelper.openCustomTab(getActivity().this, customTabsIntent, Uri.parse(url), new WebviewFallback());` It is showing error at this as ") expected" am i missing anything here?
Answer: Looks like "this" is your WebViewClient not your Activity.
If your shown code is in a Activity, try to use "YourActivity.this" to specify.
Hope it helped.
Comment: You can use [getActivity()](http://developer.android.com/reference/android/app/Fragment.html#getActivity%28%29) to get the activity of the fragment.
Comment: I am using inside a fragment, so what should i use ?
Comment: `CustomTabActivityHelper.openCustomTab(getActivity().this, customTabsIntent, Uri.parse(url), new WebviewFallback());`  It is showing error at this as ") expected" am i missing anything here?
Comment: Because you are in an anonymous class you need to call `YourFragment.this.getActivity()`.
Answer: It may be depends on the android build version problem, the below code will work successfully on 2.3+ builds, check this out
ourBrow.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedError(WebView view, int errorCode,
        String description, String failingUrl) {
            Log.d("WEB_VIEW_TEST", "error code:" + errorCode + " - " + description);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // handle different requests for different type of files
            // this example handles downloads requests for .apk and .mp3 files
            // everything else the webview can handle normally
            if (url.endsWith(".apk")) {
                Uri source = Uri.parse(url);
                // Make a new request pointing to the .apk url
                DownloadManager.Request request = new DownloadManager.Request(source);
                // appears the same in Notification bar while downloading
                request.setDescription("Description for the DownloadManager Bar");
                request.setTitle("YourApp.apk");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                }
                // save the file in the "Downloads" folder of SDCARD
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "SmartPigs.apk");
                // get download service and enqueue file
                DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                manager.enqueue(request);
            }
            else if(url.endsWith(".mp3")) {
                // if the link points to an .mp3 resource do something else
            }
            // if there is a link to anything else than .apk or .mp3 load the URL in the webview
            else view.loadUrl(url);
            return true;
    }
});


Compact formula for the Fourier transform of $x^n$ exists?

Question: Is it possible to derive a compact formula for the Fourier transform of $f(x)=x^n$ given by $$\tilde{f}(k)=\int\limits_{-\infty}^{+\infty}x^n e^{ikx}dx$$ (where $x$ is a real variable and $n$ is a positive or negative integer or zero) which shows the sigularities explicitly for certain values of $n$?
Comment: $x\mapsto x^n$ is not in $L^1(\mathbb R)$ for any $n$
Comment: @MaximilianJanisch What about this? [Computing Fourier transform of power law](https://math.stackexchange.com/questions/2173780/computing-fourier-transform-of-power-law)
Answer: Yes, the formal computations are indicated in the link by mithusengupta123 Computing Fourier transform of power law
However, as mentioned by Maximilian Janisch , $x^n$ is not an $L^1$ function, so in general you will need the Theory of Distributions to define the Fourier transform on these generalization of functions. A distributions $f$ is defined as linear forms on smooth and compactly supported functions $\varphi ∈ C^\infty_c(\mathbb{R})$, so that instead of looking to $f(x)$ you look at $\langle f,\varphi\rangle$ which if $f$ is a usual fonction will give
$$
\langle f,\varphi\rangle := \int_{-\infty}^∞  f(x)\,\varphi(x)\,\mathrm{d}x.
$$
Two distributions $f$ and $g$ are equal when for every $\varphi ∈ C^\infty_c(\mathbb{R})$,
$$
\langle f,\varphi\rangle = \langle g,\varphi\rangle.
$$
(and this is compatible with locally integrable functions: if two locally integrable functions $f$ and $g$ are equal in the above sense, then they are equal almost everywhere).
For example, if $f=x^n$, then
$$
\langle f,\varphi\rangle := \int_{-\infty}^∞  x^n\,\varphi(x)\,\mathrm{d}x.
$$
But there are other distributions that are not functions, such that the Dirac delta measure $\delta_0$. This distribution is defined by
$$
\langle\delta_0,\varphi\rangle = \varphi(0).
$$
(In particular $∫\delta_0(\mathrm{d}x) = \langle\delta_0,1\rangle =1$)
With this theory, you get that the Fourier transform of $x^n$ when $n\in\mathbb{N}$ is given by
$$
\mathcal{F}(x^n) = 2π i^n \delta^{(n)}_0,
$$
where $\delta^{(n)}_0$ is the $n^{th}$ derivative of the Dirac delta measure. When $n<0$, then you will find
$$
\mathcal{F}(x^n) = i\pi \frac{(ix)^{|n|-1}}{(|n|-1)!} \mathrm{sign}(x).
$$
(This one is in particular a function in the usual sense.)
To prove that, you can start with the case $n=0$ which is given by the Fourier inversion theorem, and then take the derivatives/antiderivatives of the identity obtained to get the others identities (the derivative in the sense of distribution being defined by $\langle f',\varphi\rangle := -\langle f,\varphi'\rangle$).


What's the term for expanding search results to include variations of a word?

Question: It's not uncommon for a search engine to take a word that is searched for, say "vase" or "obscure", and extrapolate the results to include common versions of the word. So using the earlier examples, you'd include "vases" for results of "vase" and conjugations like "obscures", "obscuring", or "obscured" for results of "obscure".
There's a term for this process, I learned it once and we mention it now-and-then as we talk about our own search system (guess what I'm about to report a bug in! ♪), but I've forgotten the term and cannot find it again. Do you know what the term for this is? Is this in fact a common and accepted term?
Comment: Hi @Grace, I can see you're new to the site. If you think an answer is correct, mark it as 'accepted' by clicking the tick mark on the left hand side. This earns you reputation!
Answer: It is Stemming.

A stemmer for English, for example, should identify the string "cats" (and possibly "catlike", "catty" etc.) as based on the root "cat", and "stemmer", "stemming", "stemmed" as based on "stem". A stemming algorithm reduces the words "fishing", "fished", "fish", and "fisher" to the root word, "fish".

You may find that the variant used in a search engine may be a suffix-stripper, that uses a dictionary with rules to remove suffices from words to get back to the stem.
Comment: Huh. I guess that kinda makes sense, especially the imagery of "stems" coming from a "root" (and I always did think about roots, so at first I kept thinking "branches", maybe?). A quick search on our chat tells me that this is the term that was tossed around internally. Thank you much!
Comment: See also [What's the Difference Between Stemming and Lemmatization?](http://www.ideaeng.com/stemming-lemmatization-0601) Lemmatization includes stemming as well as more general word matching, including synonyms, abbreviations, and typos.


mpAndroid RealTime data plot in LineChart from sensors in Kotlin, any suggestions to speed up the plot?

Question: I am building an Android app in Kotlin and i am really new to this.
My app gets data from a sensor that sends 250 data in one sec (250Hz) and save them in a local file and at the same time send them to a server via HTTP requests.
Also there is the possibility to watch these data in app via a Graph, i choose mpAndroid to plot the data into a linear chart.
I have already everything working 100%, except for the live chart, it works but it has a very slow rendering. It can go up to 3 or 4 minutes of delay since the start of the plotting and i need it as close as possible.
Basically my updateGraph method is triggered by few booleans values. When i click on the button to show the graph the boolean value changes to true and the method that receives data from the sensor starts collecting data into an array.
The updateGraph method is called in the onResume method of the LiveGraph Activity, it gets the array and add the data to the Y axis to plot them and actually it does, but as said with a big delay. I am sure the data are right because on the web server i can see them properly.
This is my main thread:
fun renderChartThread() {
    val thread = Thread(Runnable {
            runOnUiThread {
                renderLineChartOnline()
       }
    })
    thread.start()
}

This is the renderLineChartOnline method:
fun renderLineChartOnline(){

    isRendering = true

    var mChart: LineChart = graph

    yArray.add(Entry(0.toFloat(), 1.20!!.toFloat()))
    set1 = LineDataSet(yArray, "Saved Session")

    set1.setDrawCircles(false);
    set1.setDrawValues(false);
    set1.setLineWidth(2f)

    val data = LineData(set1)
    mChart.setData(data)

    mChart.getAxisRight().setEnabled(false);

    val xAxis = mChart.xAxis
    xAxis.position = XAxis.XAxisPosition.BOTTOM_INSIDE
    xAxis.setDrawGridLines(false)
    xAxis.granularity = 1f

    xAxis.textSize = 8f

    xAxis.valueFormatter = IndexAxisValueFormatter(xLabel)

}

This is the onResume method
 override fun onResume() {
    super.onResume()

    if (MainActivity.isLiveView == true) {

        var mChart: LineChart = graph

       //Getting the data from the device activity
        dataPoints = SocketActivity.liveBRTDataPoint

        updateLiveDataset(dataPoints, mChart)

        }
    mHandler.postDelayed(mTimer2, 1000)
    }

And as last this is my updateGraph method:
fun updateLiveDataset(var1: ArrayList<Float>, mChart: LineChart) {

    var i = 0
    mTimer2 = object : Runnable {
        override fun run() {
            i++

            yArray.add(Entry(i.toFloat(), var1[i]!!.toFloat()))

            // limit the number of visible entries
            mChart.setVisibleXRangeMaximum(750f)
            mChart.setVisibleXRangeMinimum(750f)

            set1 = LineDataSet(yArray, "Live View")
            set1.setDrawCircles(false)
            set1.setDrawValues(false)
            set1.setLineWidth(2f)

            mChart.getAxisRight().setEnabled(false);

            data = LineData(set1)
            mChart.data = data

            mChart.setAutoScaleMinMaxEnabled(true);

            mChart.axisLeft.removeAllLimitLines()
            mChart.axisLeft.resetAxisMaximum()
            mChart.axisLeft.resetAxisMinimum()

            mChart.notifyDataSetChanged();
            mChart.moveViewToX(var1.size.toFloat())

            mChart.invalidate()
            mChart.notifyDataSetChanged()
            mHandler.postDelayed(mTimer2, 4)
        }
    }
}

Does anyone have any suggestion on how to speed up this process?
Answer: Ok, i found a solution that plot real time data and I would like to post to you the solution, maybe can be helpful to someone else. But this gained another problem, i am missing data in the plot process, off course, because the variable that calls the real time array is not synchronized with the function that receives the data from the device.
This is my updated up code.
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import kotlinx.android.synthetic.main.activity_live_graph.*
import okhttp3.Response
import java.io.File
import java.io.InputStream

class LiveGraph : AppCompatActivity() {

    companion object{
        var isRendering:Boolean = false
        var isEcg:Boolean = false
        var isBrt:Boolean = false
    }

    lateinit var chart: LineChart

    var dataPoints = ArrayList<Float>()
    var pre_filter = ArrayList<Float>()
    var yArray = ArrayList<Entry>()
    lateinit var set1: LineDataSet
    var xLabel = ArrayList<String>()
    var data = LineData()

    private val mHandler: Handler = Handler()
    private var mTimer2: Runnable? = null

    lateinit var file: String

    var thread: Thread? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_live_graph)

        // lock the current device orientation
        val currentOrientation = this.resources.configuration.orientation
        if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
            this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        } else {
            this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        }

        // Keep screen awake
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        chart = graph

        run(chart)

    }

    fun renderChartOnline(data: ArrayList<Float>, chart: LineChart) {

        var i = 0
        if (data.size>0){
            for (d in data) {
                i +=1
                yArray.add(Entry(i.toFloat(), d.toFloat()))
                var sec = i/250.toFloat()
                val mainHandler = Handler(Looper.getMainLooper())

                if (sec > 60){
                    var min = sec/60.toFloat()
                    xLabel.add(min.toString()+"min")
                } else{
                    xLabel.add(sec.toString()+"sec")
                }
            }
        }else{
            yArray.add(Entry(0.toFloat(), 1.20!!.toFloat()))
        }

        set1 = LineDataSet(yArray, "Saved Session")

        set1.setDrawCircles(false);
        set1.setDrawValues(false);
        set1.setLineWidth(2f)

        val data = LineData(set1)
        chart.setData(data)

        chart.getAxisRight().setEnabled(false);

        val xAxis = chart.xAxis
        xAxis.position = XAxis.XAxisPosition.BOTTOM_INSIDE
        xAxis.setDrawGridLines(false)
        xAxis.granularity = 1f // only intervals of 1 day

        xAxis.textSize = 8f

        xAxis.valueFormatter = IndexAxisValueFormatter(xLabel)

        chart.invalidate()
    }

    fun run(chart: LineChart){

            runOnlineGraph()
            val mainHandler = Handler(Looper.getMainLooper())

        }

    fun runOnlineGraph(){
        isRendering = true
        feedMultiple()
    }

    private fun feedMultiple() {
        if (thread != null) thread!!.interrupt()

        val runnable = Runnable { addEntry() }

        thread = Thread(Runnable {
            while (true) {
                runOnUiThread(runnable)
                try {
                    Thread.sleep(4)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        })
        thread!!.start()
    }

    override fun onResume() {
        super.onResume()
        dataPoints = SocketActivity.liveECGDataPoint
        renderChartOnline(dataPoints, chart)
    }

    private fun addEntry() {

      /***
         * Whit this i get the data saved in the Socket process,
         * but this gives me the problem of missing datas received,
         * if i use an array the delay increase too much then,
         * so i m still looking for a solution to this point
         */

        dataPoints = SocketActivity.liveDataForGraph
        val data = chart.data
        if (data != null) {
            var set = data.getDataSetByIndex(0)
            // set.addEntry(...); // can be called as well
            if (set1 == null) {
                data.addDataSet(set)
            }
            for (i in dataPoints){
                data.addEntry(
                    Entry(
                        set.entryCount.toFloat(),
                        i
                    ), 0
                )

            data.notifyDataChanged()

            // let the chart know it's data has changed
            chart.notifyDataSetChanged()

            // move to the latest entry
            chart.moveViewToX(data.entryCount.toFloat())

            // limit the number of visible entries
            chart.setVisibleXRangeMaximum(750f)
            chart.setVisibleXRangeMinimum(750f)

            chart.getAxisRight().setEnabled(false);
            // move to the latest entry
            chart.moveViewToX(data.entryCount.toFloat())

            chart.setAutoScaleMinMaxEnabled(true);

            chart.axisLeft.removeAllLimitLines()
            chart.axisLeft.resetAxisMaximum()
            chart.axisLeft.resetAxisMinimum()

            chart.notifyDataSetChanged(); // let the chart know it's data changed

            chart.invalidate()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeCallbacks(mTimer2);

        isRendering = false
    }
}


Bash test command with 2 conditions

Question: I'm trying to execute a bash test command with 2 conditions.
test "4" = "4" && "5" = "5" || echo "false"
I'm expecting it to not print false since both conditions are true. But what I'm actually getting is this:
5: command not found
false

Why is this happening?
Comment: I recommend `[[ "4" = "4" && "5" = "5" ]]` instead of the not working `test "4" = "4" && "5" = "5"`
Answer: && goes between commands and combines their statuses. Your second command is just
"5" = "5"

which tries to run 5 as a command.
You need to repeat test.
test "4" = "4" && test "5" = "5" || echo "false"

You can also use the -a operator of the test command:
test "4" = "4" -a "5" = "5" || echo "false"

But this is not recommended; this operator is deprecated because it can be ambiguous in some cases.
Comment: `-a` (along with `-o`) is typically not recommended as it is [deprecated](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html) and has poorly defined behavior in more complex conditions.

Bash test command with 2 conditions


Execute a script on window's change

Question: Is there an easy way to execute a script when the active window changes ?
Is there a universal solution for both Xorg and Wayland ?
My goal is to execute a script that will determine either or not to execute another script when the current window change.
In other words when I change the active window (disregarding the type of event: mouse event or keyboard event, ...) the script should get executed.
[ The script then verifies the current window name and execute a script if it matches a certain pattern (for instance "is the current window an internet browser ?"). But that part is out of the question. ]
How would you do that ?
I was thinking about making a polling daemon (every .5s) that runs the script and use xdotool within to get the window's name.
But again I wish to hear more ideas.
Thanks in advance.
Answer: For those who are interested, here's how I succeeded to make it working.
I created a script :
#!/usr/bin/sh

while true
do
    if [[ "$(xdotool getwindowfocus getwindowname)" =~ "Chrome" ]]
    then
        xbindkeys 2>/dev/null
    else
        killall xbindkeys 2>/dev/null
    fi
    sleep 0.5
done

I run this script on login, when I switch to a Chrome window xbindkeys runs along with the config file ~/.xbindkeysrc containing the Emacs keys.
It's not very elegant but it works.
Comment: xdotool on Wayland? on xorg, use Wnck.Screen signal active-window-changed.
Comment: @JacobVlijm I don't code but I think it's good information for people who will fall on this post, thanks.

Execute a script on window's change


Resource file modification date

Question: I am getting an image from a resource file like this:
<code>Image img = (Image)Resources.ResourceManager.GetObject(imgName) as Image;
</code>
Is there a way to get the modification date of this image?
Comment: I *expect* that as a resource you only have the name/contents pair, not full file metadata. I would not *personally* expect this to be possible. I could be wrong, of course.
Comment: ill handle it in other way, because i needed it for my own http server, but ill just generate md5sum from file and send etag to browser, so than ill compare md5sums and i hope that will let me know if browser got same file or not
Answer: Sorry, you won't be able to access that information as the image is loaded into the assembly as binary information, not as a file.

Resource file modification date


Modify SOAP envelop to include Namespace

Question: I have SOAP response of something like this
<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope
    xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>
    <soapenv:Body>
        <calculate_response>
            <tid>33433</tid>
            <status>0</status>
            <reason>0</reason>
        </calculate_response>
    </soapenv:Body>
</soapenv:Envelope>

I need to add namespace to it and it should look something like this
<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    xmlns:def="http://com.sample.xyz/Messages">
    <soapenv:Body>
        <def:calculate_response>
            <tid>33433</tid>
            <status>0</status>
            <reason>0</reason>
        </def:calculate_response>
    </soapenv:Body>
</soapenv:Envelope>

I have created stub using wsimport, and I need this response to be modified before processing it further.
Actually it's a two step process as I understood , first step is to add namespace to soap envelop then add prefix to it.
Regarding prefix part I found this . I'm not clear about how to do first step.
Note: I need to modify response at client side and I cannot change SOAP at server side.
Comment: Why do you need to change the response at client side? What are you trying to achieve by adding that namespace?
Comment: Actually soap client is expecting a response to be of type `{http://com.sample.xyz/Messages}calculate_response`, where as it is not returned by the server, It happens to be missing namespace.
Comment: Why don't you regenerate the Soap client classes so that they match the response sent by the server?
Comment: I did, I used wsdl, xsd from server to generate client classes but it is expecting a response to be like that where as server is not returning it.
Answer: I have achieved this with the help of SOAP Message Handlers
I've written handler which implements SOAPHandler<SOAPMessageContext>
and overridden its handleMessage(SOAPMessageContext context){} with following implementation.
//Get soapElement from your soap request.
if (soapElement.getTagName().equalsIgnoreCase("calculate_response")) {
       soapElement.setElementQName(
         new QName("http://com.sample.xyz/Messages",
                  "calculate_response",
                  "def"));


control PC using alexa

Question: I have got a requirement of controlling PC/Computer using Alexa skill, i.e if I want to open an excel file on PC then if I simply say Alexa, ask openexcel to open excel file then excel file should be opened.
Can someone please guide me on how to proceed on this requirement.
Thanks
Varun
Comment: This is not how you ask questions on Stackoverflow, please review the guidelines.
Answer: Short overview:

You need a webserver on your local machine to answer Alexa's requests (I'd suggest Python's simplehttpserver)
Have the handlers on your webserver control Excel or whatever you need to do (that depends a lot on your os, you didn't mention which you use).
You need an SSL endpoint to your local webserver (the easy solution is to run ngrok, check ngrok.com
Comment: Thanks Josep  for the response. I am using Windows server.

control PC using alexa


What is the least value of the function $y= (x-2) (x-4)^2 (x-6) + 6$?

Question: What is the least value of function:
$$y= (x-2)  (x-4)^2  (x-6) + 6$$
For real values of $x$ ?
Does $\frac{dy}{dx} = 0$, give the value of $x$ which will give least value of $y$?
Thanks in advance.
Comment: $y'(x) = 0$ may give $3$ values of $x: x_1,x_2,x_3$; you choose among them the one such that $y(x_i)$ is minimal. Don't forget to show that $y(x)$ and $y(-x)$ is large for large $x$, so the least value is not attained at $\infty$ or $-\infty$
Comment: Note that the function is obviously symmetric around $x=4$ and will have a local maximum there (quick sketch) - so (given degree 4) you expect two answers symmetrically placed. This motivates the substitutions in Martin Sleziak's answer, and also gives a check on computation. The value of $y (=6)$ at $x=2,4,6$ shows solutions will be strictly between 2 and 4, and 4 and 6.
Comment: Your title should say "What is the least value of the function?".  The word "equation" is another one of those words that get incorrectly used as a catch-all.
Answer: $$\frac{dy}{dx} = (x-4)^2 (x-6)+(x-4)^2 (x-2)+2(x-2)(x-4)(x-6) = 0 $$
$$ \Rightarrow (x-4) \left[ (x-4)(2x-8)+2(x-2)(x-6) \right] = 0$$
$$ \Rightarrow (x-4) \left[ 2x^2-16x+32+2x^2-16x+24 \right] = 0$$
$$ \Rightarrow (x-4) \left[ 4x^2-32x+56 \right] = 0$$
$$ \Rightarrow 4(x-4) \left[ (x-4+\sqrt{2})(x-4-\sqrt{2}) \right] = 0$$
There is a maxima or minima at $x=4, \hspace{5pt}x=(4-\sqrt{2}),\hspace{5pt} x=(4+\sqrt{2})$
If you take the second derivative and find where the second derivative is positive, that is where the function value has a minima.
Second derivative is
$$8(x-4)^2+4(x-4+\sqrt{2})(x-4-\sqrt{2})$$
And at $x=4\pm\sqrt{2}$ for instance the second derivative is positive and therefore at it is minimum at those points.
Comment: It's $56$, not $58$. And accordingly, the answers are $x=4$, $x=4-\sqrt 2$ and $x=4+\sqrt 2$
Comment: Thanks for all nice comments
Comment: You need to phrase that a bit more carefully, since a slope of zero does not imply the existence of a maximum or minimum: consider $y=x^3$ at $x=0$.
Comment: $32+24=56$ not 58. I think you should get $4\pm\sqrt{2}$ as the points where the derivative is equal to zero instead of $4\pm\frac{\sqrt6}2$.
Comment: Okay, I was about to upvote your answer but you really need to edit it. $6$ is the maximum value, not the minimum.
Answer: An alternative solution using AM-GM inequality instead of derivatives.

If you use substitution $t=x-4$, then you want to minimize $t^2(t-2)(t+2)+6$, which is equivalent to minimizing
$$g(t)=t^2(t-2)(t+2)=t^2(t^2-4).$$
Obviously $g(t)\ge 0$ whenever $t^2\ge 4$. We can use another substitution $s=t^2$ and ask for minimum of $s(s-4)$ for $s\in\langle 0,4 \rangle$.
If we change the sign, this is the same thing as looking for the maximum of
$$h(s)=s(4-s)$$
for $s\in\langle 0,4 \rangle$.
Now we can use AM-GM inequality to see that
$$h(s)=s(4-s) \le \left(\frac{s+(4-s)}2\right)^2 = 2^2=4,$$
where the equality is attained only for $s=4-s$, i.e. $s=2$.
This leads to $t=\pm\sqrt2$ and $x=4\pm\sqrt2$. The minimal value is 2. (Obtained as $6-4=2$, since $4$ is the maximal possible value of $h(s)$.)

You can check this at wolframalpha: minimize (x-2) * (x-4)^2 * (x-6) + 6.
Comment: Completing the square works too: the minimum of $s(s-4) = (s-2)^2-4$ is clearly $-4$ when $s=2$.
Answer: Since you are asked to find the least value of
$$\tag{1}
f(x)=(x-2)(x-4)^2(x-6)+6
$$
over the reals, you are looking for the  global minimum value, if there is one.

Your function is continuous, so the following general procedure is applicable:
Given a continuous function $g$ defined on a nondegenerate interval $I$, to determine if $g$ has a global minimum value on $I$ and to find its value when it exists:

Examine the "endpoint behaviour" of $g$. For example:

If $I=[a,b]$, evaluate $g(a)$ and $g(b)$.
If $I=(a,b)$, calculate $\lim\limits_{x\rightarrow a^+} g(x)$ and    $\lim\limits_{x\rightarrow b^-} g(x)$.
If $I= \Bbb R$, calculate $\lim\limits_{x\rightarrow\infty} g(x)$ and    $\lim\limits_{x\rightarrow-\infty} g(x)$.

There are other cases to consider, but I hope that it's obvious what
to do in those cases.
The quantities found here will be used later, so keep them in mind.
Find all critical points of $g$ in the interval $I$. These are
points $x\in I$ where $g'(x)=0$ or where $g'(x)$ does not exist. These points and any endpoints of $I$ contained in $I$ are the only points at which a global minimum value can occur.
Evaluate the function $g$ at each point found in step 2..
Use the information found in steps 1. and 3. to determine if $g$
has a global  minimum value and what that value is when it exists.
That, is compare the values found in steps 1. and 3.. There are
several cases to consider depending on the form of $I$.  For
example:

If $I=[a,b]$, then $g$ will have a global minimum value. The global    minimum will be the smallest of the quantities found in
steps 1. and    3..
If $I=(a,b)$, then $g$ will have a global minimum value if and only if the smallest value found in step 3. is less than or equal to
both of the limit values found in step 1.. In this case, the global
minimum value of $g$ is the smallest value found in step 3.. Note
here that since $I$ does not include its endpoints,  the endpoints of $I$ are not  candidates for places where the global minimum of $g$, if it exists, can occur.
If $I=\Bbb R$, then $g$ will have a global minimum value if and only    if the smallest value found in step 3. is less than or equal
to both    of limit values found in step 1.. In this case, the global
minimum value of $g$ is the smallest value found in step 3..

Back to our problem:
In our case, the implied domain of $f$ is all of $\Bbb R$.
Step 1:
Note that the function $f$ is a polynomial of degree 4 with positive leading coefficient. This implies that
$$\lim\limits_{x\rightarrow\infty}f(x)=\infty\quad\text{and}\quad
 \lim\limits_{x\rightarrow-\infty}f(x)=\infty.$$
Looking ahead a bit, we can conclude that $f$ does have a global minimum value and that value will be  the smallest value found in step 3..
Step 2:
We first find
$$\tag{2}\eqalign{
f'(x)&=(x-4)^2(x-6)+2(x-2)(x-4)(x-6)+(x-2) (x-4)^2\cr
&=4(x-4)(x^2-8x+14 ).
}$$
The derivative $f'$ exists everywhere. We are left with the task of solving  the equation $f'(x)=0$. This is easy to do looking at $(2)$ and using the quadratic formula: $f'(x)=0$ if and only if
$$
x=4,\quad x={8\pm\sqrt{64-56}\over 2}=4\pm\sqrt2.
$$
Step 3:
We evaluate $f$ at each of the three points found above:
$$\tag{3}
\eqalign{
f(4)&= 6\cr
f(4+\sqrt2)&=(2+\sqrt2)\cdot2\cdot( -2+\sqrt2)+6=2\cr
f(4-\sqrt2)&=(2-\sqrt2)\cdot2\cdot(-2-\sqrt2)+6=2.\cr
}
$$
Step 4:
From step 1., $f(x)$ tends to infinity as $x\rightarrow\infty$ or as  $x\rightarrow-\infty$.
This means that $f$ does have a global minimum value and that that value must be the smallest value found in step 3..
So, from $(3)$, we see that the minumum value of $f$ is $2$. This minimum value is achieved  at two places: $x=4+\sqrt2$ and at $x=4-\sqrt 2$.
Answer: Note that $(x-2)(x-6)=x^2-8x+12$ and $(x-4)^2=x^2-8x+16$. This suggests the symmetrizing substitution $w=x^2-8x+14$. Thus
$$y=(w-2)(w+2)+6=w^2+2.$$
We want to minimize the absolute value of $w$. But $w=(x-4)^2-2$. So $w$ has minimum absolute value $0$, reached when $(x-4)^2=2$, that is, when $x=4\pm\sqrt{2}$.  The minimum value of $y$ is $2$.
Remark: The curve $y=(x-2)(x-4)^2(x-6)+6$ is very special, with a beautiful double symmetry. It seems likely that the method used above was the intended one. The same idea works for $(x-a)(x-b)(x-c)(x-d)+k$, where $a+d=b+c$.
Answer: $$y= (x-2)  (x-4)^2  (x-6) + 6$$
$let , t = x-4$
$$y= t^2(t-2)(t+2)+ 6$$
$$y= t^4-4t^2+6 $$
$$y=(t^2-2)^2+2$$
$$y(min)=2$$
attained when $t^2=2$
$(x-4)^2=2$ which gives, $ x=4-\sqrt2$ and $ x=4+\sqrt2$


Is my plan to replace interior doors reasonable?

Question: I bought some pre-hung doors, intending to replace several interior doors. The problem is, the existing door jambs are shallower than usual -- I think 3.5" instead of 4.5". So if I simply remove the old doors and install the new pre-hung doors, I'll need to build up the frame or something to attach the casing. Seems like a big hassle, and not likely to look good.
So I thought maybe the best plan would be to leave the frames in place, but replace the doors. I figure:

Remove the hinges from the existing frames
Use wood putty to fill the spots where the hinges were (is this a mortise?)
On the new door, measure the location of the hinges
Use the hinges to draw a template on the existing frames
Drill pilot holes for where the screws will go on the existing framse
Use a router to mortise the hinge template
Screw in the hinges
Hang the door
Beer

I'm obviously 99% clueless so if this is a terrible plan, please let me know.
Comment: why wouldn't you just trim the prehung jamb to 3.5"?
Comment: The other options are, as @FreshCodemonger said, to trim down the new door casing by 1", or, center the new door in the opening so you've got about 1/2" on each side and apply a slightly thicker casing on each side.
Comment: It's very odd for prehung jambs to be _larger_ than the old ones. Are you sure? I've revised my badly off-the-mark answer.
Comment: You missed a meaningful step in the "hang a new door in an old opening" list: 2a. Fit the square door to the out of square opening by cutting the top/ bottom and strike side as necessary. Bevel the strike side if it got cut.
Answer: There's nothing inherently wrong with your plan aside from the massive amount of work needed. With good technique, a high level of precision, and the proper filler material you can arrive at a good outcome, but it would be fussy work. If you're up for that, have at it.
Another probably easier option is to disassemble the jambs, rip them in half behind the stop location, and remove material to shrink the jamb depth. Then reassemble. The surgical scar will be hidden by the stop. (Modern jambs are usually veneered and radiused.)
If you happen to have solid wood jambs (very rare in my experience), you could simply rip off one side and re-sand the face, but that may actually be more work.
Disassembly usually starts with popping the stops off. They're usually shot on with trim nails. Pull the nails through from the back side with a locking or channel pliers. Then gently knock apart the corner joints in the direction of their nails.
Be sure to size your jambs to the largest wall thickness in each case. Your trim will be easier to fit then. Reattach the jambs however you like so that the fasteners are hidden by the casing. Trim nails and glue work well, but the ideal solution may be pocket screws. Inexpensive kits make that easy. Screws don't wiggle loose and you could forego the glue. Glue is usually a good idea, though.
Comment: Second best would be a circular saw with a sharp blade and a rip guide. Again, just one rip on the far side of the jamb. (I'm not usually a fan of rip guides, but this is about the best application of one I can think of.) Top tip: rip to the widest width of the existing wall: it's way easier to case when the jamb is a bit proud.
Comment: Thanks all. It sounds like ripping the jambs might be the way to go. @isherwood -- can you elaborate on the fussiness of my original plan? What strikes you as particularly tricky?
Comment: All of it, really. Filling and sanding. Positioning and mortising. It's all slow, tedious work. I could reduce the width of a dozen prehung jambs in the time it would take me to just fill old hinge slots with putty and sand them flat (and square--there's a corner to deal with). Of course, if you're _finishing_ (staining, varnishing, or painting) the prehung doors yourself that is also a slow process. YMMV.
Comment: Maybe I'm missing something, but the "rip out of the middle, hidden by the stop" approach seems unnecessarily complicated. (Both in terms of material handling and alignment for the finished product. Though it does have the upside of allowing any kind of butchery to go unnoticed.)
Comment: I'd find someone with a tablesaw and do one decent rip on the far side of the jamb (not the strike/hinge side) of the disassembled pieces. Most of the cut is covered by casing, so it would only be a bit of sanding to remove saw marks.
Comment: All of my comments above apply to solid wood or (ugh!) mdf jambs. If they were veneered and a visible cut edge would be terrible, cut out of the middle is the way to go.


What is the difference between functionality and implementation details in abstraction?

Question: I'm learning about OOP and Java, and the definition of Abstraction is the process of hiding the implementation details from the user, only the functionality will be provided to the user.
Can someone explain me what is the difference between functionality and implementation details?
Comment: Possible duplicate of [How does abstraction helps in hiding the implementation details in Java?](https://stackoverflow.com/questions/46041202/how-does-abstraction-helps-in-hiding-the-implementation-details-in-java)
Comment: Maybe even better dupe: https://stackoverflow.com/questions/24626/abstraction-vs-information-hiding-vs-encapsulation
Comment: Don't think too much about these definitions. "abstraction", "details" and "functionality" are used because they still have their ordinary meaning you'll find in a dictionary. There's no exact meaning in programming for them. It's a concept that has slightly different meaning to everyone. What people try to say with "abstraction" is that you don't go into details (like what kind of for/while loop you'll use), you keep it at a conceptual level. An "implementation detail" is always whatever you *feel* is too much detail to describe the concept. The same thing might be a concept in other places.
Answer: Real world example: Think of a gear box, the user only have the ability to change gears and that is the functionality.
The mechanism behind the gearbox and how the gear box is working internally is the implementation and the implementation is hidden from the user.
Answer: A good example is the Java List interface.
That provides methods to dynamically add or remove elements to the list. That is the function. How that really happens is not expressed in that interface, and for users of that List interface, it also doesn't matter (too much).
For example, the implementation could be a doubly linked list, where you just change the "links" between the objects in your list, or if an array is used that needs to grow/shrink accordingly, that is up to the implementation) Of course, there are actual pros and cons for the different implementation options, but in many situations, you might decide to not care about them.
Answer: Functionnality : What it does
Implementation : How it does it
Answer: Encapsulation: wrapping up of data into a single unit.single unit(class). within a  class, there are members, data members which wrapped in a unit called class. For example, your bag is a single unit you put books, pens inside the bag. The same class is a single unit.
Resources for Encapsulation:

https://javatutorial.net/java-encapsulation-example
https://www.w3schools.com/java/java_encapsulation.asp

Abstraction: hiding the background details. OOP provides these facilities. we can keep data inside the objects which provide security. The class also provide this facility you cannot access private data of the class. Only public, protected data can be accessible if you want to secure your data when you make it private.
Resources for Abstraction:

https://javatutorial.net/java-abstraction-example
https://www.edureka.co/blog/java-abstraction/
Answer: To put it simply, consider the code below:
public Data getStoredData(int ID) {
    DBConnection conn = DBConnection.getInstance();
    conn.connect();

    Data data = conn.query("..." + ID);

    if(data != null) {
        data.setSomeValue('Some Value');
    }

    return data;
}

The term implementation details are the code you write inside your function.
The term functionality it the method signature or the things you want to expose to the calling client. This is how you want your method to be used.

In the example above, the functionality is this public Data getStoredData(int ID), while your implementation is the one that resides inside it.


Quickest method to sell everything

Question: I've built up a huge empire and have accumulated a sufficient fortune, but unfortunately (accidental pun) my empire is built on by-gone technologies that are limiting my profit potential (though it be the year 2022, my transport system is based primarily on rail, using far outdated engines).
Though the auto-replace feature makes upgrading my road vehicles easy, they are merely auxiliary to my train network which can not be upgraded so easily (I will have to rebuild all the track and stations and depots with monorail)
I've also found some deficiencies with my network on a very deep rooted, structural level, and am now looking to start over - removing all of my constructions and establishments whilst maintaining my wealth (rather than starting a new game).
Doing this the conventional way (the bulldozer) will take hours of tedious work, and I can't merely drag the bomb across the map (it would destroy the cities of which I've shaped the growth, and surely destroy my company's reputation).
What is the fastest approach to doing this kind of thing?
Will I have to send all my vehicles to depots, then sell them, then the depots, then all the stations and tracks?
Is there a button somewhere to do it all for me, or some kind of shortcut I can take?
Any bright ideas could save me a lot of time and work!
The people of Lartown thank you!
Comment: The fastest way might be to just bulldoze bit by bit.  That gives you the added advantage of updating your routes piecemeal, rather than reconstructing them from scratch.  Those routes that have structural issues might be more complicated to fix, though.
Comment: It's a long time since I've played openttd so I may be wrong, but can you destroy the company and transfer all your wealth to a new company?
Comment: You could try destroying your current company, and then using cheats to give your new company the correct amount of money? http://wiki.openttd.org/Cheats#Increase_money_by_.C2.A310.2C000.2C000
Comment: I saved my map, opened it in multiplayer, opened a new game client, made a new company and tried to transfer the money, but half of it disappeared. Then all of it. But when I destroyed the first company, $80M came back. I can live with that. It successfully destroyed all my constructions (except roads, of course), so I thank you! :)
Comment: Oops. Putting the map back on single player just lost all the money. I don't know how this works. Ah crap.
Comment: That's odd, I can't remember any mechanisms in game for money simply disappearing :S
Comment: I might as well start a new game and use cheats! It's not the same :'(
Comment: It'd probably be easier just to reset the game. That'd get rid of everything pretty damn quickly.
Answer: Can't you do a track conversion? I'm sure there is a tool that lets you convert from one track type to another?
http://wiki.openttd.org/Convert_rail
Comment: @axrwkr It's a button that looks like a piece of track with a looping arrow over the top of it.  On that link above, it's the right most button on the toolbar.
Basically, you select what track type you want to convert to, then click the convert button and drag it over the track you want to convert.
Comment: which one might that be?
Comment: And you can also convert the trains by converting the depot. drive train to depot -> sell train -> upgrade depot -> buy new train. The new train should have the same orders as the one you just sold.
Answer: Destroying your current network
Towns won't allow you to destroy more than a couple buildings before dropping their rating too low, even from the maximum of '1000' rating. It's also quite easy to get enough rating back to build a new station by building trees.
Dragging the bulldoze tool across the map after having sold all your trains or put them in depots is thus quite an effective way of quickly getting rid of your network.
Keep in mind that bulldozing water can get quite expensive. You can hold down the SHIFT key when doing any building or terraforming operation to check how much a that operation will cost in openTTD without executing it.
Upgrading an existing network
I've often had to do this in my games. First off, things become a lot less painful if you have made use of the 'groups' system to group all your collections of trains that have the same orders. However, it still features quite a bit of manual steps with default openTTD installations.
If you have not, then I advise you to make a group for each of those collections. You can do this in the vehicle list. It's a bit of organizing that pays off managing your network later. Groups can also have shared orders which means if you change the orders of one train in the group, all the others will copy your changes.
Then, order all your trains to move to their depots from the same vehicle list by selecting 'all vehicles' then 'manage list' to 'go to depot'. Depending on the amount of depots, the size of your network, and the speed of your vehicles as well as your game settings it may take anywhere between a few months to several years of in-game time before all trains are situated in a depot.
Then, you can start upgrading all your rail with the 'convert rail' tool, except for the depots, to monorail or maglev. It can be found in the rail construction menu.
Afterwards, we can build the new trains. For each of your rail groups, do the following, assuming you're upgrading to maglev (otherwise replace 'maglev' with 'monorail'):

Find the station that's first on the order list of an old train.
Build a new maglev depot near the station.
Manually create a single maglev train that matches the railway train.
Open up the orders menu. Hold down the CTRL key and click on the existing old train in the train list.
Check that the maglev train has copied orders from the existing train.
Now click the 'clone' button in the depot, hold down the CTRL key again (for shared orders) and clone your new maglev train any number of times you want. I advise cloning 1 maglev train for every 2 railway trains you had previously, as they are quite a bit faster, more powerful, and carry more cargo.

There are some newGRFs that can make the process a bit less of a chore. I'd recommend you look into Universal Railtype depots that can support trains of every rail type. With these you can replace railway vehicles with maglev vehicles using autoreplace.
If you're playing on a multiplayer server that spans multiple railway types in its time period, consider recommending this type of newGRF to the admins. It can be configured so that the universal railtype has a speed penalty (e.g. a max speed of say 50 kph) so it can't easily be abused and is only used for depots for type switching without having to have amazing apm to keep up.
Answer: There was a cheat for this in Transport Tycoon Deluxe, where you could make a sign and put Cht: Tracks 1 2 to convert all your rail to monorail or Cht: Tracks 1 3 to convert from rail to maglev.
I'm not sure if this is in OpenTTD, but it might be worth a shot. At least then you'd only have to do some minor network restructuring, rather than rebuilding the whole lot.

Quickest method to sell everything


Question about inertia groups and unramified extensions

Question: Let $K$ be a number field, and $v$ a finite place. If $\bar{K}$ is a separable closure of $K$, then in $G_K=\text{Gal}(\bar{K}/K)$ we can find the decomposition group of (a place over) $v$, which is isomorphic to the Galois group of $\bar{K_v}/K_v$, with $K_v$ the completion at $v$.
It is well know that the fixed field of the inertia $I_v$ in $\bar{K_v}$ is the maximal unramified extension of $K_v$. Is it also true that the fixed field of the inertia in $\bar{K}$ is the maximal extension of $K$ unramified at $v$? I think this is true, since we can easily move to the finite case where is true, but also I could appreciate a check.
After this, if we consider the maximal extension of $K$ unramified at $v$ and $v'$, with $v\ne v'$, then it is the intersection of the maximal extension unramified at $v$ with the one unramified at $v'$ (it is true? It seems to me obvious), therefore, by Galois correspondence, the product of the inertia $I_vI_{v'}$ is the group corresponding to that field.
But what happens if we consider the maximal extension unramified outside a finite set of places, so unramified at an infinite set of places? The infinite intersection would correspond to an infinite product of subgroups, which of course make no sense. So have we to compute it with, maybe, inverse limit, or something like this?
(My final goal is to understand a proof in Rubin's book Euler systems: he proved that, given a Galois representation $T$ with coefficients in the valuation ring $O$ of a finite extension of $\mathbb{Q}_p$, and a finite set of primes $\Sigma$ containing all primes where $T$ ramifies, primes above $p$ and infinite places, then the Selmer group $S^{\Sigma}(K,T)$ is equal to $H^1(K_{\Sigma}/K,T)$, where $K_{\Sigma}$ is the maximal extension unramified outside $\Sigma$.
The proof is the following: $$\begin{split}S^{\Sigma}(K,T)&\overset{(1)}{=}\ker \left(H^1(K,T)\to \prod_{v\not\in\Sigma} H^1(K_v,T)/H_f^1(K_v,T)\right)=
\\&\overset{(2)}{=}\ker\left(H^1(K,T)\to\prod_{v\not\in\Sigma}\text{Hom}(I_v,T)\right)=\\&\overset{(3)}{=}\ker\left(H^1(K,T)\to H^1(K_{\Sigma},T)\right){=}H^1(K_{\Sigma}/K,T).
\end{split}$$
(1) is the definition. In (2) we need $\text{Hom}(I_v,T)^{Fr}$, the fixed points of Frobenius, but not a big deal, since we want the kernel,so we can enlarge the codomain. But my big problem is in (3), with which the question is related).
Comment: The compositum of infinitely many subgroups is well-defined, it is just the smallest subgroup containing all of them. I think it should do the job (maybe add "smallest closed" for the Galois correspondence).
Comment: Yes, you're right... And is this isomorphic to the direct sum of all of them? If so, this could also help for (3), since $\prod_{v\not\in \Sigma}\text{Hom}(I_v,T)\cong \text{Hom}(\oplus_{v\not\in \Sigma} I_v,T)$, and so maybe $\oplus_{v\not\in \Sigma} I_v=\text{Gal}(K_{\Sigma}/K)$... But I think that, to be true, they need to have trivial intersections.
Comment: I don't think the elements in different inertia subgroups commute, so I don't think you can get a direct sum.
Comment: Ye, the inertia are normal but not of trivial intersection
Comment: One last thought is that the inertia subgroups should generate the absolute galois group of $K_\Sigma$ and so homomorphisms from the absolute galois group to $T$ are determined by their actions on each $I_v$. I don't feel comfortable enough with homology to address (3) but maybe that works for the twisted homomorphisms in $H^1$ and that would at least be a start for passing from the second to the third lines.
Answer: Pick a place $w$ of $\overline{K}$ above $v$. The absolute Galois group acts transitively on those places so we don't care which $w$ we chose.
By density of $\overline{K}$ in $\overline{K}_w\cong \overline{K_v}$ then $Gal(\overline{K}_w/K_v)$ is the $\sigma\in Gal(\overline{K}/K)$ that are continuous for $w$, ie. $D_w$.
$$I_w = Gal(\overline{K}_w/K_v^{nr}), \qquad K_v^{nr}=\bigcup_{n\ge 1} K_v(\zeta_{p^n-1})$$
For a finite Galois extension $L/K$, iff $L$ is fixed by $I_w$ then $L\subset K_v^{nr}$ to that $L/K$ is unramified at $w|_L$. And since $L/K$ is Galois we have unramified at $w|_L$ iff unramified at all the places above $v$.
$\overline{K}^{I_w}$ is the largest extension of $K$ unramified at $w$, not the same as unramified at all the places above $v$.
When considering the largest extension unramified at a set of places, consider the subfield fixed by the all corresponding intertia groups, ie. the subfield fixed by the subgroup of $Gal(\overline{K}/K)$ generated by those intertia groups.


Gaussian primes and Lucas numbers

Question: Let $L_{n}$ be the $n$ th Lucas number. For example, $L_{1} = 1, L_{2} = 3, L_{3} = 4$.
Conjecture: there is no Gaussian primes in the sequence $(L_{n-1} + L_{n} i)$ for $n = 2$ to $\infty$.
I hope that this will be proved or disproved.
Answer: $L_{n-1}+L_n i= (2+i)(F_n+F_{n-1}i)$.
Comment: What if we modify the conjecture to Fibonacci instead of Lucas ?
Answer: Your conjecture is true; the sum of the squares of the components is always divisible by 5. Indeed it is easy to show by induction that $L_{n+1}^2+L_n^2=5F_{2n}$ where $F_{2n}$ is the $2n^{th}$ Fibonacci number.

Gaussian primes and Lucas numbers


How to mock a un-export (private) function inside user module using Jest

Question: I have a "private" function which wraps the common functionality for an API request and I have a bunch of "public" functions to fire the actual requests with request configuration object (see below in requestUploadStatementFile file).
I am trying to test these public functions but I am not sure how to mock the private function using Jest, in this case, requestWithAutoTokenRenew function.
/**
 * An API wrapper which auto renew JTW once it get expired
 *
 * @param {Object} requestConfig Request configuration object
 * @returns {Promise}
 */
const requestWithAutoTokenRenew = async requestConfig => {
  const session = await doGetSession();
  const sessionToken = session.idToken.jwtToken;
  const { url, method, params, payload } = requestConfig;
  const requestObj = {
    url,
    method,
    headers: {
      Accept: "application/json",
      Authorization: sessionToken,
      "Content-Type": "application/json"
    },
    data: payload,
    ...params
  };

  return axios.request(requestObj).then(response => response.data);
};

/**
 * Upload bank or credit card statement for parsing
 *
 * @param {Object} file Statement PDF file needs to be parsed
 */
export const requestUploadStatementFile = file => {
  const requestConfig = {
    url: URL_UPLOAD,
    method: "POST",
    payload: file
  };

  return requestWithAutoTokenRenew(requestConfig);
};

Comment: It is considered a bad practice to mock private function.
You should always mock only the outer layer of your app, usually public API
Answer: The workaround I adopted is not to mock the entire "private" function but only the "impossible" part of the functionality inside the "private" function. In this case, fetching the token from the remote service doGetSession and calling external API using Axios lib request method.
// Mocks
import { request } from "axios";
import { doGetSession } from "../utilities/auth/auth";

// Targets
import { requestUploadStatementFile } from "./api";

jest.mock("../utilities/auth/auth");
jest.mock("axios");

describe("requestUploadStatementFile", () => {
  it("should fire request with correct reqeust configuration object", done => {
    doGetSession.mockImplementationOnce(() => {
      return Promise.resolve({ idToken: { jtwToken: "SAMPLE-TOKEN" } });
    });

    request.mockImplementationOnce(() => {
      return Promise.resolve({ data: [] });
    });

    requestUploadStatementFile({}).then(transactions => {
      const transactionsExpected = [];
      const requestExpectedArgs = {
        data: {},
        headers: { Accept: "application/json", Authorization: undefined, "Content-Type": "application/json" },
        method: "POST",
        url: "https://*.*.amazonaws.com/api/upload"
      };

      expect(transactions).toEqual(transactionsExpected);
      expect(request).toHaveBeenCalledTimes(1);
      expect(request).toHaveBeenCalledWith(requestExpectedArgs);

      done();
    });
  });
});

Thanks for the comment from @felixmosh.

It is considered a bad practice to mock private function. You should always mock only the outer layer of your app, usually public API
Comment: I agree. Similarly, I mocked node-fetch call inside my private function (which function under test was using).