text:
Q: Realtime DB persistence distorts data display in order When I open an app I display a list of groups which have name, creationDate and etc. One of the fields is recentMessage, which value is ID which points to messages collection's message. I get that recent message by:
fun loadRecentMessage(param: (Message) -> Unit) {
    reference.child("/messages/$groupd/messages/$messageid")
        .addValueEventListener(object: ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.value != null) {
                    // If I had a list of ["1", "2", "3", "4", "5"]
                    // 'messageid' will show to message "5"
                    // and param will be invoked with it.
                    (snapshot.getValue(Message::class.java)?.let { param.invoke(it) })
                }
            }

            override fun onCancelled(error: DatabaseError) {
                // Log error
            }
        })
}

Now when I press on group, I navigate to messages fragment and attach childEventListener to messages and display them:
fun loadMsgs(data: MutableLiveData<MutableList<Message>>) {
    reference
        .child("/messages/$groupid/messages/${messageid}")
        .addChildEventListener(object : ChildEventListener {
               override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) {
                   // If I have a list of messages: ["1", "2", "3", "4", "5"]
                   // and I called loadRecentMessage() before, my snapshot values comes in this order:
                   // "5", "1", "2", "3", "4", "5"
                   // If I don't call that method or that method uses get(), my messages
                   // order comes in good order
                   snapshot.getValue(Message::class.java)?.let { data.addAsynchronous(it) }
               }

               override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) {
                   // Empty
               }

               override fun onChildRemoved(snapshot: DataSnapshot) {
                   // Empty
               }

               override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) {
                   // Empty
               }

               override fun onCancelled(error: DatabaseError) {
                   // Log error
               }
           }
        )
}

The problem is, that my recent message, that I have loaded before, shows up first in the list, even though, it's last. When I use get() instead of addValueEventListener() to load recent message everything is fine, but I need to keep that up to date. I think it's because the persistence had my recent message saved, thus it loads it first. How to display my messages in order, even though I have one message loaded before?
UPDATE 1:
// This is where param.invoke(it) comes in work:
database.getRecentMessage(groupid) {
    groupsMutableValue.addAsynchronous(it)
}

// addAsynchronous() method
fun <T> MutableLiveData<MutableList<T>>.addAsynchronous(item: T) {
    val newList = mutableListOf<T>()
    this.value?.let { newList.addAll(it) }
    newList.add(item)
    this.postValue(newList)
}

// message list from DB
"messages" : {
    "-MXSkzXdm2OxV6CC3Xl3" : {
      "messages" : {
        "-MXVeBEq5ksZfPn4BoDB" : {
          "content" : "Hi",
          "from" : "2YnfQSeBladXsD9sPEcKrhxJ6CB2"
        },
        "-MXVeJ5MBOOzl53kEEC1" : {
          "content" : "Hey",
          "from" : "2g87tAMuQSOgu7b1W0uOvKDpg3K2"
        },
        "-MXVeR6vPi7KZ8tC52EP" : {
          "content" : "Hola",
          "from" : "iLOmzFZqzVRtMb5eOC1gRRWY5Ar2"
        },
        "-MXXlQVAhbT6JBJbpIRt" : {
          "content" : "Last message",
          "from" : "2YnfQSeBladXsD9sPEcKrhxJ6CB2"
        }
    }
}


text:
Q: Path name no longer gets updated in tabs of xfce4-terminal once you update $prompt I'm using xfce4-terminal in XFCE and each tab by default shows the user/host/path name of that tab, which is what I want.
However, once I change $prompt (to customize it), this no longer happens.  New tabs now actually come up with the name "Untitled".
Before I made the change, this was the content of $prompt:
echo $prompt
%%[%n@%m %c]%#
But even if I do this, I never get the tab name to get updated again:
set prompt = '%%[%n@%m %c]%#'
In fact, I know something is wrong here because when I set $path to that value, I actually pick up another "%" sign in the front of the prompt that wasn't there before.
Could someone please help me explain this and tell me how to fix it?

A: I'm not sure if I understand the codes you are using, but, assuming you're using Bash, I think maybe you're trying to do something like this:
PS1="\[\e]2;\u@\h: \w\a\]\u@\h: \w \$ "

If you are using Bash, here's info on Bash in general, and the prompt in particular.
Also, the Arch Wiki contains a bit more prompt snacks :-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: iPhone. View architecture Can anyone summarize the relationship between the following items?

*

*Content View

*View Controller

*Nib

*the view, subclass of UIView

*Application delegate

I got very confused about these. Coz some people say the "content view" contains the "nib" while other people say "content view" and "nib" are not containing each other.
Many thanks!

A: Oh man… that's not so easy. But I'll try.

*

*Application is being launched from main().

*Application delegate receives callbacks from Application during runloop. For example, when app finished launching or something else.

*Usually application contains single instance of UIWindow, that is the root of all view hierarchy.

*UIWindow can have UIViews, they can have UIViews by themselves. So, there's a hierarchy of UIViews (a tree)

*Each view has controller, that gets user input and other events and controls UIView (for example, tells it to redraw itself because of user tap). Controller can be standard or custom, written by developer.

*Content View is a normal view. Usually within a table cell. UITableViewCell instance has a property that is called contentView. It's a normal view and it can be any UIView subclass.

NIB is another story. You can create whole view hierarchy by yourself. But there is an alternative way: use Interface Builder. After creating views/subviews in the interface builder — you can save this hierarchy with all its properties as a single (serialized) file. And load it at once during application run.
NIB has three main objects. File Owner is an object, that you'll get when you send some message like
+ (BOOL)loadNibNamed:(NSString *)aNibName owner:(id)owner

Here owner will be filled with all properties of File Owner from the NIB.
First responder - first receives input. You can simply forget about it for now.
View — is the main view. Usually it is linked to a view property of File Owner.
It's a veeery short overview of all these things. You really have to read documentation to understand it better.


text:
Q: Formula Issue when Predicting using LMER I get the following error when I try to predict using lmer
> predict(mm1, newdata = TEST)
Error in terms.formula(formula(x, fixed.only = TRUE)) :
  '.' in formula and no 'data' argument

This is what my formula looks like
> formula(mm1)
log_bid_price ~ . - zip_cbsa_name + (1 | zip_cbsa_name)

I'm able to summarize the model, but I can't pass it to the predict function.
I would like to be able to automatically generate a formula given the columns of the predictor matrix and then pass that to lmer. How would I do that?

A: You might have more success building formula objects like so:
resp <- "log_bid_price"
reserve.coef <- c("zip_cbsa_name")
RHS <- names(data)[-(which(names(data)  %in% c(resp, reserve.coef))]
f <- paste0(paste(resp, paste(RHS, collapse="+"), sep= "~"), " + (1 | zip_cbsa_name)")
mm1 <- lmer(f, data= data)

eg.
paste0(paste("Y", paste(c("a", "b", "c"), collapse= "+"), sep="~"),  "+ (1 | zip_cbsa_name)")
[1] "Y~a+b+c+ (1 | zip_cbsa_name)"

If you wish to do variable selection as you do model selection, you can iterate on this to produce your RHS object


text:
Q: .NET DateTime.Parse When trying to use the parse method on the DateTime class, I get an exception thrown:

String was not recognized as a valid DateTime.

*

*The string reads as "26/10/2009 8:47:39 AM" when outputted.

*This string is obtained from a group on a match from a regex.

*None of the strings obtained from this match group will parse to datetime.

Examples of other strings:

26/10/2009 8:47:39 AM
26/10/2009 8:00:41 AM
26/10/2009 7:48:35 AM

The weird thing is, I am sure it has worked before.

A: You're probably using the wrong culture. The month cannot be 26, so it's not a US timestamp. This works though:
using System;
using System.Globalization;

class Program
{
    static void Main(string[] args)
    {
        DateTime dateTime = DateTime.Parse("26/10/2009 8:47:39 AM",
            CultureInfo.GetCultureInfo("en-GB"));
    }
}

A: Parsing strings into DateTime object is almost always a pain. If you know for certain that they will always have the format as your examples do, this should work:
string input = "26/10/2009 8:00:41 AM";
DateTime dateTime = DateTime.ParseExact(input, "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

A: Has the culure changed on the machine? 26/10/2009 is a good UK date but a bad US date (for instance)

A: Either call DateTime.Parse() with the culture as a parameter or call DateTime.ParseExact() with the date, the exact format of the date to parse, and the culture:
DateTime.ParseExact()

A: Parse takes regional settings (culture of current thread) into account. Therefore, I'd use ParseExact and specify the correct format explicitly with an invariant culture (or the culture you need, eg. en-US, for AM/PM).

A: I second @Lucero, Parse uses current thread's culture info etc. See also the opposite direction: a ToString question in this context.

A: I have to solve some really strange date format coming from other system... In this example is for SPANISH format ...
string input="07/06/2019 07:01:54 p. m.";

public static DateTime ParseSpanishDate(string input)
{
    string normalized = input.Replace("a. m.", "AM").Replace("p. m.", "PM");
    normalized = normalized.Replace("12:00:00 AM", "00:00:00 AM");
    return  DateTime.Parse(normalized, CultureInfo.GetCultureInfo("es"));
}


text:
Q: if statements in buttons c# I'm a brand new n00bie in visual c# and I ran into a weird obstacle that is driving me CRAZY!! Here is the code in question (yes, an Hello World program):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (textBox1.Text.Equals("Goodbye Cruel World"))
            {
                textBox1.Text = ("Hello World!");

            }
            else { textBox1.Text = ("Goodye Cruel World"); }

        }

    }
}

I also tried to use textBox1.Text=="Goodbye Cruel World"; as the evaluation parameter for the if statement getting no errors in the compiler (by the way I am using Visual Studio 2012 Ultimate)
The program runs fine. I initalised the textbox text property as "Hello World!" using the Design GUI of VS. The problem I am facing is that the code works only the first time the user clicks the button. Any time after the button does NOTHING.
I debugged the code and I made sure that the textbox text property is appropriately changed the first time the user clicks the button. When the user clicks the button a second time (or any time after that for that matter) once the code gets to the if statement it skips it, as if the evaluation of the expression within is FALSE. In fact, keeping up with the debug tool, the button keeps executing only the code within the else block, even though I know for a fact that the TextBox.Text property that I am working with has been appropriately changed before.
What am I missing here??? Why doesn't the button just switches the textbox text value between the two strings I hardcoded within?

A: You are using three strings, not two. "Goodye Cruel World" is not equal to "Goodbye Cruel World". Hence, you cannot expect any kind of "string swapping" behaviour whatsoever from this source code.
Lesson to learn: Do not use the same string at different points of your code. Instead, create a constant string variable which has that value, and then use it every time you need it. For example code see Habib's answer.

A: That is a case of defining string constant in your code:
public partial class Form1 : Form
{
    private const string GOODBYE = "Goodbye Cruel World";
    private const string HELLO = "Hello World!";
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (textBox1.Text.Equals(GOODBYE ))
        {
            textBox1.Text = HELLO;

        }
        else { textBox1.Text = (GOODBYE ); }
    }
}

If you are using same string in multiple places then its better if you define it as a const and use that everywhere in your code, this will help you in reducing errors like the one you have now (Goodye is Goodbye) and it is also easier to change/maintain.

A: Check the spelling of Goodye in the else clause. The condition will always be false.


text:
Q: Python - DocxTemplate - Not Printing "&" in final document I am running a script that takes the names from a csv file and populates them into individual word documents from a template. I got that part. But here is where I need a bit of help.
Some cells in the csv file are two names, such as "Bobby & Sammy." When I go check the populated word document, it only has "Bobby Sammy." I know that the "&" is a special character, but I am not sure what I have to do for it to populate the word documents correctly.
Any and all help is appreciated.
Edit: Code
csvfn = "Addresses.csv"
df = pd.read_csv('Addresses.csv')

def mkw(n):
tpl = DocxTemplate('Envelope_Template.docx')
df_to_doct = df.to_dict()
x = df.to_dict(orient='records')
context = x
tpl.render(context[n])
tpl.save("%s.docx" %str(n))
wait = time.sleep(random.randint(1,3))
~
print ("There will be ", df2, "files")
~
for i in range(0, df2):
    print("Making file: ",f"{i}," ,"..Please Wait...")
    mkw(i)

print("Done! - Now check your files")

~ Denotes new cell, I am using JupyterLab
File is a standard csv file
Standard CSV File
Without "&" Prints fine
Empty space where "&" is supposed to be


text:
Q: A bound on number of elements less than $n$ of a $B_2[g]$ sequence Let $S \subset \mathbb{N}$. We say $S$ is of type $B_2(g)$ if the number of representation
of the form $n = s_1 + s_2 \ (s_1 \leq s_2)$ is bounded by $g$ for every $n \in \mathbb{N}$.
Let $S(n)$ be the number of elements of $S$ not exceeding $n$.
Is it reasonable to expect
$S(n) \leq n^{1/2}$? If so, could someone please explain to me why? Thank you.


text:
Q: OpenCV Should I use smart pointers to prevent memory leak i have a OpenCV program for preprocessing and detecting text area for OCR.
For example in this part of program:
    cv::Mat image;
    cv::Mat outImage;
    cv::Mat image_blurred_5x5_kernel;

    cv::resize(image, outImage, cv::Size(), .75, .75);
    cv::GaussianBlur(image, image_blurred_3x3_kernel, cv::Size(3, 3), 0);

The program creates 3 images; original, resized and blurred one. I'm only going to use the last image i acquired. For example after resizing the original image and storing it in some variable, i won't be using original image anymore.
but as you see i created and used objects themselves, i am wondering is using smart pointers would result in better memory control? Or destructors are enough for this and difference between two methods is negligible? Execution time is my priority, rather than space usage.

A: cv::Mat is itself managing its resources, which will be released when the destructor is called. Since you put them on the stack, that will be handled automatically when you go out of scope.
You should use smart pointers if you were not putting the objects on the stack, i.e.
cv::Mat* image_ptr = new cv::Mat; // now you need to handle memory, since the allocated object will not be deleted automatically when changing scope
auto image_smart_pointer = std::make_unique<cv::Mat>(); // allocated object will be deallocated correctly when changing scope, since image_smart_pointer is destructed at change of scope.


text:
Q: Retrofit 404 not found web api I have a web api and an application. So I want to a Register app but I have a problem. I use the azure.
There is my registerapi (interface)
@FormUrlEncoded
@POST("/application/json")
public void insertUser(
        @Field("Username") String Username,
        @Field("Password") String Password,
        @Field("Email") String Email,
        Callback<Response> callback);

and my mainactivty.java page
public class MainActivity extends AppCompatActivity {

private EditText editTextUsername;
private EditText editTextPassword;
private EditText editTextEmail;
private Button buttonRegister;
final public static String ROOT_URL = "http://bsapmusic.azurewebsites.net/api/music/register";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editTextUsername = (EditText) findViewById(R.id.etusername);
    editTextPassword = (EditText) findViewById(R.id.etpassword);
    editTextEmail = (EditText) findViewById(R.id.etmail);
    buttonRegister = (Button) findViewById(R.id.btnkayit);
    buttonRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            insertUser();
        }
    });
}
private void insertUser()
{
    RestAdapter adapter =new RestAdapter.Builder().setEndpoint(ROOT_URL).build();
    RegisterAPI api = adapter.create(RegisterAPI.class);
    api.insertUser(
            editTextUsername.getText().toString(),
            editTextPassword.getText().toString(),
            editTextEmail.getText().toString(),
            new Callback<Response>() {
                @Override
                public void success(Response result, Response response) {
                    BufferedReader reader = null;
                    String output = "";
                    try{
                        reader=new BufferedReader(new InputStreamReader(result.getBody().in()));
                        output=reader.readLine();
                    }
                    catch (IOException e){
                        e.printStackTrace();
                    }
                    Toast.makeText(MainActivity.this,output,Toast.LENGTH_LONG).show();
                }

                @Override
                public void failure(RetrofitError error) {
                    Toast.makeText(MainActivity.this, error.toString(),Toast.LENGTH_LONG).show();
                }
            });
};

and I get retrofit 404 not found.

A: Assuming http://bsapmusic.azurewebsites.net/api/music/register is the url to your register method in your API:
A 404 means there is no API for this url.
Your baseurl is http://bsapmusic.azurewebsites.net/api/music/register
After this baseurl the path inside the @post is appended. This will result in the url: http://bsapmusic.azurewebsites.net/api/music/register/application/json.
The url to your register method is probably the first url.
The baseurl should the url to the root url of your api, in your case this probably is: http://bsapmusic.azurewebsites.net/api/. In the @GET, @POST, @PUT you set the path to a specific api method. In your case that would be @POST("music/register"). You don't set the type of data that is sent to the API in here.


text:
Q: file_get_contents throws 400 Bad Request error PHP I'm just using a file_get_contents() to get the latest tweets from a user like this:
$tweet = json_decode(file_get_contents('http://api.twitter.com/1/statuses/user_timeline/User.json'));

This works fine on my localhost but when I upload it to my server it throws this error:

Warning: file_get_contents(http://api.twitter.com/1/statuses/user_timeline/User.json) [function.file-get-contents]:failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request...

Not sure what might be causing it, maybe a php configuration I need to set on my server?
Thanks in advance!

A: You can use file_get_contents adding the ignore_errors option set to true, in this way you will get the entire body of the response in case of error (HTTP/1.1 400, for example) and not only a simple false.
You can see an example here: https://stackoverflow.com/a/11479968/3926617
If you want access to response's headers, you can use $http_response_header after the request.
http://php.net/manual/en/reserved.variables.httpresponseheader.php

A: You might want to try using curl to retrieve the data instead of file_get_contents. curl has better support for error handling:
// make request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.twitter.com/1/statuses/user_timeline/User.json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);

// convert response
$output = json_decode($output);

// handle error; error output
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {

  var_dump($output);
}

curl_close($ch);

This may give you a better idea why you're receiving the error. A common error is hitting the rate limit on your server.

A: Just a little addendum on Ben's answer.
According to the PHP manual the CURLOPT_URL option may be set when inizializing the cURL handle with curl_init().
// make request
$ch = curl_init("http://api.twitter.com/1/statuses/user_timeline/User.json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);

// convert response
$output = json_decode($output);

// handle error; error output
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {

  var_dump($output);
}

curl_close($ch);


text:
Q: Detecting if Browser supports canplaythrough I've got an issue at the moment, that some browsers do not seem to be playing a video when I wrap the play method inside an eventListener for the "canplaythrough" event.
My Code is
document.getElementById('introVideo').addEventListener("canplaythrough", playVideo, false);

function playVideo(){
    document.getElementById('introVideo').play();
    document.getElementById('introVideo').removeEventListener("canplaythrough", playVideo, false);
}

However for some reason, Firefox occasionally doesn't play the video and other browsers "sometimes" don't play either, it just sits on the first frame.


text:
Q: How To Store Multiple Words As An ArrayList Value  public void addItem() {
        System.out.println("Please type the item to add to the To-Do List");
        System.out.println();
        String newItem = inputread.next();
        toDoList.add(newItem);
        System.out.println("Your item has been added! Type any key and press Enter to continue");
        String discardMe = inputread.next();
        menu();
    }

This is my code, I'm just learning Java and trying to made a little "To-Do List" type program. As it stands, I can only add one word at a time. If, for example, I type "Pick Up Milk", the arrayList only stores "Pick".
I tried using inputread.nextLine() above, but then I get an "InputMismatchException". Any advice? I'm sure it's something simple.
Edited to include the whole class, per request:
public class ToDo {
    Scanner inputread = new Scanner(System.in);
    ArrayList<String> toDoList = new ArrayList<String>();

    public void menu() {
        clearConsole();
        System.out.println("Welcome to the To-Do program.");
        System.out.println();
        System.out.println();
        System.out.println("Please select an option from the following menu, using the number.:");
        System.out.println("1- View To-Do List");
        System.out.println("2- Add Item To List");
        System.out.println("3- Remove Item From List");
        int userinput = inputread.nextInt();

        switch (userinput) {
            case 1:
                clearConsole();
                displayList();
                System.out.println();
                System.out.println("This is your list. Type any key and press Enter to continue");
                String discardMe = inputread.next();
                menu();
                break;
            case 2:
                clearConsole();
                addItem();
                break;
            case 3:
                clearConsole();
                deleteItem();
                break;

        }
    }

    public void clearConsole() {
        for (int i = 0; i < 25; i++) {
            System.out.println();
        }
    }

    public void addItem() {
        System.out.println("Please type the item to add to the To-Do List");
        System.out.println();
        String newItem = inputread.nextLine();
        toDoList.add(newItem);
        System.out.println("Your item has been added! Type any key and press Enter to continue");
        String discardMe = inputread.next();
        menu();
    }

    public void displayList() {
        if (toDoList.isEmpty()) {
            System.out.println("For [REDACTED]'s sake, add an activity.");
        } else {
            for (String listItem: toDoList) {
                System.out.println(listItem);
            }
        }

    }

    public void deleteItem() {
        System.out.println("Please choose the number of the line you want to delete:");
        displayList();
        int userinput = inputread.nextInt();
        int listPos = userinput - 1;
        toDoList.remove(listPos);
        System.out.println("That item has been deleted. Type any key and press Enter to continue.");
        String discardMe = inputread.next();
        menu();
    }
}

A: I would suggest using a BufferedReader instead of the Scanner class. The problem with a Scanner is that it looks for tokens between white spaces and new lines, so when you add something like Go to the store, each token between the white spaces will get picked up, and you will end up with go to the store, rather than 1 large token. You can get input using the BufferedReader by declaring it using:
public static BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));

Then, in your addItem() method, in a while(true) loop, you read the input from the reader, then check if it is empty or not. IF it is empty, then you break the loop and exit the function, otherwise add an item to your list.
    System.out.println("Please type the item to add to the To-Do List"); // Output
    while (true) { // Continue adding items until user just hits enter
        String newItem = buf.readLine(); // read user input
        if (newItem == null || newItem.isEmpty()) { // check if the user entered anything, or just hit enter
            break; // If they didn't enter anything, then break the loop and drop out of the function
        }
        toDoList.add(newItem); // if they did enter something, add it to your to-do list

    }

For example, to test this I used a main method:
public static BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[] args) throws IOException {
    List<String> toDoList = new ArrayList<String>();
    System.out.println("Please type the item to add to the To-Do List");
    while (true) {
        String newItem = buf.readLine();
        if (newItem == null || newItem.isEmpty()) {
            break;
        }
        toDoList.add(newItem);

    }
    System.out.println("Your item has been added! Type any key and press Enter to continue");

    for (String s : toDoList) {
        System.out.println(s);
    }
}

Then, when prompted for input I entered:
Please type the item to add to the To-Do List
Go to the grocery store and get milk
Stop by the gym and pay membership fees
Pick up flowers for the wife

And for output I got:
Your item has been added! Type any key and press Enter to continue
Go to the grocery store and get milk
Stop by the gym and pay membership fees
Pick up flowers for the wife

A: You have several problems in this code.
Let's first address your input issues.
In the menu, you read a number. When you use scanner.next(), scanner.nextInt() etc., it reads the following item up to - but not including - any white space or newline. So the white space or newline remain in the buffer waiting to be read.
Now, when you go to the addItem() and use nextLine(), it reads just that whitespace or newline. If it was just a newline (a Return you pressed), then you get an empty string, and you probably don't want to add that to the list. If you use next() it will skip that newline but... it will read just one word.
So you need to have a nextLine() after your nextInt() in the menu. After you read your integer, you'll clear the buffer up to and including the newline.
Then, inside the addItem() method, you'll be able to use nextLine() again, because it will now start on a fresh new line - and it will read the next line in its entirety.
Also, the discardMe part has to be with nextLine(), not with next(), otherwise it will not clear the end-of-line for the next operation.

Your other problem is something you didn't ask about. What you currently do is basically go into the menu, then go into an operation, then go into the menu, then an operation. You keep calling more and more functions, and you never return, or rather, you return from all when you display the list.
In time, this may cause a stack overflow.
The proper way to do this is not to call menu() from inside the operational methods, but rather, to have a loop in the menu() method, which shows the menu, calls the appropriate operational method, and when it returns (clears its space on the stack), loops back to the menu and so on. This keeps your stack nice and flat.
And of course, you should have a "Quit" option on your menu.

A: an example for Stultuskes idea:
    public void addItem() {
        System.out.println("Please type the item to add to the To-Do List");
        System.out.println();
        try (Scanner in = new Scanner(System.in)) {
            while (in.hasNext()) {
                String newItem = in.next();
                toDoList.add(newItem);
                System.out
                    .println("Your item has been added! Type any key and press Enter to continue");
            }
        }
        System.out.println(toDoList);
}

A: public void addItem() {
    System.out.println("Please type the item to add to the To-Do List");
    //The skip gets over the leftover newline character
    inputread.skip("\n");
    String newItem = inputread.nextLine();
    toDoList.add(newItem);
    System.out.println("Your item has been added! Type any key and press Enter to continue");
    String discardMe = inputread.next();
    menu();
}

Putting in the skip fixed it for me. I want to thank you guys for your answers.


text:
Q: Complicated plots faceting I have a data like this
structure(list(Chr_id = c("1A", "1A", "1A", "1A", "1A", "1A",
"1A", "1A", "1A", "1A", "1A", "1A", "1A", "1A", "1A", "1A", "1A",
"1A", "1A", "1A", "1A", "1A", "1A", "1A", "1A", "1A", "1A", "1A",
"1A", "1A", "1B", "1B", "1B", "1B", "1B", "1B", "1B", "1B", "1B",
"1B", "1B", "1B", "1B", "1B", "1B", "1B", "1B", "1B", "1B", "1B",
"1B", "1B", "1B", "1B", "1B", "1B", "1B", "1B", "1B", "1B", "1D",
"1D", "1D", "1D", "1D", "1D", "1D", "1D", "1D", "1D", "1D", "1D",
"1D", "1D", "1D", "1D", "1D", "1D", "1D", "1D", "1D", "1D", "1D",
"1D", "1D", "1D", "1D", "1D", "1D", "1D"), Start = c(111381744,
312370649, 106700529, 577069227, 13903751, 484952182, 546871249,
549719683, 560876463, 343004004, 301369910, 295169503, 82127411,
7487575, 531277958, 499574273, 508318998, 112534618, 135111292,
71379690, 301371731, 62654363, 474295484, 462885209, 90752869,
37060118, 516181841, 586104884, 508318998, 513528750, 1205670212,
1259468661, 633852277, 594372162, 1183474873, 843578162, 1017681165,
699258349, 1073242080, 1279167768, 880972535, 867779030, 1155145280,
608978435, 1044603066, 1023765196, 751735249, 1164927036, 614786148,
897594687, 1113070984, 1184408414, 894457006, 1103476280, 606094615,
1175159133, 1166717363, 691495384, 1155547991, 602113219, 1309902292,
1367857833, 1652686374, 1367857833, 1300204987, 1290581423, 1357433559,
1751459106, 1748871019, 1592296298, 1361382337, 1388111038, 1695238483,
1535545547, 1761828229, 1697034092, 1360290688, 1319668145, 1495335256,
1687491614, 1400339618, 1645319622, 1503836513, 1537716335, 1743422939,
1404043162, 1743422939, 1489337730, 1693017288, 1293616598),
BAF = c(0.989473684210526, 0.953125, 0.989583333333333, 0,
0.265625, 0.979166666666667, 0.984375, 0.182291666666667,
0.00520833333333333, 0.958333333333333, 0.958333333333333,
1, 0.00520833333333333, 0.807291666666667, 1, 0.239583333333333,
0.953125, 0.994791666666667, 0, 0, 0.369791666666667, 0.00520833333333333,
0.21875, 0.936842105263158, 0, 0, 1, 0.333333333333333, 0.953125,
0.989583333333333, 0.932291666666667, 0.215789473684211,
0.552083333333333, 0.880208333333333, 0.572916666666667,
0.994736842105263, 0.947916666666667, 0, 0.9375, 1, 1, 0.604166666666667,
0.25, 0.505208333333333, 0.00520833333333333, 0.942708333333333,
0.989583333333333, 0, 0.221052631578947, 0.729166666666667,
0.947916666666667, 0, 0.421875, 0.848958333333333, 0.905263157894737,
0.859375, 0.3, 0, 1, 0.0677083333333333, 1, 0, 0.0157894736842105,
0, 0.226315789473684, 0.854166666666667, 0.00526315789473684,
0.384210526315789, 1, 0.927083333333333, 0.994791666666667,
0.0105263157894737, 0.625, 0.0104166666666667, 0, 0.34375,
0, 0.00520833333333333, 0.729166666666667, 0.994736842105263,
0.994791666666667, 0, 0.00520833333333333, 0.0520833333333333,
0.0989583333333333, 0.0364583333333333, 0.0989583333333333,
0.661458333333333, 0.145833333333333, 0.0210526315789474),
log_ratio = c(-1.785, -2.286, -2.218, 2.715, 2.189, -1.671,
-1.541, 3.209, 1.528, -1.836, -1.516, -1.501, 2.051, -1.082,
-0.648, 1.326, 1.114, -1.137, 0.655, 1.895, -2.928, 0.306,
0.028, -2.574, 1.532, 3.061, -0.482, 1.142, -0.673, -2.15,
-1.268, 2.613, -1.607, -2.225, -1.82, -1.386, -0.157, 1.054,
-1.055, -1.332, -0.971, -2.503, 1.965, 0.928, 2.926, -1.94,
-2.144, 1.876, 0.87, 0.171, -2.682, 1.073, 1.758, 0.499,
-1.241, -0.788, 0.342, 2.076, -0.98, 2.599, -1.413, 0.813,
1.095, 0.822, 2.381, -2.431, 2.814, 0.646, -1.328, -2.616,
-1.27, 0.481, -1.208, 1.588, 2.067, 0.514, 0.747, 0.312,
0.04, -2.497, -2.291, 2.014, 0.177, 1.6, 0.986, 1.49, 1.613,
-0.354, -1.739, 0.801)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -90L))

And I use this code
ggplot(data_sample, aes(x = Start)) +
    geom_point(aes(y = BAF),
               color = 'blue') +
    geom_point(aes(y = log_ratio),
               color = 'red') +
    theme_minimal(base_size = 20) +
    facet_wrap(~ Chr_id,
               ncol = 1,
               nrow = 3,
               scales = 'free') +
    theme(axis.title.x = element_blank(),
          axis.text.x = element_blank(),
          legend.position = 'none')

to create plot like this one

Red points have very different scale from blue ones and I tried to create a pairs of plots for each group by Chr_id (1A, 1B, 1D) values and to move geom_point contains red points on the plot below the plot with blue points. I have no idea is there even possible because I already use facet_wrap and I need to make like subgrid for every Chr_id plot produced by facet_wrap. I think it is possible using grid.arrange function but in real data Chr_id contains 17 categories and code will be too bulky. Is there more elegant solution for this? Thanks.
Update 1
I want to do plot like this

I did this using grid.arange and code is too big as I mentioned before. Also x-axis for pairs of subplots is not synchronized.

A: If you make a list with all your plots, you can use do.call to call grid.arrange on the whole list. It's easiest to make a list of plots if we write a little function to produce 1 plot. I changed your base_size to 10 to make the image fit better on Stack Overflow--you can of course change it back and customize the one_plot function however you'd like.
library(dplyr)
library(tidyr)
long_data = data_sample %>%
  pivot_longer(cols = c("BAF", "log_ratio")) %>%
  mutate(grouper = paste(Chr_id, name, sep = ":"))

one_plot = function(chr, data) {
  ggplot(filter(long_data, Chr_id == chr), aes(x = Start, color = name, y = value)) +
      geom_point() +
      theme_minimal(base_size = 20) +
      facet_grid(rows = vars(name),
                 cols = vars(Chr_id),
                 scales = 'free') +
      theme(axis.title.x = element_blank(),
            axis.text.x = element_blank(),
            legend.position = 'none')
}

plot_list = lapply(unique(long_data$Chr_id), one_plot, data = long_data)
do.call(grid.arrange, c(plot_list, ncol = 1))


text:
Q: Tkinter Image Updating Image + lambda Error As of late I have been basically self-teaching myself Tkinter. I've been working on this project for about a week now and I feel like it's coming along rather nicely. Today while I was working on it I got this code, which when ran successfully sets up the GUI. However, when I try to change the image via the Combobox, it fails and gives me the following error:
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
TypeError: <lambda>() takes 0 positional arguments but 1 was given

After a quick search I found that using lambda x: would fix this error. After making this change, the GUI initiates as normal, however the images will still not change, in fact, the second panel glitches out and removes the image if an item is selected from the first Combobox. Complete removal of 'lambda' causes the panels to not be initiated at all. Basically, I would like to know what is causing these glitches and how to get my images to update.
from tkinter import *
from tkinter.ttk import *
from PIL import Image, ImageTk
import os

class App(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        parent.title('Vainglory DMG Calculator | BETA')
        self.dyn_panel = []
        self.dyn_combobox = []
        self.dyn_image_path = ['', '']
        self.dyn_img = ['', '']
        self.cwd = os.getcwd()
        self.hero_list = ('Adagio', 'Alpha', 'Ardan', 'Baptiste', 'Baron', 'Blackfeather', \
                          'Catherine', 'Celeste', 'Churnwalker', 'Flicker', 'Fortress', \
                          'Glaive', 'Grace', 'Grumpjaw', 'Gwen', 'Idris', 'Joule', \
                          'Kestrel', 'Koshka', 'Krul', 'Lance', 'Lorelai', 'Lyra', 'Ozo', \
                          'Petal', 'Phinn', 'Reim', 'Reza', 'Ringo', 'Rona', 'Samuel', \
                          'SAW', 'Skaarf', 'Skye', 'Taka', 'Varya', 'Vox')
        for i in range(2):
            self.create_hero_combo_box(parent, i)
            self.set_image(i)
            self.create_hero_panel(parent, self.dyn_img[i], i)

    def create_hero_panel(self, window, img, index):
        self.dyn_panel.append(Label(window, image=img))
        self.dyn_panel[index].grid(row=0, column=index*2)

    def create_hero_combo_box(self, window, index):
        self.dyn_combobox.append(Combobox(window, values=(*self.hero_list,)))
        self.dyn_combobox[index].grid(row=1, column=index*2)
        self.dyn_combobox[index].set(self.hero_list[0])

    def set_image(self, index):
        self.dyn_image_path[index] = (self.cwd + '/img/heroes/' + self.dyn_combobox[index].get().lower() + '.png')
        self.dyn_img[index] = ImageTk.PhotoImage(Image.open(self.dyn_image_path[index]))

    def update(self, index):
        self.dyn_panel[index].configure(image=self.set_image(index))

if __name__ == '__main__':
    root = Tk()
    app = App(root)
    for i in range(2):
        app.dyn_combobox[i].bind('<<ComboboxSelected>>', lambda x: app.update(i))
    root.mainloop()

A: Every widget has method update() but you create update() in App(Frame) so you replace it - and it can makes problem. Use different name than update()


text:
Q: LINQPad, using multiple datacontexts I am often comparing data in tables in different databases.  These databases do not have the same schema.  In TSQL, I can reference them with the  DB>user>table structure (DB1.dbo.Stores, DB2.dbo.OtherPlaces) to pull the data for comparison.  I like the idea of LINQPad quite a bit, but I just can't seem to easily pull data from two different data contexts within the same set of statements.
I've seen people suggest simply changing the connection string to pull the data from the other source into the current schema but, as I mentioned, this will not do.  Did I just skip a page in the FAQ?  This seems a fairly routine procedure to be unavailable to me.
In the "easy" world, I'd love to be able to simply reference the typed datacontext that LINQPad creates.  Then I could simply:
DB1DataContext db1 = new DB1DataContext();

DB2DataContext db2 = new DB2DataContext();

And work from there.

A: Keep in mind that you can always create another context on your own.
public FooEntities GetFooContext()
{
   var entityBuilder = new EntityConnectionStringBuilder
               {
                    Provider = "Devart.Data.Oracle",
                    ProviderConnectionString = "User Id=foo;Password=foo;Data Source=Foo.World;Connect Mode=Default;Direct=false",
                    Metadata = @"D:\FooModel.csdl|D:\FooModel.ssdl|D:\FooModel.msl"
                };

    return new FooEntities(entityBuilder.ToString());
}

A: Update: it's now possible to do cross-database SQL Server queries in LINQPad (from LINQPad v4.31, with a LINQPad Premium license). To use this feature, hold down the Control key while dragging databases from the Schema Explorer to the query window.
It's also possible to query linked servers (that you've linked by calling sp_add_linkedserver). To do this:

*

*Add a new LINQ to SQL connection.

*Choose Specify New or Existing Database and choose the primary database you want to query.

*Click the Include Additional Databases checkbox and pick the linked server(s) from the list.

A: You can instantiate as many contexts as you like to disparate SQL instances and execute pseudo cross database joins, copy data, etc.  Note, joins across contexts are performed locally so you must call ToList(), ToArray(), etc to execute the queries using their respective data sources individually before joining.  In other words if you "inner" join 10 rows from DB1.TABLE1 with 20 rows from DB2.TABLE2, both sets (all 30 rows) must be pulled into memory on your local machine before Linq performs the join and returns the related/intersecting set (20 rows max per example).
//EF6 context not selected in Linqpad Connection dropdown
var remoteContext = new YourContext();
remoteContext.Database.Connection.ConnectionString = "Server=[SERVER];Database="
+ "[DATABASE];Trusted_Connection=false;User ID=[SQLAUTHUSERID];Password="
+ "[SQLAUTHPASSWORD];Encrypt=True;";
remoteContext.Database.Connection.Open();
var DB1 = new Repository(remoteContext);

//EF6 connection to remote database
var remote = DB1.GetAll<Table1>()
    .Where(x=>x.Id==123)
    //note...depending on the default Linqpad connection you may get
    //"EntityWrapperWithoutRelationships" results for
    //results that include a complex type.  you can use a Select() projection
    //to specify only simple type columns
    .Select(x=>new { x.Col1, x.Col1, etc... })
    .Take(1)
    .ToList().Dump();  // you must execute query by calling ToList(), ToArray(),
              // etc before joining

//Linq-to-SQL default connection selected in Linqpad Connection dropdown
Table2.Where(x=>x.Id = 123)
    .ToList() // you must execute query by calling ToList(), ToArray(),
              // etc before joining
    .Join(remote, a=> a.d, b=> (short?)b.Id, (a,b)=>new{b.Col1, b.Col2, a.Col1})
    .Dump();

remoteContext.Database.Connection.Close();
remoteContext = null;

A: I do not think you are able to do this. See this LinqPad request.
However, you could build multiple dbml files in a separate dll and reference them in LinqPad.

A: Drag-and-drop approach: hold down the Ctrl key while dragging additional databases
from the Schema Explorer to the query editor.
Use case:
//Access Northwind

var ID = new Guid("107cc232-0319-4cbe-b137-184c82ac6e12");

LotsOfData.Where(d => d.Id == ID).Dump();

//Access Northwind_v2

this.NORTHWIND_V2.LotsOfData.Where(d => d.Id == ID).Dump();

A: Multiple databases are as far as I know only available in the "paid" version of LinqPad (what I wrote applies to LinqPad 6 Premium).
For more details, see this answer in StackOverflow (section "Multiple database support").


text:
Q: NuxtJS - how to disable route load/render? NuxtJS is rendering/loading the page every time. I want to have the page content just hidden or shown. not to reload it each time. i looked in the documentation but i can't find anything regarding this.
How can i do it?


text:
Q: Saving sensor data from IBM Bluemix quickstart into Cloudant NoSQL DB I am using IBM Bluemix quickstart in order to display sensor data from Node-red and I am able to see the sensor data coming in real time in Bluemix. However, I would like to save this in Cloudant NoSQL. How can I do this, link the quickstart data to be saved in Cloudant NoSQL DB?
Any help is much appreciated!


text:
Q: Text difference patch Am trying to write a piece of code which will allows the user to type text into a textbox which then gets saved on the server. When the user types some more text in the textbox, I want only the difference to be sent to the server.
Is there a difference algorithm for JS which I can use to send only information about the difference. So it should be able to tell the difference between two text boxes essentially.
It could also be language agnostic and I can port it.
Thank you for your time.
UPDATE
In simple words. I have a text area which keeps saving the text in the box every X seconds. Now to save bandwidth I only want it to send the difference from the last saved revision (which I can say put in a variable. Initially this will be empty). Now the JS has to check the difference between the last revision and the current state of the textbox and generate a change list to send to the server.
UPDATE 2
Something like www.etherpad.com

A: Google DiffMatchPatch has a Javascript implementation, I've used it with much success.
http://code.google.com/p/google-diff-match-patch/

A: The Python difflib module does this and more. It's very flexible but might be challenging to port to Javascript.
Regarding your update, I'm first wondering why you need to worry about bandwidth. Unless your users are typing a lot of text into an edit box (which has its own usability issues) then there just aren't that many bytes to send. Send the whole text box each time you autosave. Users can't type fast enough to really notice the use of bandwidth.
Or, you could meet halfway. Every time you autosave, check to see whether the user has only added new text to the end compared to the last time. If so, send an "append" type update with just the new text. If the user has gone back and edited anything else, then send a "replace" type update where you send the whole text. This takes care of the common append-only case without severely complicating your implementation.

A: Depends on how far you are ready to go.
You would like to check deltav algorithm, it is used by svn in particular: http://svn.apache.org/repos/asf/subversion/trunk/notes/svndiff

A: Instead of calculating a diff between 2 texts, which is difficult,
you could always, while people are editting, record the keystrokes and the caret position in the textbox. If you send this over every now and then (and clean the buffer), the server can playback the exact same sequence.

A: This code-smells of premature optimization.  Perhaps you should implement your solution first and then see about optimizing your transfer rates using diffs.  How much text are you looking at?  Because the request and response packets are going to be more or less the same size with only a few bytes difference for your message, so the savings could be very minimal.
At the very least, complete your solution without optimization and profile your network traffic using tools like Firebug and then test to see how much worse the performance is with what you would consider to be the maximum text block that could be sent.
Finally, you could always use the TypeWatch JQuery plugin to listen for change events in the textbox.  You can set a delay so that once the user finishes typing and the delay elapses, the callback function is triggered.  This means that the text will only be sent when the user types something, and only when they are finished typing.  This will be significantly more efficient than repeatedly polling the server.


text:
Q: How to call multiple services via a single service in Talend? I am new to Talend ESB. I have a ReST service A which creates a record in Table A. There is also a SOAP Service called B which creates a record in table B. I need to create a ReST service which can call both service A and service B so there is a single ESB layer to access both the services. How can I achieve that?

A: You can create a REST Service through the 'job' interface, as you would normally do to create a job. Make sure to use tRESTRequest as your input.
Inside your REST Service, you can make calls to existing SOAP / REST service through the dedicated components : tESBConsumer & tRESTClient.


text:
Q: How to reach $k\cdot 2^{k+2}$ from $(2k)\cdot 2^{k+1}$? I was trying to figure out the step between these two equal expression:
$$(2k)\cdot 2^{k+1} = k\cdot 2^{k+2}$$

A: HINT A number raised to an exponent tells you how many times to multiply that number by itself.
For example: $2^{k}=2*2*...*2$ k-times, so $2*2^{k}=2*(2*2*...*2)$ a total of $k+1$ times so $2*2^{k}=2^{k+1}$


text:
Q: Write to clipboard with custom mime type in node js Is it possible to set the cipboard using a cusom mime type with NodeJS?
I trying to set some text in the clipboard with a mime type of "dyn.ah62d4rv4gk8zuxnxnq" so it can be pasted onto another application.
I'm on mac - so if someone has an Applescript/osascript solution that'll work too :)


text:
Q: How to make 2 password fields match with PHP form validation? Could someone please help me. I am a beginner and I am trying to make two password fields match with PHP functions. Help? Code below...
function validateMemberPasswordRepeat($memberPasswordRepeat){
                if(preg_match("$memberPasswordRepeat === $memberPassword", $memberPasswordRepeat)){
                      return true;
                   }else{
                       return false;
                 }
            }

A: You need to provide both passwords to the function and no need of preg_match a regular comparison will work
function validateMemberPasswordRepeat($memberPasswordRepeat,$memberPassword) {
    if($memberPasswordRepeat === $memberPassword)
        {
          return true;
        }
        else
        {
          return false;
        }
}

A: use Javascript onclick event

<form action=".." method="..">
   <input type="password" name="pass1"/>

   <input type="password" name="pass2"/>

    <input type="submit" onclick="return validatePasswords();"/>
</form>


text:
Q: Identify science fiction retelling of "My Fair Lady" I am looking for a book that was written most likely in 1980s-1990s, that is almost a science fiction retelling of My Fair Lady.
The book was about a professor that rescues a girl from a back planet and brings her to Earth, then gives her an education so she can go to university. In the beginning of the book the girl has a heavy accent but it fades as she is educated and she goes off as a scientist to visit other worlds.

A: You may be thinking of Pauline Ashwell's 1992 collection/fix-up novel Unwillingly to Earth, described as follows on her Wikipedia page:

Unwillingly to Earth (1993), a fix-up of four previously published stories detailing the space adventures of the young Lysistrata (aka "Lizzie") Lee, including

*["Unwillingly to School"](https://www.isfdb.org/cgi-bin/title.cgi?55651) ([*Astounding Science Fiction*, January 1958](https://www.isfdb.org/cgi-bin/pl.cgi?57500+c)), set on the rough mining planet where Lizzie was born and from which she was sent against her will to university on Earth. [Available at the [Internet Archive](https://archive.org/stream/Astounding_v60n05_1958-01_dtsg0318#page/n7/mode/2up).]

*["Rats in the Moon"](https://www.isfdb.org/cgi-bin/title.cgi?49439) ([*Analog Science Fiction/Science Fact*, November 1982](https://www.isfdb.org/cgi-bin/pl.cgi?57196+c)), where Lizzie exposes plots of interplanetary political corruption on Earth's Moon.

*["Fatal Statistics"](https://www.isfdb.org/cgi-bin/title.cgi?48690) ([*Analog Science Fiction/Science Fact*, July 1988](https://www.isfdb.org/cgi-bin/pl.cgi?56913+c)), where Lizzie negotiates between hostile factions on the planet Figueroa, whose civilization collapsed, and helps survivors make a new start.

*["The Lost Kafoozalum"](https://www.isfdb.org/cgi-bin/title.cgi?55544) ([*Analog Science Fact -> Fiction*, October 1960](https://www.isfdb.org/cgi-bin/pl.cgi?56733+c)), where Lizzie takes part in a daring plot to avert nuclear war on the planet Incognita, and when things go terribly wrong she sets them right, saves the life of her professor and eventually marries him. [Available at [Project Gutenberg](http://www.gutenberg.org/ebooks/30427).]
I've only read the first story, "Unwillingly to School", which was the answer to this question. The professor is Dr. D. J. M'Clare, Professor of Cultural Engineering at the Russett Interplanetary College of Humanities, on Earth; he finds Liz on her rough mining planet and takes her back to Earth to study at his school. As Liz tells it:

Where I grew up is Excenus 23, how I got hauled off it is due to a string of catastrophes but the name of the biggest is D. J. M'Clare.
Excenus sun is what they call a swarmer, ninety-seven small planets in close orbits plus odd chunks too many to count. Twenty-three is the biggest, gravitation one point oh seven Earth diameter is a fraction less, if you ever heard of the place it was because they mine areopagite there. Ninety-four percent production for sale in the known volume of space comes from mines on Twenty-three; but for that, no reason to live there at all.
My Dad started as a miner and made his pile, then he took up farming and spent the lot, he has it all back again now.

Liz doesn't want to go but her Dad convinces her:`

[. . .] and he says Going to send you to College, girl.
I say What!
Dad says Liz, Excenus is no place for a young girl all her life. Time you seen some other worlds and I cannot leave the farm and got no one to have an eye to you, now M'Clare says he will get you into this College and that is just what I need.
I say But—!
Dad says They got schools on Earth for kids like you, been on an outback planet or education restricted other ways, they are called Prelim Schools; well you got the Rudiments already; M'Clare says after three months Prelim you should be fit to get into Russett College of Humanities, he will act as your official guardian while on Earth. Do not argue with me Liz!

As first-person narrator Liz does not talk about her own accent (in the parts I've read) but no doubt she has an outplanet accent:

Each person says a name and the monitor repeats it to the kind of box he carries and this lights up with figures on it. I wonder why the box needs a human along and then I remember, one hundred twenty-four different planets and accents to match. I guess this is one point where Man can be a real help to Machine.


text:
Q: write a programme that reads 10 letter, After the letters have been read,Display the one that comes earliest in the alphabet how to write a programme that reads 5 letter, After the letters have been read,Display the one that comes earliest in the alphabet.

A: this should work in every language and it's maybe a good starting point.
write a loop, which reads 5 times a Character
store the Characters in a array
look at the integer value of this character (just google convert char to integer) and look at the ascii table
then you have found your solution


text:
Q: How to make the floor completely white and with shadows Please help me make the floor completely white and with shadows, as in the drawing. I tried different materials, emissive color, turn on and off the map of the scene environment and light sources, still my plane is gray, not white.
Example image


text:
Q: About META Tags: Can not Find Them in Page Source! I encountered many sites including stackoverflow.com whose page source do not show META tags like keywords, description.
I am just wandering is it because they blocked it by some sort of tech or they just drop them since, as I know, those tags are not so much valuable as before.
If they blacked them, then what kind of software or tech do they need. If not then how Google extract description from those sites when Google displays search results?
Lot of dumb questions, thanks for your time and reply!
Any input is appreciated!

A: They're not MATA tags, they're META tags. They are not as important as the actual content of your site and the other sites that link to yours, since it's well known that meta tag content is easier to abuse and misrepresent. Meta elements are more useful in the areas where there is no benefit from such abuse, eg. content encoding or language, but some of this data can be sent by the web server in the HTTP headers anyway. So you rarely, if ever, need any meta elements.
You don't need any sort of technology to 'block' meta tags. Every tag is just a bit of text you insert into your HTML. If you don't want to send out a meta tag, you just don't write it into the HTML.
If you want specific information on how Google views your site then you could start with their webmasters page.

A: Just had a look around on Google .. may be followings help you something.
Avoid the META keyword tag!

Do not use the meta keywords tag. Many
  people still think of this as a quick
  fix for SEO. It's not. Google no
  longer uses it. In fact, it is likely
  that Google penalizes sites that do
  employ the meta keywords tag. Yahoo is
  perhaps the only search engine that
  still uses the meta keywords tag but
  places very little weight on it.

Death of META Tag
pretty old link though

"In the past we have indexed the meta
  keywords tag but have found that the
  high incidence of keyword repetition
  and spam made it an unreliable
  indication of site content and
  quality. We do continue to look at
  this issue, and may re-include them if
  the perceived quality improves over
  time," said Jon Glick, AltaVista's
  director of internet search.


text:
Q: Probability of Convergence of Stochastic Process to $1$ We define the stochastic process $(X_n)_{n \geq 0}$ with $X_0 = x \in [0, 1]$, and:
\begin{align*}
X_{n+1} =
\begin{cases}
X_n^2, &\text{ with probability $\frac{1}{2}$} \\
2X_n - X_n^2, &\text{ with probability $\frac{1}{2}$}
\end{cases}
\end{align*}
I want to show that $\mathrm{P}[\lim_{n \to \infty} X_n = 1] = x$. This is a homework problem, and I was given the following hint:

Use Martingale Convergence Theorem. Under what conditions is the expectation of limit equals that of martingale under what conditions?

My attempt involves first showing that $(X_n)_{n \geq 0}$ is indeed a martingale. One can check that $0 \leq X_n \leq 1 \; \forall n$, so we can apply both Martingale Convergence Theorem and Dominated Convergence Theorem to conclude that $X_n \to X$ for some random variable $X$, and $\mathrm{E}[X] = \lim_{n \to \infty}\mathrm{E}[X_n] = x$. I'm stuck on where to proceed here.
I conjecture that $X \in \{0,1\}$ almost surely, which would thus imply the result.
Any help is appreciated.

A: By Martingale Convergence Theorem $X =\lim X_n$ exist a.e. Taking limit in the definition we see that  $X=X^{2}$ or $X=2X-X^{2}$. The second equation is same as the first so $X=X^{2}$ a.s. This means $X=0$ or $1$ a.s. Also $P(\lim X_n=1)=P(X=1)$. Since $X$ is $0-1$ valued $EX=P(X=1)$. Hence $P(\lim X_n=1)=EX=EX_0=x$


text:
Q: Make a CSV/spreadsheet showing number of polygons in polygons? I have a QGIS project containing two multipolygon layers: 2010 Census block groups and Parcels. Each layer is in a separate shapefile.

The thick-lined layer represents block groups. The thin-lined layer is parcels. The block group layer attribute table shows that each block group has a unique ID.
How do I output the number of parcels in each block group into a spreadsheet-style format? Is it possible in QGIS or must I choose another program?

A: Steps I would take to solve this problem assuming the block groups is a separate file to the parcels:

*

*Add a field to the parcels polygons call it whatever you want

*Calculate that new field in the parcels table to equal 1

*Perform a spatial join between the block group is joining the parcels and the 'SUM' statistics button is selected

*export the spatial join output to a .csv file
spatial join tutorial


text:
Q: Muted youtube with iframe and javascript code not working Good afternoon,
I have the following code:


text:
Q: Is there a way to catch or detect if any of this PowerBI Button is clicked? I am working on PowerBI Embedding and I have to detect if the 'include' or 'exclude' button has been selected.

I have tried using its html title, but it doesn't work:
    $("button[title='Include']").click(function () {
        alert("TEst");
    });

    $("button[title='Include']").on("click", function () {
        alert("TEst");
    });

I also tried PowerBI command trigger event but it didn't work as well:
report.on("commandTriggered", function (event) {
    let commandName = event.detail.command;
    if (commandName === "command name") {
        // Handler code
    }
});

A: Currently, there is no method to do that. The embedding does not have any event handlers that handle this Event. You can obtain detailed information about what visual was selected and if the Include or Exclude button was hit by just looking at the filters that have been set . This might not always work as user can pass filters at the time of embedding as well.


text:
Q: Remove values from list element, and add to other element Basically what I need is to make a list of 400 elements, all have value 1. The next step is to create a function, that subtracts value (-1) from an element, and adds that to another element.
So: (1,1,1,1) could become (1,2,1,0).
Running the function 1 time is called a sweep.
The sum of the list has to be 400 at all times, and an element needs to have minimum value 0.
The function needs to make all elements ''exchange'' 1's with each other randomly.
(1,2,1,0) could also become (0,4,0,0) for example.

A: Here is a rough stab at it that should help you get started:
f[x_List] := Module[{n, lis = Range @ Length @ x, len = Length @ x, d = x},
  Do[(n = RandomChoice[lis, 2];
    If[d[[First @ n]] > 0, d[[First @ n]] -= 1; d[[Last @ n]] += 1]), {len}];
  d]

Now we generate our list of ones:
list = ConstantArray[1, 400];

Then:
res = f @ list

{0, 2, 2, 1, 1, 2, 3, 0, 0, 1, 1, 1, 1, 2, 0, 0, 2, 1, 0, 2, 0, 1, 3,
1, 1, 4, 2, 2, 0, 1, 0, 0, 2, 1, 0, 1, 2, 1, 1, 1, 1, 1, 0, 1, 0, 0,
1, 0, 0, 3, 2, 1, 1, 0, 2, 1, 0, 1, 1, 0, 0, 2, 0, 0, 1, 0, 1, 2, 1,
2, 1, 1, 1, 1, 1, 1, 0, 2, 1, 3, 0, 0, 1, 0, 1, 1, 2, 2, 0, 0, 0, 0,
2, 0, 2, 2, 0, 0, 1, 0, 0, 1, 3, 0, 1, 0, 1, 1, 1, 0, 2, 2, 0, 1, 2,
0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 2, 0, 0, 0, 1, 0, 3, 1, 2, 2, 1, 1, 1,
0, 0, 2, 1, 1, 0, 0, 1, 2, 0, 0, 3, 0, 1, 2, 3, 2, 2, 0, 3, 4, 1, 0,
0, 2, 0, 0, 0, 0, 0, 1, 2, 1, 4, 0, 0, 0, 0, 0, 0, 3, 0, 2, 1, 3, 2,
0, 1, 1, 0, 1, 2, 1, 0, 2, 1, 0, 0, 0, 0, 0, 3, 2, 0, 2, 0, 1, 0, 0,
1, 3, 1, 0, 2, 1, 0, 1, 1, 1, 3, 0, 1, 2, 1, 1, 0, 1, 2, 4, 0, 1, 2,
0, 2, 3, 3, 0, 0, 1, 2, 2, 0, 3, 1, 1, 0, 0, 1, 2, 0, 0, 1, 0, 0, 1,
0, 1, 2, 0, 1, 1, 1, 0, 3, 1, 1, 0, 2, 1, 0, 1, 0, 0, 2, 1, 1, 1, 1,
0, 0, 1, 1, 0, 1, 3, 0, 1, 1, 2, 0, 2, 1, 0, 2, 1, 0, 0, 0, 0, 0, 1,
3, 3, 0, 2, 2, 2, 1, 0, 2, 1, 3, 2, 0, 0, 0, 2, 0, 1, 3, 1, 2, 2, 2,
1, 3, 3, 1, 0, 1, 0, 2, 2, 1, 0, 1, 1, 1, 2, 1, 1, 0, 0, 2, 0, 2, 0,
1, 2, 2, 1, 2, 1, 0, 1, 2, 0, 3, 2, 2, 0, 2, 2, 2, 1, 0, 3, 0, 0, 2,
2, 0, 0, 4, 1, 2, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 2, 2, 1, 0,
0, 1, 1, 2, 0, 0, 1, 0, 1}

And:
Total @ res

400


text:
Q: Run-time error '1004' : Method 'Range' of object'_Global' failed in a VBA code with LastRow and Workbook_Sheetchange I use the following code (see below) in VBA and get the following error:

Run-time error '1004' : Method 'Range' of object'_Global' failed

in this row:
Range("Evaluation!B" & LastRow & ":F" & LastRow).Value = Range("checklist!A" & target.Row & ":E" & target.Row).Value

Can anyone help me?
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal target As Range)
    If Sh.Name = "checklist" Then
          'Monitoring from A3:E100, if different change this
          If Not Intersect(target, Range("A3:E100")) Is Nothing Then
             'if any monitoring here, please you add here
             Test target 'Here procedure to insert
          End If
    End If
End Sub

Private Sub Test(target As Range)
    Dim LastRow As Long

    LastRow = Range("Evaluation!A" & Sheets("Evaluation").Rows.Count).End(xlUp).Row

    If Range("Evaluation!A1").Value <> "" Then
       LastRow = LastRow + 1
    End If
    'every change A3:E in checklist will insert row to this evaluation
    'but if different please you decide here
    Range("Evaluation!A" & LastRow).Value = Format(Now, "dd.mm.yyyy hh:mm") 'you can change this
    Range("Evaluation!B" & LastRow & ":F" & LastRow).Value = Range("checklist!A" & target.Row & ":E" & target.Row).Value
End Sub


text:
Q: Predicting probabilities with H2O flow Is it possible to predict probabilities in a binary classification task a in H2O flow? In particular I am finding difficulties in camputing the probability instead a crisp prediction because I can't see option in the UI of H2O when predicting.
If it's not possible doing it in H2O Flow, is there a way to do it in R (or Python) using the same model built in H2O flow?
Thanks in advance for any help.

A: This is possible in Flow and it is also possible to get the model from the backend using its key and then continue with your model analysis in one of the apis (R/Py)
Please also take a look at the documentation on how to make predictions in Flow if needed.
After you build a model you will see that there is a predict button:

*

*Click on the predict button.

*Specify a name for your prediction frame, the model will already be set, select the frame you want to predict on using the frame dropdown menu, and then click on the action button called predict.

*In the next cell called Prediction you will see a table that will have three hyperlinks (model, frame, and predictions). The third hyperlink should correspond to your predictions dataframe, which you provided the name for or H2O-3 provided a default name for.

*Click on the hyperlink in the predictions row or create a new cell, type getFrameSummary "prediction" (without the ` marks, and replace "prediction" with the name of your prediction frame).

*Now click on the view data button, and if your binary target is of type enum (i.e. categorical and not numeric) you will see a table with prediction labels and probabilities.


text:
Q: How can I include a groovy script(with classes, functions) in another groovy file? My environment: groovy -v
Groovy Version: 3.0.4 JVM: 1.8.0_242 Vendor: Azul Systems, Inc. OS: Linux
I write two files: AStar.groovy and digit.groovy.
file AStar.groovy like:
class State{
    int deep = 0;
    def pre;
    double f = 0;
}

abstract class AStar {
    State begin;
    State end;
    def astar() {
        // some astar code
    }
    abstract def judge(def state);
}

and file digit.groovy like:
class DigitState extends State {
    // some fields and methods
}
class Digit extends AStar {
    // some fields and methods;
    def judge(def state) {
        // some codes.
    }
}
def digit = new Digit();
def path = digit.astar();
path.each {
    println(it);
}

now I want to run digit as: groovy digit.groovy
But it tell me "unable to resolve class State"
I see this url:
Including a groovy script in another groovy
But I can not run my script by that way, and I do not know what is my wrong.
How can I include the file without compile please?

A: In digit.groovy, use:
import AStar

if they are in the same package.
I tried your code in Eclipse and it ran even without the import statement.


text:
Q: Is using 204 http status code to do "ajax" forms considered "good practice"? I want to do html forms that submit in the background. I currently use a external library (jquery ajax form) in order to this.
I just learned about the 204 http status code which tells the agent not to redirect. In my tests when a form submit callback returns this code the web browser (chrome) stays on the same page. Would using this status code instead of a library to do ajax forms be considered a good practice or should I continue using a library for this? Do most browsers support it? Why do libraries even exist if there is a status code to do this?

A:
204 Status code
  The server has fulfilled the request but does not need to return an
  entity-body, and might want to return updated metainformation. The
  response MAY include new or updated metainformation in the form of
  entity-headers, which if present SHOULD be associated with the
  requested variant.

Status code 204 can be used for ajax requests. Response with 204 status code is meant to say to the client that the request has been successfully accepted/executed but there is no entity body in the response. But there can be updates in meta information. i.e you can add updates to the headers.


text:
Q: My function could return a promise or value, how to avoid it? I think it's bad practice to have different return types. So, this is my function, and I want it to always return a promise.
I tried to simplify the scenario. Let's say I have two lines of products (line X and line Y) and the way I'm retrieving a product by name, from each line is totally different from the other.
Please also note that ideally, I wanted to have a function to "or" two promises and return whichever that resolves successfully. But I couldn't think of a better way to achieve this!
ProductService.findProductByName = function findProductByName(name) {
  return LineXService.findOneByName(name) // promise
    .then(function _returnProduct(product) {
      return product
        ? product // value
        : LineYService.findOneByName(name)); // promise
    })
};

A: You're right that returning a consistent thing is better than an ambiguous result. Normally you can cast an arbitrary value into a promise easily enough. For example using resolve:
if (product) {
  return Promise.resolve(product);
}

return LineYService.findOneByName(name);

It's worth noting, as Kevin B observes, that this is irrelevant in this particular case since your outer function always returns a promise. The need to promisify a value is only a concern if this is not part of a surrounding promise.


text:
Q: Jquery Get Local pc ip address and check administrator in my organization all http sites are blocked
and i want ip address and to check administrator if not then logout in sharepoint.
I am using http://ipinfo.io to fetch ip address. but now this is blocked and when i am using https://ipinfo.io it is giving me server ip not my local pc ip.
Any help would be appreciated.
var IPCollections = "192.168.1.29"; // Add ips here
$.ajax
     ({
         url: "/_api/web/CurrentUser?$select=Title",
         method: "GET",
         async: false,
         headers: {
             "accept": "application/json;odata=verbose",
             "content-type": "application/json;odata=verbose",
             "X-RequestDigest": $("#__REQUESTDIGEST").val()
         },
         success: function (data) {
             try {
                 if (data.d.Title == "superuser" || data.d.Title == "Super Admin") {
                     $.get("http://ipinfo.io", function (response) {
                         var Ip = response.ip;
                         console.log(Ip);
                         var arrycoll = IPCollections.split(',');
                         var keeplogin = false;
                         for (var i = 0; i < arrycoll.length; i++) {

                             if (Ip == arrycoll[i]) {
                                 keeplogin = true;
                             }
                         }
                         if (!keeplogin) {
                             window.location.href = "/_layouts/SignOut.aspx";
                         }

                     },"jsonp");
                 }
             } catch (err) { }
         },
         error: function () {
         }
     });

A: I find hard to believe that jquery (that runs on PC) gives web server's ip. I suggest you make a html page on you pc and run it. Are you sure it doesn't give proxy ip?


text:
Q: How to print a view in MVC with out showing printer options screen I have a view which contains few tables and it has some dynamic data.
I need to print this view up on clicking some button.
for ex:
I have following method in my controller
[HttpPost]
public ActionResult SomeMethod(Someparameter)
{
   if(someclass.somemethod())
   //if the above method returns true I need a print function here to print my view
}

I need this print function to be handled in C#,unlike js print().
And the more challenging is I dont want to display the print options to user and user is not aware of printing.
Print function should take configurable printer options and print directly.
Any help?
Thanks in advance.
EDIT:
i got the following code:
using System.Drawing;
using System.Drawing.Printing;

public void Print()
{
  var doc = new PrintDocument();
  doc.PrinterSettings.PrinterName = "\\\\deployment-machine-name\\share-name";
  doc.PrintPage += new PrintPageEventHandler(ProvideContent);
  doc.Print();
}
public void ProvideContent(object sender, PrintPageEventArgs e)
{
  e.Graphics.DrawString(
"Hello world",
new Font("Arial", 12),
Brushes.Black,
e.MarginBounds.Left,
e.MarginBounds.Top);
}

where it takes the printer name and prints the required with out showing printer settings window.
But the problem is I want to print a view(in the above code,it prints a string value).


text:
Q: Тип timestamp отображается как DATETIME Установил в таблице тестовой тип поля timestamp, и при добавлении туда значения в виде 1421312123 оно отображается как 0000-00-00 00:00:00
Почему так происходит?
Перепроверяю, тип действительно timestamp.

A: тип timestamp хранит дату и время (отметку времени):

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

вы же пытаетесь вставить в столбец число (в математическом смысле этого слова).
это число весьма похоже на количество секунд, прошедших с 1970-01-01 00:00:01 по 2015-01-15 11:55:23 (в московском часовом поясе), т.е., на unix-время (unix timestamp).
если так, то нужно преобразовать это число в дату и время с помощью функции from_unixtime. примерно так:
insert into t values (from_unixtime(1421312123));

тогда в столбец с типом timestamp попадёт корректное значение, и эта отметка времени будет корректно отображаться:
select * from t;
+---------------------+
| d                   |
+---------------------+
| 2015-01-15 11:55:23 |
+---------------------+


text:
Q: xampp fatal error I am very new to php, xampp.
I was using xampp for php interacting with phpmyadmin.
I was working pretty well until xampp mysql stoped working.
For some reason, I could not start mysql, although I was able to start apache.
so, i decided to uninstall xampp and reintall it. however, when i was reinstalling it and choose the blank folder for some process, it said the folder i chose is not empty. so i deleted the phpmyadmin folder inside xampp folder.
Then now it is telling me that alloc: invalid block.
I looked up on the internet, but I cannot find the solution.
If someone knows what is going on my laptop, please let me know the solution
and I am very new to this field, please please explain in as the easiest way as possible.

A: May be your old installed xampp is not uninstalled properly. Follow this steps :-
1) Delete 'xampp' folder in 'C:/',
2) Delete 'MySQL' folder in 'C:/Program Files' if there,
3) Delete 'Apache Software Foundation' folder in 'C:/Program Files' if there.
4) Restart your PC/Laptop,
5) Install xampp again.
If you want to prevent your folder data then copy them into a temporary folder. After installation cut them and copy to their relevant locations.

A: *

*Try checking if xampp is installed by looking in your C drive.

*Check Windows Uninstall Utility.

*Check if port 80/443 is running. If so, this means that Xampp is installed and running

*Open taskmgr and see if xampp is running.

*Restarting your computer

*Reinstall or try an older version


text:
Q: In a non-Hausdorff space, can a compact subset fail to be closed? In a Hausdorff space $X$, every compact subset $Y$ is closed. So if I relax the condition on $X$ being Hausdorff, is it possible compact subset $Y$ of $X$ not being closed?

A: Yes.  Take a compact Hausdorff space with topology $\tau$ and weaken the topology, i.e. take any topology $\tau'$ strictly weaker than $\tau$, so that there is some set $U$ that is open in topology $\tau$ but not in $\tau'$.
But $U^c$ is still compact in $\tau'$ (because any open cover for $\tau'$ is still an open cover for $\tau$).  So $U^c$ is a compact set that is not closed
for topology $\tau'$.

A: For sure. Consider $X = \{a, b\}$ with topology $\tau = \{\emptyset, \{a\}, X\}$. Note that $(X, \tau)$ is not Hausdorff and that $\{a\}$ is compact (the open covers for $\{a\}$ are already finite), but not closed.

A: Yes, it's possible. Let $X=(-1,1)\cup\{0'\}$, where the point $0'$ is a distinct "copy" of the point $0$. Let $\tau$ be the topology on $X$ generated by the sets $(-1,a)$, $(a,1)$, $((-1,b)\setminus\{0\})\cup\{0'\}$, and $((c,1)\setminus\{0\})\cup\{0'\}$, where $a\in(-1,1)$, $b\in(0,1)$, and $c\in(-1,0)$.
This topology is not Hausdorff and the set $[-1/2,1/2]$ is compact but not closed.


text:
Q: Calculate between two day and calculate a fine $date2 = $row['returnbefore'];

$date1 = date('Y/m/d');

$diff = abs(strtotime($date1) - strtotime($date2));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

$final = ($days * 10) ;

echo $final;

i want to do a library system when user return book will check the return date between current date and calculate a fine to user which multiply day by 10 .
what step i left ? and i wan set the current time is my computer time so i can test it

A: This is a fairly simple problem to accomplish using DateTime and DateInterval.
$now = new DateTime();
$dueDate = new DateTime($row['returnbefore']);

$lateInterval = $now - $dueDate;
$daysLate = $lateInterval->format('d');
$fine = $daysLate > 0 ? intval(floor($daysLate)) * 10 : 0; // This means that you are not charged for a late day until the end of the day


text:
Q: How do I deserialize an array of enum using Json.Net? I have a JSON like this:
[{
    "agencyId": "myCity",
    "road": {
    "note": "",
        "lat": "45.321",
        "lon": "12.21",
        "streetCode": "290",
        "street": "street1",
        "fromNumber": "",
        "toNumber": "",
        "fromIntersection": "",
        "toIntersection": ""
    },
    "changeTypes": ["PARKING_BLOCK", "ROAD_BLOCK"],
},]

and a class like this:
public class AlertRoad : BaseAlert
{
    [JsonProperty("agencyId")]
    [JsonConverter(typeof(StringEnumConverter))]
    public AgencyType AgencyId { get; set; }

    [JsonProperty("changeTypes")]
    [JsonConverter(typeof(StringEnumConverter))]
    public ChangeType[] ChangeTypes { get; set; }

    [JsonProperty("road")]
    public Road RoadInfo { get; set; }
}

AgencyType is an enumeration, and deserializiation and serialization for AgencyId works.
ChangeType is another enumeration, but deserializiation and serialization for ChangeTypes doesn't work.
I assume the reason is that ChangeTypes is an array of enumeration values.
The question is: how can I deserialize/serialize ChangeTypes field, or in general an array of enumeration values?
I tried by defining my own field converter, called ChangeTypeConverter, and changing StrinEnumConverter to ChangeTypeConverter for ChangeTypes field, but in the ReadJson function the value of reader is null.
public class ChangeTypeConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {

    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var val = reader.Value;
        //val is null?!?
        return val;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(ChangeType);
    }
}

A: The StringEnumConverter expects only a single enumeration value.  Because ChangeTypes is an array, you need to annotate the property a little differently to make it work.
Try this instead:
[JsonProperty("changeTypes", ItemConverterType=typeof(StringEnumConverter))]
public ChangeType[] ChangeTypes { get; set; }

A: There is no need to write a custom JsonConverter for serializing/deserializing array of Enum.
Instead of decorating individual property within parent model, just decorate the Enum with a StringEnumConverter JsonConverter attribute.
For eg:-
Following Environment model has Shelter enum property and array of enum Shelter[]
public class Environment
{

    public string Name { get; set; }
    public Shelter Shelter { get; set; }
    public Shelter[] Shelters { get; set; }
}

[JsonConverter(typeof(StringEnumConverter))]
public enum Shelter
{
    Indoor,
    Outdoor
}

Output json:-
 {
   "name": "",
   "shelter": "Indoor",
    "shelters": [
       "Indoor",
       "Outdoor"
  ]
 }


text:
Q: Problem using `flake8` for linting on Sublime Text 3 I've been unsuccessfully trying to use the SublimeLinter-flake8 on my Xubuntu laptop. I have Python 3.7.7 installed through the Anaconda distribution, as well as the flake8 package. I'm also using the Anaconda IDE plugin for Sublime Text 3, with Anaconda's linting turned off.
But I keep getting the same error message whenever I type some Python code in:
SublimeLinter: #1 flake8 <untitled 25> ERROR:
=============================================

Traceback (most recent call last):
  File "/home/srdjan/anaconda3/bin/flake8", line 11, in <module>
    load_entry_point('flake8==3.7.7', 'console_scripts', 'flake8')()
  File "/home/srdjan/.local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 484, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "/home/srdjan/.local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 2714, in load_entry_point
    return ep.load()
  File "/home/srdjan/.local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 2332, in load
    return self.resolve()
  File "/home/srdjan/.local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 2338, in resolve
    module = __import__(self.module_name, fromlist=['__name__'], level=0)
  File "/home/srdjan/anaconda3/lib/python3.7/site-packages/flake8/main/cli.py", line 2, in <module>
    from typing import List, Optional
  File "/home/srdjan/anaconda3/lib/python3.7/site-packages/typing.py", line 1347, in <module>
    class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
  File "/home/srdjan/anaconda3/lib/python3.7/site-packages/typing.py", line 1003, in __new__
    self._abc_registry = extra._abc_registry
AttributeError: type object 'Callable' has no attribute '_abc_registry

Strangely enough, I was having somewhat similar problems when I was using SublimeLinter-pycodestyle and SublimeLinter-pyflakes, where pyflakes would keep throwing these weird error messages. I was never able to get it to work.
Should I perhaps uninstall pycodestyle and pyflakes from my laptop, now that I have flake8 and its accompanying SublimeLinter-flake8 plugin?


text:
Q: How to run strapi in the background? I am able to deploy my strapi project to a remote server. How it works? - I connect via the console to the remote nginx server, go to the root of the project and write npm run develop, but unfortunately, if I close the terminal (through which I connected to the remote server), the project will close, and I need it to work 24/7.
Question: How to do it?
PS: I could attach nginx configurations here, but I don't know if they are needed.

A: the easiest way of doing this is thru pm2:
in root of your project add file strapi.js with following config:
/strapi.js
const strapi = require('@strapi/strapi');
strapi().start();

connect to the server via ssh, let's assume that your strapi project is located in /var/www/strapi
so
yarn global add pm2
OR
npm install pm2@latest -g

cd /var/www/strapi
pm2 start strapi.js

After the process is created
you can do:
pm2 stop strapi    // stops server
pm2 start strapi   // starts server
pm2 monit strapi   // monitor server
pm2 list           // lists pm2 processes

you can reference docs


text:
Q: How to make sure the sql result is continued range? I have table like:
id   | low_number | high_number
-------------------------------
1    |  12        | 32
-------------------------------
2    |  13        | 33
-------------------------------
3    |   15       | 36
-------------------------------
4    |   33       |  50
-------------------------------
5    |   35       | 52
...
-------------------------------
17   |   52       |  80

I want to get result like:
id   | low_number | high_number
-------------------------------
1    |  12        | 32
-------------------------------
4    |   33       |  50
-------------------------------
17   |   52       |   80

that is because the low_number bigger than the pervious row high_number.
How to write sql to get these result? I use postgresql

A: This seems like a recursive CTE problem.  You want to choose the first row (by id) and then choose the next row based on that.
The idea is to cycle through the rows, one at a time.  Then when the condition is met, transition to that row.  And so on.
As a query, this looks like:
with recursive tt as (
      select id, low_number, high_number, row_number() over (order by id) as seqnum
      from t
     ),
     cte as (
      select id, low_number, high_number, seqnum, true as is_change, id as grouping_id
      from tt
      where seqnum = 1
      union all
      select tt.id, tt.low_number, tt.high_number, tt.seqnum, tt.low_number > t.high_number,
             (case when tt.low_number > t.high_number then tt.id else cte.grouping_id end)
      from cte join
           t
           on cte.grouping_id = t.id join
           tt
           on tt.seqnum = cte.seqnum + 1
     )
select *
from cte
where is_change;

Here is a db<>fiddle.

A: Use the window function LAG() to get a value of a previous row, e.g.
WITH j AS (
  SELECT
    id,low_number,high_number,
    LAG(high_number) OVER (ORDER BY id) AS prev_high_number
  FROM t)
SELECT id,low_number,high_number  FROM j
WHERE low_number > prev_high_number OR prev_high_number IS NULL;

Demo: db<>fiddle


text:
Q: Malliavin derivative of a Lebesgue integral. Let $X_t$ a random process such that its Malliavin derivative is well defined for all $t$. Then I have read that :
$D_s(\int_0^t \! X_u \, \mathrm{d}u)=\int_s^t \! D_s(X_u) \, \mathrm{d}u.$
What I don't understand is why in the second integral, the domain of integration is now $[s,t]$.
Thanks for your help !

A: I assume that $X_t$ is progressively measurable with respect to the corresponding Wiener process $W_t$ (otherwise the formula doesn't hold).
$X_t$ being $\sigma(W_s,s\le t)$-measurable implies that it does not depend on the "tail" $\{w(v),t<v\le T\}$ as a functional from $L_2(C([0,T],\mathbb{R}),\text{Wiener measure})$, $t<T\le\infty$. Thus, $D_hX_t$ is zero on the $\{h: \operatorname{supp}(h)\in(t,T]\}$ and $D_s(X_t)=0$ for $s>t$, therefore
$$
D_s\left(\int_0^t  X_udu\right)=\int_0^t D_s(X_u) du=\int_s^t D_s(X_u) du.
$$


text:
Q: Return promise in node.js i try to return data in node.js from a APIs , but I'm having problems, because I need an asynchronous function, I couldn't understand for sure the correct use of the promise, I've tried everything and I couldn't put the result in the return, only in the console.log, somebody help me?
const express = require('express')
const MFA = require('mangadex-full-api')

module.exports = {
    async indexManga(req, res) {

        const mangalist = MFA.login('DarksGol', 'R@ul1605', './md_cache/').then(async () => {

            manga = []
                await MFA.Manga.search('Kiss').then(results => {
                results.forEach((elem, i) => {
                    let obj = {}
                    obj.status = elem.status
                    obj.title = elem.title

                    manga.push(obj)
                })
            }).catch(console.error)

            return manga

        }).catch(console.error)

        console.log(await mangalist)
        return mangalist
    }
}

no error occurred, only infinite loading on request
const express = require('express')
const routes = express.Router()

const searchManga = require('../src/controllers/searchManga')

routes.get('/searchManga', searchManga.indexManga)

module.exports = routes

A: I don't see why this would cause "infinite loading on request", but you could greatly simplify the code to just
const express = require('express');
const MFA = require('mangadex-full-api');

module.exports = {
    async indexManga(req, res) {
        await MFA.login('DarksGol', 'R@ul1605', './md_cache/')
        const mangaList = [];
        const results = await MFA.Manga.search('Kiss');
        results.forEach(elem => {
            mangaList.push({
                status: elem.status,
                title: elem.title,
            });
        });
        return mangalist;
    },
};

A: Looks like indexManga is an endpoint. Each endpoint function must end the request-response cycle by sending a response ( res.send(), res.json(), res.end(), etc). If indexManga s an endpoint, the solution would be:
...

//return mangalist
res.send(mangalist)

or
//return mangalist
res.json({ status: "success", message: "logged in successfully" })

If it is a meddleware:
async indexManga(req, res, next) {
  ...
  //return mangalist
  return next()
}

EDIT: you are using async/await with .then() improperly in some places.
Try this way:
module.exports = {
    indexManga(req, res) {
        MFA.login('DarksGol', 'R@ul1605', './md_cache/').then(() => {

            manga = []
            MFA.Manga.search('Kiss').then(results => {
                results.forEach((elem, i) => {
                    let obj = {}
                    obj.status = elem.status
                    obj.title = elem.title

                    manga.push(obj)
                })

                res.json({ status: "success", data: manga })

            }).catch((err) => {
               res.json({ status: "fail", error: err })
            })

        }).catch((err) => {
           res.json({ status: "fail", error: err })
        })
    }
}


text:
Q: Configure R to use utf-8 by default To avoid problems when using R and RStudio, can R be configured to work with utf-8 by default? My system is windows 10 64 bit, R scripts are saved as ANSI, however when opening those same files with RStudio there are problems with the Latin characters, ñ, tildes, euro symbol €. I have to convert the files to change the character encoding, so that I can use them with RStudio.
From the R console:

> sessionInfo()
R version 4.0.5 (2021-03-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042)

Matrix products: default

locale:
[1] LC_COLLATE=Spanish_Spain.1252  LC_CTYPE=Spanish_Spain.1252
[3] LC_MONETARY=Spanish_Spain.1252 LC_NUMERIC=C
[5] LC_TIME=Spanish_Spain.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_4.0.5

A: In RStudio go to Tools bar, then click Global options (at the bottom):
See picture below: Click Code, then Saving -> you can set default text encoding


text:
Q: DEAP algorithm with several weights I'm pretty new to DEAP and looking at several places and examples I've seen it creates classes for genetic algoritms using this method:
creator.create('FitnessMax', base.Fitness, weights=(1.0, -0.5,))
creator.create('Individual', list, fitness=creator.FitnessMax)

What I don't understand is the weights parameter. It is supposed that DEAP can be used to solve multiobjectives problems (maximize and minimize), that's why weights can be positive or negative.
But how is it linked to the fitness/objective function? Must the fitness function return several values, one for each weight?

A: For multi-objective problems, your fitness function must return a tuple with the same number of results as the specified number of weights, e.g.:
creator.create('Fitness', base.Fitness, weights=(1.0, -0.5,))
creator.create('Individual', list, fitness=creator.Fitness)

[...]

toolbox.register('evaluate', fitness)

def function_minimize(individual):
    return individual[0] - sum(individual[1:])

def function_maximize(individual):
    return sum(individual)

def fitness(individual):
    return (function_maximize(individual), function_minimize(individual)),

Also, keep in mind that your selection method must support multi-objective problems, tournament selection for instance, doesn't, so if you use it, weights will be ignored). A selection method that supports this kind of problem is NSGA2:
toolbox.register('select', tools.selNSGA2)


text:
Q: how to add + button for foreign key , similar to django's admin i'm trying to implement + button for foreign key select field , if the foreign key doesnt exist instead of going to another page just pop up a form page to add new entry for the foreign key , i've implemented but its full size and dont go to the previous page when i submit the form : this is what i tried
class RelatedFieldWidgetCanAdd(widgets.Select):
    def __init__(self, related_model, related_url=None, *args, **kw):
        super(RelatedFieldWidgetCanAdd, self).__init__(*args, **kw)
        if not related_url:
            rel_to = related_model
            info = (rel_to._meta.app_label, rel_to._meta.object_name.lower())
            related_url = 'admin:%s_%s_add' % info
            self.related_url = related_url

    def render(self, name, value, *args, **kwargs):
        self.related_url = reverse(self.related_url)
        output = [super(RelatedFieldWidgetCanAdd, self).render(name, value, *args, **kwargs)]
        output.append(' ' % \
            (self.related_url, name))
        output.append('' % (settings.STATIC_URL, 'Add Another'))
        return mark_safe(''.join(output))

class BookingVisitorForm(forms.ModelForm):
    visitor = forms.ModelChoiceField(
        queryset=Vistor.objects.all().order_by('-pk'),empty_label='--------',
        widget=RelatedFieldWidgetCanAdd(Vistor,related_url='')
    )
    class Meta:
        model = BookingVisitor
        fields = ['visitor','reason']

updated
this is screen shot of my window

python 3
django 3.2
is there something i did wrong ? or isnt there a better way to achieve it , but when i added a new visitor it should being selected in the foreign key drop down field ! thank you in advance ...


text:
Q: Ambiguous method overloading for method grails.spring.BeanBuilder#registerBeans I'm following Mike Kelly's brilliant tutorial videos but I have been stumped by the following problem. It happens when I add a new Domain Class. I've tried backing out changes and adding a DomainClass with a different name, restarting the IDE, etc. With only one Domain Class I have no error, if I add one the error appears.
I'm working with ggts 3.4.0, Grail 2.3.1, JDK 1.7.0_45.
 | Error 2013-11-04 21:56:37,442 [Thread-8] ERROR plugins.AbstractGrailsPluginManager  - Plugin [domainClass:2.3.1] could not reload changes to file [C:\Grails\ProjectTracker\grails-app\domain\projecttracker\EndUser.groovy]: Ambiguous method overloading for method grails.spring.BeanBuilder#registerBeans.
Cannot resolve which method to invoke for [null] due to overlapping prototypes between:
    [interface org.codehaus.groovy.grails.commons.spring.RuntimeSpringConfiguration]
    [interface org.springframework.beans.factory.support.BeanDefinitionRegistry]
Message: Ambiguous method overloading for method grails.spring.BeanBuilder#registerBeans.
Cannot resolve which method to invoke for [null] due to overlapping prototypes between:
    [interface org.codehaus.groovy.grails.commons.spring.RuntimeSpringConfiguration]
    [interface org.springframework.beans.factory.support.BeanDefinitionRegistry]
    Line | Method
->> 2980 | chooseMostSpecificParams     in groovy.lang.MetaClassImpl

A: This is a bug. I was able to reproduce the problem when I was investigating http://jira.grails.org/browse/GRAILS-10735 .

A: You can override the ambiguous method when passing null to its parameter
MyClass.metaClass.myAmbiguousMethod = {def param ->
    if(param != null){
        myAmbiguousMethod(param)
    } else{
        null
    }
}

A: I can reproduce this in grails 3.2.4 by providing a render invalidVariablestatement. Bad argument to render can cause this from what I can tell