text:
Q: java do while loop keeps looping after condition is met I am a new java programmer and I am writing a program that sets 3 model numbers for 3 printers. If user inputs wrong values I want it to continue asking user for the model number. I got it to work but only if the first value the user inters the the number for one of the 3 printers. if the first value is not one of the possible values and the second input is it still keeps repeating the loop.
package printing;

import java.util.Scanner;

public class newClass {

    public static void main(String[] args) {

        int count = 0;

        String machine1 = "546";
        String machine2 = "892";
        String machine3 = "127";

        Scanner s = new Scanner(System.in);

        System.out.print("Model Number:");
        String modelNumber = s.nextLine();
        // increment count if first input value is wrong
        if (!s.equals(machine1) || !s.equals(machine2) || !s.equals(machine3))
            count++;

        // if user inputs right value
        while (true) {
            if (modelNumber.equals(machine1)) {
                System.out.println("Machine 1 is online");
                break;
            }
            if (modelNumber.equals(machine2)) {
                System.out.println("Machine 2 is online");
                break;
            }
            if (modelNumber.equals(machine3)) {
                System.out.println("Machine 3 is online");
                break;
            }

            // keep looping if user does not input values for machine1, machine2 or machine3
            do {
                System.out.println("Try again");
                System.out.print("Model Number:");
                String modelNumberFalse = s.nextLine();
                /* each time user gets value wrong the count variable goes up by 1 and
                   the loop breaks when count reaches 3 */
                count++;
                if (count == 3)
                    break;
            } while (!s.equals(machine1) || (!s.equals(machine2)) || (!s.equals(machine3)) && (count < 2));

        }
    }
}

Also each time the user inputs the wrong value I want the count variable to increment until it reaches 3 and the do while loop breaks  but it keeps asking for the model number after I've entered the wrong values more than 3 times.

A: There are several problems. This line is wrong:
while(!s.equals(machine1) || (!s.equals(machine2)) || (!s.equals(machine3)) && (count < 2));

s is a Scanner, not a String, this isn't a valid comparison. Substituting modelNumber for s gives:
while(!modelNumber.equals(machine1) || (!modelNumber.equals(machine2)) || (!modelNumber.equals(machine3)) && (count < 2));

This can't be false unless modelNumber, machine1, machine2, and machine3 are all the same value.
Also testing count is messing this up and is redundant since you're testing it and breaking within the loop.
It should be
while(!modelNumber.equals(machine1)
    && (!modelNumber.equals(machine2))
    && (!modelNumber.equals(machine3)));

See DeMorgan's Laws. Applying this rule gives
while(!(modelNumber.equals(machine1)
    || modelNumber.equals(machine2)
    || modelNumber.equals(machine3)))

which may be easier to read.
Also, if you substitute "return" for "break;" along with making the change to the do-while condition, it works. So there is something else going on. Calling break in the inner do-while causes control to return to the top of the outer while loop. Adding a boolean flag that is set before you break and which is tested in the outer while loop would be one way to solve this. Or just use return.

A: import java.util.Scanner;

public class newClass
{

    public static void main(String[] args)
    {
        int count = 0;
        String machine1 = "546";
        String machine2 = "892";
        String machine3 = "127";

        Scanner s = new Scanner(System.in);

        while (true)
        {
            System.out.print("Model Number:");
            String modelNumber = s.nextLine();
            // increment count if first input value is wrong
            if ((!modelNumber.equals(machine1)) || (!modelNumber.equals(machine2)) || (!modelNumber.equals(machine3)))
                count++;

            if (count == 3)
            {
                System.out.println("You have utilized your maximum number of try's");
                break;
            }

            if (modelNumber.equals(machine1))
            {
                System.out.println("Machine 1 is online");
                break;
            }
            if (modelNumber.equals(machine2))
            {
                System.out.println("Machine 2 is online");
                break;
            }
            if (modelNumber.equals(machine3))
            {
                System.out.println("Machine 3 is online");
                break;
            }

            System.out.println("Try again");

        }
    }
}

Hope this solves your question

A: *

*First: you use NOT OR when you need NOT AND

*Second: You are repeating
the test for no good reason

In your code, you end up having the same test repeated. This means, as you add machines, you will have to update your code in multiple places.
First rule of software is to not repeat yourself. When the next guy is asked to chance the conditions, he/she will find the first block of code and edit it and probably never notice the repeated block. Copy pasted code is the root or many future bugs.
You could simplify your code to having each check only once like this:
import java.util.Scanner;

public class newClass {

    public static void main(String[] args) {

        int count = 0;

        // for extra credit, try to make this an ArrayList
        // so you can keep adding models as needed
        // then you would adjust your tests to leverage the ArrayList
        // search functions
        String machine1 = "546";
        String machine2 = "892";
        String machine3 = "127";

        Scanner s = new Scanner(System.in);

        // when using a while loop, it is good practice to use a boolean
        // as your logic expands, multiple tests in the loop may set the
        // boolean to true or false
        // it is cumbersom to have large blocks of code in your while check
        boolean keepOnTrucking = true;

        System.out.print("Enter Model Number:");
        while (keepOnTrucking) {

            String modelNumber = s.nextLine();

            // when using multiple tests, it is good
            // to give each test its own line and end the line
            // with the logical operator that joins it to the next
            // it makes it easier to read
            // and easier to edit (add or remove tests)

            // Logical operator note:
            // Your test was: not A OR not B OR not C
            // This would NEVER work, as A != B != C
            // If a user entered machine2, the check would
            // fail for !(machine1), OR !(machine2) OR !(machine3)
            // because while (!s.equals(machine2)) would say false
            // (!s.equals(machine1)) would say true, and the OR
            // chain would stop and count it as an error.
            // Instead you want:
            // !(machine1) && !(machine2) && !(machine3)
            // Thus to to error, it has to not any of the machines.
            // If it is true for all three nots, then you have an error
            if (!machine1.equals(modelNumber) &&
                !machine2.equals(modelNumber) &&
                !machine3.equals(modelNumber)) {

                // you only increment on failure
                count++;

                // nice developers give meaningful feed back to users
                if (count>=3) {
                    System.out.print("Out of guesses! Go Away!"); // even when it is mean

                    // since you are nested in one while loop,
                    // this will break you out
                    break;
                } else {
                    System.out.print("Not a valid model number, please re-enter:");
                }
            } else {

                // the found a machine, so exit the while loop
                keepOnTrucking = false;

                if (machine1.equals(modelNumber)) {
                    System.out.println("Machine 1 is online");
                } else if (machine1.equals(modelNumber)) {
                    System.out.println("Machine 2 is online");
                } else { // since this ins the only one left, you don't need an if clause
                    System.out.println("Machine 3 is online");
                }
            }

        }
    }
}


text:
Q: Add resolve info to Robolectric package manager This SO question is very similar to what I want to do: How can I shadow the PackageManager with Robolectric
However, all the answers rely on ShadowApplication.setPackageManager(). In 2.2, this method no longer seems to exist: http://robolectric.org/javadoc/org/robolectric/shadows/ShadowApplication.html
I attempted to just grab the package manager and add a resolve info:
    RobolectricPackageManager packageManager = (RobolectricPackageManager) Robolectric.application.getPackageManager();
    Intent intent = new Intent(Intent.ACTION_MAIN,null);
    intent.addCategory(Intent.CATEGORY_HOME);
    ResolveInfo ri = new ResolveInfo();
    ActivityInfo ai = new ActivityInfo();
    ai.packageName = "com.fun.test";
    ri.activityInfo = ai;
    ri.isDefault = true;
    packageManager.addResolveInfoForIntent(intent, ri);

But to no avail. Does anyone know how to do this?

A: Intent.resolveActivity is expecting the ResolveInfo to have the following:
if (info != null) {
    return new ComponentName(
            info.activityInfo.applicationInfo.packageName,
            info.activityInfo.name);
}

So based on that, the following works for me in Robolectric 2.3:
RobolectricPackageManager packageManager = (RobolectricPackageManager) shadowOf(Robolectric.application).getPackageManager();
Intent intent = ... //create an Intent like the one you want to resolve

ResolveInfo info = new ResolveInfo();
info.isDefault = true;

ApplicationInfo applicationInfo = new ApplicationInfo();
applicationInfo.packageName = "com.example";
info.activityInfo = new ActivityInfo();
info.activityInfo.applicationInfo = applicationInfo;
info.activityInfo.name = "Example";

packageManager.addResolveInfoForIntent(intent, info);

A: You should adding the resolve info as a List:
packageManager.addResolveInfoForIntent(intent, Collections.singletonsList(ri));

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Unwanted events happened" "Unwanted events happened" couldn't be an example for passive because there's no objective in the sentence, it's just like this example, "the child cried", because "happen" is an intransitive verb.
https://www.duolingo.com/comment/9213318
Am I right?

A: As far as linguists and grammarians are concerned, you are correct that "Unwanted events happened" is not in the passive voice. (Your explanation is not quite right, however, since true passive-voice verbs don't require the objective case, either: we say "I was robbed", not *"Me was robbed". And anyway, the distinction between the subjective and objective cases only applies to pronouns; "unwanted events" would have the same form either way.)
However, many English speakers have only an imprecise understanding of "passive voice", and think that "passive" describes a sentence that conceals or de-emphasizes the agent. (They have probably misgeneralized from examples like "Mistakes were made", where the passive voice is used for that purpose.) So I think it's fair to say that the term "passive" now has two loosely-related meanings: a technical sense relating to syntax, and a non-technical sense relating to semantics and pragmatics.

A: "happened" is no passive. The passive would be "was happened" or "to be happened". (Both passive forms make no sense.) For passive you need a form of to be + past participle.


text:
Q: Having Trouble with void travel::display I am having trouble displaying a traveler in the list. It shows the date but doe not show the name and the destination. I don't know how to solve the problem.
So here is the code below.
Travler.header

#ifndef SICT_TRAVELER_H
#define SICT_TRAVELER_H

namespace sict {

    class Traveler {

    private:
         char max_destination_size[32];
         char max_name_size[16];
         char max_name_sizelast[16];
         int yearofdepart;
         int monthofdepart;
         int dayofdepart;

    public:
        Traveler();
        Traveler(const char *, const char *, const char *);
        Traveler(const char *, const char *, const char *, int, int, int);
        bool isEmpty()const;
        void display()const;
        const char* name() const;
        bool canTravelWith(const Traveler&) const;

    };
}

#endif

Taveler.cpp

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "Traveler.h"
#include <cstring>
#include <string.h>
using namespace std;

namespace sict {

    Traveler::Traveler() {
        max_destination_size[0] = '\0';
        max_name_size[0] = '\0';
        max_name_sizelast[0] = '\0';
        yearofdepart = 0;
        monthofdepart = 0;
        dayofdepart = 0;
    }

    Traveler::Traveler(const char * travlerfirstname, const char * travelerlastname, const char * destination) {
        bool nameinvalid = travlerfirstname && travelerlastname == nullptr;
        bool destinvalid = destination == nullptr;
        bool invalid = nameinvalid && destinvalid;

        if (!invalid) {
            yearofdepart = 2019;
            monthofdepart = 7;
            dayofdepart = 1;
        }
    }

    Traveler::Traveler(const char * travelerfirstname, const char * travelerlastname, const char * destination, int xyear, int xmonth, int xday)
    {
        bool yearvaild = xyear >= 2019 && xyear <= 2022;
        bool monthvaild = xmonth >= 1 && xmonth <= 12;
        bool dayvaild = xday >= 1 && xday <= 31;

        if (travelerfirstname == nullptr || travelerlastname == nullptr || destination == nullptr || !yearvaild || !monthvaild || !dayvaild) {
            *this = Traveler();
        }
        else {
            strncpy(max_name_size, travelerfirstname, 15);
            strncpy(max_name_sizelast, travelerlastname, 15);
            strncpy(max_destination_size, destination, 31);
            yearofdepart = xyear;
            monthofdepart = xmonth;
            dayofdepart = xday;
        }
    }

    bool Traveler::isEmpty()const {
        bool valid = strlen(max_name_size) > 0 && strlen(max_name_sizelast) > 0 && strlen(max_destination_size) > 0 && dayofdepart != 0 && monthofdepart != 0 && yearofdepart != 0;
        return !valid;
    }

    void Traveler::display()const {
        if (max_name_size[0] == '\0' || max_name_sizelast[0] == '\0' || max_destination_size == '\0' || yearofdepart == 0 || monthofdepart == 0 || dayofdepart == 0) {
            cout << "--> Not a valid traveler! <--" << endl;
        }
        else {
            if (monthofdepart > 0 && monthofdepart >= 6 && dayofdepart <= 7) {
                cout << max_name_sizelast << ", " << max_name_size << " goes to " << max_destination_size << " on " << yearofdepart << "/0" << monthofdepart << "/0" << dayofdepart << endl;
            } else if(monthofdepart > 0 && monthofdepart == 6){
                cout << max_name_sizelast << ", " << max_name_size << " goes to " << max_destination_size << " on " << yearofdepart << "/0" << monthofdepart << "/" << dayofdepart << endl;
            }
            else {
                cout << max_name_sizelast << ", " << max_name_size << " goes to " << max_destination_size << " on " << yearofdepart << "/" << monthofdepart << "/" << dayofdepart << endl;
            }
        }
    }

    const char * Traveler::name() const {
        return max_name_size, max_name_sizelast;
    }

    bool Traveler::canTravelWith(const Traveler& p) const {
        bool xday = (*this).dayofdepart == p.dayofdepart;
        bool xmonth = (*this).monthofdepart == p.monthofdepart;
        bool xyear = (*this).yearofdepart == p.yearofdepart;

        bool match = xday && xmonth && xyear;

        return match;
    }
}

Here is the main source file.
   #include <iostream>
#include "Traveler.h"

using namespace std;
using namespace sict;

int main()
{
    Traveler travelers[] = {
        Traveler(nullptr, "Smith", "Toronto", 2020,  4, 20),
        Traveler("",      "Smith", "Toronto", 2020,  4, 20),
        Traveler("John",  "",      "Toronto", 2020,  4, 20),
        Traveler("John",  "Smith", nullptr,   2020,  4, 20),
        Traveler("John",  "Smith", "",        2020,  4, 20),
        Traveler("John",  "Smith", "Toronto", 2020,  4, 20), // valid
        Traveler("John",  "Smith", "Toronto", 2028,  4, 20),
        Traveler("John",  "Smith", "Toronto", 2014,  4, 20),
        Traveler("John",  "Smith", "Toronto", 2022, 12, 31), // valid
        Traveler("John",  "Smith", "Toronto", 2020, 40, 20),
        Traveler("John",  "Smith", "Toronto", 2020,  0, 20),
        Traveler("John",  "Smith", "Toronto", 2019,  1,  1), // valid
        Traveler("John",  "Smith", "Toronto", 2020,  4,  0),
        Traveler("John",  "Smith", "Toronto", 2020,  4, 32),
        Traveler(nullptr, nullptr, nullptr,      0,  0,  0),
        Traveler("John",  "Smith", "Toronto"),               // valid
        Traveler()
    };
    cout << "----------------------------------------" << endl;
    cout << "Testing the validation logic" << endl;
    cout << "(only travelers 6, 9, 12 and 16 should be valid)" << endl;
    cout << "----------------------------------------" << endl;
    for (int i = 0; i < 17; ++i)
    {
        cout << "Traveler " << i + 1 << ": "
            << (travelers[i].isEmpty() ? "not valid" : "valid") << endl;
    }
    cout << "----------------------------------------" << endl << endl;

    Traveler david("David", "Davis", "Toronto", 2019, 6, 20);
    Traveler friends[] = {
        Traveler("Vanessa",  "Miller",  "Toronto", 2019,  6, 20),
        Traveler("John",     "Miller",  "Toronto", 2019,  6,  6),
        Traveler("Alice",    "Turner",  "Toronto", 2019, 10, 20),
        Traveler("Bob",      "Moore",   "Paris",   2019,  6, 20),
        Traveler("Jennifer", "Hill",    "Toronto", 2020,  6, 20),
        Traveler("Mike",     "Flores",  "Toronto", 2019,  6, 20),
        Traveler("Sarah",    "Stewart", "Toronto", 2019,  6, 20),
        Traveler("Mark",     "Simmons", "Toronto") <-- This part I need to solve
    };

    cout << "----------------------------------------" << endl;
    cout << "Testing Traveler::display(...)" << endl;
    cout << "----------------------------------------" << endl;
    for (int i = 0; i < 8; ++i)
        friends[i].display();
    cout << "----------------------------------------" << endl << endl;

    cout << "----------------------------------------" << endl;
    cout << "Testing Traveler::canTravelWith(...)" << endl;
    cout << "----------------------------------------" << endl;
    cout << david.name() << " can travel with: " << endl;
    for (int i = 0; i < 8; ++i)
    {
        if (david.canTravelWith(friends[i]))
            cout << "  - " << friends[i].name() << endl;
    }
    cout << "----------------------------------------" << endl << endl;

    return 0;
}

And here is my current output.
 ----------------------------------------
Testing the validation logic
(only travelers 6, 9, 12 and 16 should be valid)
----------------------------------------
Traveler 1: not valid
Traveler 2: not valid
Traveler 3: not valid
Traveler 4: not valid
Traveler 5: not valid
Traveler 6: valid
Traveler 7: not valid
Traveler 8: not valid
Traveler 9: valid
Traveler 10: not valid
Traveler 11: not valid
Traveler 12: valid
Traveler 13: not valid
Traveler 14: not valid
Traveler 15: not valid
Traveler 16: valid
Traveler 17: not valid
----------------------------------------

----------------------------------------
Testing Traveler::display(...)
----------------------------------------
Miller, Vanessa goes to Toronto on 2019/06/20
Miller, John goes to Toronto on 2019/06/06
Turner, Alice goes to Toronto on 2019/10/20
Moore, Bob goes to Paris on 2019/06/20
Hill, Jennifer goes to Toronto on 2020/06/20
Flores, Mike goes to Toronto on 2019/06/20
Stewart, Sarah goes to Toronto on 2019/06/20
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠π, ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠π goes to ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠π on 2019/07/01 <-- the problem
(The last one should be like this "Simmons, Mark goes to Toronto on 2019/07/01")
----------------------------------------

----------------------------------------
Testing Traveler::canTravelWith(...)
----------------------------------------
Davis can travel with:
  - Miller
  - Moore
  - Flores
  - Stewart
----------------------------------------

So can anyone point out what am I missing or what kind of problem that my code have?

A: The issue is with the constructor definition:
Traveler::Traveler(const char * travlerfirstname, const char * travelerlastname, const char * destination) {
    bool nameinvalid = travlerfirstname && travelerlastname == nullptr;
    bool destinvalid = destination == nullptr;
    bool invalid = nameinvalid && destinvalid;

    if (!invalid) {
        yearofdepart = 2019;
        monthofdepart = 7;
        dayofdepart = 1;
    }
}

Here, fields max_name_size, max_name_sizelast and max_destination_size are left uninitialized.
And the below call invokes exactly the same constructor:
Traveler("Mark", "Simmons", "Toronto") <-- This part I need to solve

Instead, you should do this:
Traveler::Traveler(const char * travlerfirstname, const char * travelerlastname, const char * destination) {
    bool nameinvalid = travlerfirstname && travelerlastname == nullptr;
    bool destinvalid = destination == nullptr;
    bool invalid = nameinvalid && destinvalid;

    if (!invalid) {
        strncpy(max_name_size, travlerfirstname, 15);
        strncpy(max_name_sizelast, travelerlastname, 15);
        strncpy(max_destination_size, destination, 31);
        yearofdepart = 2019;
        monthofdepart = 7;
        dayofdepart = 1;
    }
}

Suggestion:
Please learn about delegating constructors. This type of coding always hits you back later in the form of bugs and maintainability issues.


text:
Q: How can I work around a member not found error? I have a command where you are supposed to have 3 options:
1) Mention user
2) Enter user ID
3) Enter arbitrary name
In all 3 cases the bot should spit out the embed with the appropriate input.
In doing so it should:

*

*If it is a Discord user mark it in the description.

*If it is not a user just accept the entered name but send the embed anyway with the name in the description.

The normal way it works:
@client.command()
async def slap(ctx, *, member: discord.Member):
    if member is None:
        re = discord.Embed()
        re.title = "Du hast die Luft geschlagen, Idiot..."
        re.set_image(url="https://i.pinimg.com/originals/8f/f9/f9/8ff9f9b0e469f751f47fc0a995a172ad.gif")
        await ctx.send(embed=re)

    else:
        er = discord.Embed()
        er.title = "Das muss weh tun..."
        er.description = f"Du hast {member.mention} geschlagen!"
        er.set_image(url=random.choice(slapgif))
        await ctx.send(embed=er)

But if I input a random name it gives me the BadArgument error. How can I avoid that and also accept random names?
I tried:
user: str = None

This of course then gives only the ID when entered, but also names like I'mTest123 which is of course desired, but the with the ID should end in a member if this is on the server.

A: It gives the error since you specified the member argument to be a discord member, changing it to this should work:
    @client.command()
    async def slap(ctx, *, member=None):
       if member is None:
          re = discord.Embed()
          re.title = "Du hast die Luft geschlagen, Idiot..."
          re.set_image(url="https://i.pinimg.com/originals/8f/f9/f9/8ff9f9b0e469f751f47fc0a995a172ad.gif")
          await ctx.send(embed=re)

       else:
          er = discord.Embed()
          er.title = "Das muss weh tun..."
          er.description = f"Du hast {member.mention} geschlagen!"
          er.set_image(url=random.choice(slapgif))
          await ctx.send(embed=er)

Also if you want it to accept random names you can use isinstance() and type() functions in an if statement like this:
    @client.command()
    async def slap(ctx, *, member=None):
       if member is None:
           re = discord.Embed()
           re.title = "Du hast die Luft geschlagen, Idiot..."
           re.set_image(url="https://i.pinimg.com/originals/8f/f9/f9/8ff9f9b0e469f751f47fc0a995a172ad.gif")
           await ctx.send(embed=re)

        else:
           if isinstance(member, discord.Member): #checks if it's a discord.member
              er = discord.Embed()
              er.title = "Das muss weh tun..."
              er.description = f"Du hast {member.mention} geschlagen!"
              er.set_image(url=random.choice(slapgif))
              await ctx.send(embed=er)
           elif len(member) == 18 and type(int(member)) == int: #checks if it's an user ID
              member2 = await ctx.guild.fetch_member(int(member))
              er = discord.Embed()
              er.title = "Das muss weh tun..."
              er.description = f"Du hast {member2.mention} geschlagen!"
              er.set_image(url=random.choice(slapgif))
              await ctx.send(embed=er)
           else:
              er = discord.Embed()
              er.title = "Das muss weh tun..."
              er.description = f"Du hast {member} geschlagen!"
              er.set_image(url=random.choice(slapgif))
              await ctx.send(embed=er)


text:
Q: C++ AMP nested loop I'm working on a project that requires massive parallel computing. However, the tricky problem is that, the project contains a nested loop, like this:
for(int i=0; i<19; ++i){
    for(int j=0; j<57; ++j){
        //the computing section
    }
}

To achieve the highest gain, I need to parallelise those two levels of loops. Like this:
parallel_for_each{
    parallel_for_each{
        //computing section
    }
}

I tested and found that AMP doesn't support nested for loops. Anyone have any idea on this problem? Thanks

A: You could, as @High Performance Mark suggest collapse the two loops into one. However, you don't need to do this with C++ AMP because it supports 2 and 3 dimensional extents on arrays and array_views. You can the use an index as a multi-dimensional index.
array<float, 2> x(19,57);
parallel_for_each(x.extent, [=](index<2> idx) restrict(amp)
{
    x[idx] = func(x[idx]);
});

float func(const float v) restrict(amp) { return v * v; }

You can access the individual sub-indeces in idx using:
int row = idx[0];
int col = idx[1];

You should also consider the amount of work being done by computing section. If it is relatively small you may want to have each thread process more than one element of the array, x.
The following article is also worth reading as just like the CPU if your loops do not access memory efficiently it can have a big impact on performance. Arrays are Row Major in C++ AMP

A: So collapse the loops:
for(int ij=0; ij<19*57; ++ij){
        //if required extract i and j from ij
        //the computing section
    }
}


text:
Q: Creation of Column I am making a table of made up of two columns, but the problem is that in the last row I have multiple column with in a single row, I don't know how to do this. I applied \multicolumn but it did not produce the desired result. Here is an image of the desired table.

Help me in this regard

A: There are multiple ways to do this, but in your situation I think the best is to nest tabular environments. Try something like this:
\begin{tabular}{cc}
  \hline
  Heading & Heading \\
  \hline
  Item 1  & Item 2  \\
  Item 3  &
  \begin{tabular}{cc}
    A & B       \\
    C & D       \\
  \end{tabular} \\
  \hline
\end{tabular}

The above code will produce this table.
Add vertical rules as desired (although they should generally be avoided when possible).


text:
Q: to_timestamp to store time zone data I have two columns, one named "date" and the other named "time". Date is a date datatype and "time" is a character datatype. I'm using the following query to select a new combined timestamp column
SELECT
    to_timestamp(concat_ws(' ',air_date,air_time),'yyyy-MM-dd HH24:MI:SS') as datetime
FROM table1

This returns the correct timestamp but with "+00" timezone. I want to explicitly tell the query that the timezone is in "EST5EDT" so that I get either "+04" or "+05" for the timezones. I've tried the following but received an error
SELECT
    to_timestamp(concat_ws(' ',air_date,air_time,'EST5EDT'),'yyyy-MM-dd HH24:MI:SS TZ') as datetime
FROM table1

ERROR: "TZ"/"tz"/"OF" format patterns are not supported in to_date
SQL state: 0A000

How can I select a timestamp column with the EST5EDT time zone info contained within it?

A: If you just add yoru tz to timestamp cast, it will add appropriate amount of hours:
t=# select
  concat_ws(' ','2016-08-16'::date,'10:00:00'::time,'EST5EDT')::timestamptz
, concat_ws(' ','2016-08-16'::date,'10:00:00'::time)::timestamptz;
       concat_ws        |       concat_ws
------------------------+------------------------
 2016-08-16 14:00:00+00 | 2016-08-16 10:00:00+00
(1 row)

If I understand you right, you want same date and time with TZ "value" appended? Then this might help:
t=# set timezone = EST5EDT;
SET
t=# select
  concat_ws(' ','2016-08-16'::date,'10:00:00'::time,'EST5EDT')::timestamptz
, concat_ws(' ','2016-08-16'::date,'10:00:00'::time)::timestamptz;
       concat_ws        |       concat_ws
------------------------+------------------------
 2016-08-16 10:00:00-04 | 2016-08-16 10:00:00-04
(1 row)


text:
Q: unity android crash - UI LayoutUtility GetLayoutProperty When running my program on my android tablet, it will inconsistently crash when starting up, or just as I am about to share a screen shot to social media using a plugin.
The device I am using is on android kit kat 4.4 and I am building from unity 5.3.4.
I get the log file from Unity. I get these few lines before the program crashes

NullReferenceException: Object reference not set to an instance of an object
  at UnityEngine.UI.LayoutUtility.GetLayoutProperty (UnityEngine.RectTransform rect, System.Func`2 property, Single defaultValue, ILayoutElement& source) [0x00000] in :0
at UnityEngine.UI.LayoutUtility.GetLayoutProperty (UnityEngine.RectTransform rect, System.Func`2 property, Single defaultValue) [0x00000] in :0
at UnityEngine.UI.LayoutUtility.GetMinHeight (UnityEngine.RectTransform rect) [0x00000] in :0
at UnityEngine.UI.LayoutUtility.GetMinSize (UnityEngine.RectTransform rect, Int32 axis) [0x00000] in :0
at UnityEngine.UI.HorizontalOrVerticalLayoutGroup.CalcAlongAxis (Int32 axis, Boolean isVertical) [0x00000] in :0

Is there any solution to this issue?
thanks in advance
-phil

A: Your issue is that the layout you are accessing is null. Check that you find/set the proper element in the inspector.
Thanks.


text:
Q: bug change recurring google calendar event visibility from private back to default If I have a google calendar event with a resource invited, set its visibility to private for all events, save, and then set it back to "default".  It results in the resource not reverting back to default.  Furthermore, if I try to change the event in the resource's calendar to default, the change again is not propagated.
Another weird thing I've noticed is that if you then remove the resource, and re-add it, it comes back with the same visibility + status.
Same thing happens in the UI.
Seems like a bug on the back-end.  Any ideas?


text:
Q: Update a MySQL table from an HTML table with thousands of rows I have an html file on network which updates almost every minute with new rows in a table. At any point, the file contains close to 15000 rows I want to create a MySQL table with all data in the table, and then some more that I compute from the available data.
The said HTML table contains, say rows from the last 3 days. I want to store all of them in my mysql table, and update the table every hour or so (can this be done via a cron?)
For connecting to the DB, I'm using MySQLdb which works fine. However, I'm not sure what are the best practices to do so. I can scrape the data using bs4, connect to table using MySQLdb. But how should I update the table? What logic should I use to scrape the page that uses the least resources?
I am not fetching any results, just scraping and writing.
Any pointers, please?

A: My Suggestion is instead of updating values row by row try to use Bulk Insert in temporary table and then move the data into an actual table based on some timing key. If you have key column that will be good for reading the recent rows as you added.

A: You can adopt the following approach:
For the purpose of the discussion, let master be the final destination the scraped data.
Then we can adopt the following steps:

*

*Scrape data from the web page.

*Store this scraped data within the temporary table within MySQL say temp.

*Perform an EXCEPT operation to pull out only those rows which exist within the master but not in temp.

*persist the rows obtained in step 3 within the master table.

Please refer to this link for understanding how to perform SET operations in MySQL. Also, it would be advisable to place all this logic within a store procedure and pass it the set of the data to be processed ( not sure if this part is possible in MySQL)
 Adding one more step to the approach - Based on the discussion below, we can use a timestamp based column to determine the newest rows that need to be placed into the table. The above approach for SET based operations works well, in case there are no timestamp based columns.


text:
Q: cannot use custom object mapper for single objects in jersey (works for collections) I'm using the latest release of Jersey (2.13) on a glassfish server together with the latest version of jackson (version. 2.4) . I've written and registered a custom ObjectMapper, but it only collections seems to be serialized by my custom objectmapper.
I've seen a similar issue at this page: https://java.net/jira/browse/GLASSFISH-20815
but the workaround presented there did not work for me.
My jersey mapper provider class:
@Provider
public class JerseyMapperProvider implements ContextResolver {
private static ObjectMapper apiMapper = null;

public JerseyMapperProvider() {
}

@Override
public ObjectMapper getContext(Class<?> type) {
    System.out.println(type.toString() + " this is only printed for collections...");
    if (apiMapper == null) {
        apiMapper = getDefaultObjectMapper();
    }
    return apiMapper;
}

...

A: okay, suddenly it worked by adding the following features to my resourceConfig...
@ApplicationPath("/")

public class JerseyConfig extends ResourceConfig {

public JerseyConfig() {
    super();
    Map<String, Object> map = new HashMap<>();
    map.put(CommonProperties.MOXY_JSON_FEATURE_DISABLE, true);
    map.put(CommonProperties.JSON_PROCESSING_FEATURE_DISABLE, true);
    addProperties(map);
    ....// more configuration here..

}
}


text:
Q: How to call lame executable from Android? I downloaded LAME for Windows. It have two files, one is lame_enc.dll and another is lame.exe.
I want to convert an MP3 file from 320kbs to 128kbs.
In Windows I use command line: C:\Lame\lame.exe --preset cbr 128 "320.mp3" "128.mp3" - it works good. My question is how can I call lame.exe from my Android project? And what steps must I take to achieve that?
Thank you for your replies!

A: You can't just "run lame executable from Android", because Android does not run Windows' executable files. Analogical you are not able to run MacOS applications in Windows without converting them/using emulator/etc.
I advice you to use something different than LAME for this job - I haven't used any of such, so I can't reccomend you anything right now.
EDIT
It seems that you may also easily port LAME for Android - Lame MP3 Encoder compile for Android

A: You can't call Windows executable files in Android, because they have different architecture.
It easy to understand, you can't run apk file on Windows if you don't have any converting or simulation softwares.
You can use extended libraries such as ffmpeg, lame to change bitrate of mp3 files. You can access this link to build shared library in Android:
http://developer.samsung.com/android/technical-docs/Porting-and-using-LAME-MP3-on-Android-with-JNI


text:
Q: replace string to space without using built in class or method I have
String  url =" http://@50stackoverflow.com/questions/@50724043/@50xyz.html "

I want to replace @50 to space without using built in class or function.
What I want is
String url =" http:// stackoverflow.com/questions/ 724043/ xyz.html "

A: This is a very weird question, why not using the tools java have?
is "for" is build in? is String is build in?
any way, is this good enough not-java-solution? (please don't use this code anywhere)
char[] url = "http://@50stackoverflow.com/questions/@50724043/@50xyz.html".toCharArray();
    String output = "";
    int i;
    for (i = 0; i < url.length - 3; i++) {
        if (url[i] == '@' && url[i+1] == '5' && url[i+2] == '0') {
            output += " ";
            i+=3;
        } else {
            output += url[i];
        }
    }
    for (;i < url.length; i++) {
        output += url[i];
    }
    System.out.println(output);

A: Try this
char[] realString = "http://@50stackoverflow.com/questions/@50724043/@50xyz.html".toCharArray();
String newString = "";
for (int i = 0; i < realString.length; i++) {
    if (i<realString.length-2 && realString[i] == '@' && realString[i+1] == '5' && realString[i+2] == '0') {
        newString = newString + " ";
        i=i+3;
    } else {
        newString = newString + realString[i];
    }
}
System.out.println(newString);


text:
Q: Gensim framework: Saving and storing word2vec keyed vectors I'am using the word2vec model and I have a problem with storing and reading it.
import gensim.models.keyedvectors as w2v
from gensim.models import KeyedVectors

word_vectors = w2v.wv
word_vectors.save(filepath + "Vectors.bin")

m = word2vec.KeyedVectors.load_word2vec_format(filepath + "Vectors.bin", binary=True)

I get following error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte

In the following way the laoding will work:
vectors = KeyedVectors.load(filepath + "Vectors.bin", mmap='r')

But If I then call
vectors.similar_by_word("cat")

I get following error:
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
What am I doing wrong?
How can I use the save_word2vec_format() function?

A: Your initial block of code that does import gensim.models.keyedvectors as w2v and word_vectors = w2v.wv doesn't make much sense.
Read literally, that is assigning the full Python code module gensim.models.keyedvectors to the variable w2v. That module isn't going to have a .wv property, so I wouldn't expect word_vectors = w2v.wv to even execute. It certainly wouldn't result in word_vectors then being an actual set of trained-up word-vectors, unless there's a bunch of other training code you're not showing.
Are you sure the code in your question is representative of what you're actually doing?
Nevertheless, if you did succeed in getting word_vectors to hold one of gensim's KeyedVectors objects, filled with word-vectors you want to save, you then have two choices:

*

*To save the word-vectors in the same format as was used by Google's original word2vec.c release, you can use the .save_word2vec_format(path, ...) method. Then, to later reload those vectors, you'd use the matched reloaded_vectors = KeyedVectors.load_word2vec_format(path, ...) method.

*To save the word-vectors in gensim's own Python-based format, you can use the .save(path) method. Then, to later reload those vectors, you'd use the matched reloaded_vectors = KeyedVectors.load(path) method. This approach may save a little more info (if it's present from your training), such as word-counts. For efficiency with larger objects, it may store the bulk of the vectors into a separate file, which should be kept alongside the main path file if you move the files elsewhere, and allows the option (but not the requirement) of using mmap options later.
You can't mix and match these formats: a file saved by save_word2vec_format() can only be read by load_word2vec_format(), and a file saved by save() can only be read by load().
Regarding your other TypeError, there's not enough info to speculate what's gone wrong. You'd need to edit your answer to add more details, and make the demonstrating code self-consistent.
For example, you show loading into a variable named vectors, but then an operation on a variable called model. This discrepancy hints the problem might be some other mismatch in your un-shown code.
Similarly, if you encounter any error, you should quote exactly the error message and full error stack reported into your question, so answerers can see exactly which lines of code, in your code and the libaries you are relying on, are involved in exactly your error. (This usually helps finger exactly the place where your expectations/code deviate from the library's requirements.)


text:
Q: Combining @SqsListener and @RequestMapping We're currently in the middle of migrating our current architecture into Spring-AWS-based microservices. One of my tasks is to research on how our microservices communicate with one another. I'm aiming to set-up a hybrid system of RESTful HTTP endpoints and SQS producers and consumers.
As an example, I have the below code:
@SqsListener("request_queue")
@SendTo("response_queue")
@PostMapping("/send")
public Object send(@RequestBody Request request, @Header("SenderId") String senderId) {
    if (senderId != null && !senderId.trim().isEmpty()) {
        logger.info("SQS Message Received!");
        logger.info("Sender ID: ".concat(senderId));
        request = new Gson().fromJson(payload, Request.class);
    }

    Response response = processRequest(request); // Process request

    return response;
}

Theoretically, this method should be able to handle the following:

*

*Receive a Request object via HTTP

*Continually poll the request_queue for a message containing the Request object

As an HTTP endpoint, the method returns no error. However, as an SQS listener, it runs into the following exception:
org.springframework.messaging.converter.MessageConversionException:
    Cannot convert from [java.lang.String] to [com.oriente.salt.Request] for
    GenericMessage [payload={"source":"QueueTester","message":"This is a wonderful
    message send by queue from Habanero to Salt. Spicy.","msisdn":"+639772108550"},
    headers={LogicalResourceId=salt_queue, ApproximateReceiveCount=1,
    SentTimestamp=1523444620218, ....

I've tried to annotate the Request param with @Payload, but to no avail. Currently I've also set-up the AWS config via Java, as seen below:
ConsuerAWSSQSConfig.java
@Configuration
public class ConsumerAWSSQSConfig {

@Bean
public SimpleMessageListenerContainer simpleMessageListenerContainer() {
    SimpleMessageListenerContainer msgListenerContainer = simpleMessageListenerContainerFactory()
            .createSimpleMessageListenerContainer();
    msgListenerContainer.setMessageHandler(queueMessageHandler());
    return msgListenerContainer;
}

@Bean
public SimpleMessageListenerContainerFactory simpleMessageListenerContainerFactory() {
    SimpleMessageListenerContainerFactory msgListenerContainerFactory = new SimpleMessageListenerContainerFactory();
    msgListenerContainerFactory.setAmazonSqs(amazonSQSClient());
    return msgListenerContainerFactory;
}

@Bean
public QueueMessageHandler queueMessageHandler() {
    QueueMessageHandlerFactory queueMsgHandlerFactory = new QueueMessageHandlerFactory();
    queueMsgHandlerFactory.setAmazonSqs(amazonSQSClient());
    QueueMessageHandler queueMessageHandler = queueMsgHandlerFactory.createQueueMessageHandler();
    List<HandlerMethodArgumentResolver> list = new ArrayList<>();
    HandlerMethodArgumentResolver resolver = new PayloadArgumentResolver(new MappingJackson2MessageConverter());
    list.add(resolver);
    queueMessageHandler.setArgumentResolvers(list);
    return queueMessageHandler;
}

@Lazy
@Bean(name = "amazonSQS", destroyMethod = "shutdown")
public AmazonSQSAsync amazonSQSClient() {
    AmazonSQSAsync awsSQSAsync = AmazonSQSAsyncClientBuilder.standard().withRegion(Regions.AP_SOUTHEAST_1).build();
    return awsSQSAsync;
}
}

What do you guys think?


text:
Q: how to combine result of select statement to the other table with different database I'm having a hard time to combine the result my select statement to the other table with different database.
This is one of my select statement and it works fine:
Database name "LIS" table "Legal_Records"
Select CaseNo,Judicial_level,Received_date,Due_Date, (SELECT Max(cast(Due_date as datetime)) FROM Legal_Records subc WHERE subc.CaseNo=c.CaseNo Group by c.CaseNo) AS MaxDue_Date from Legal_Records c

Result :

Here is the other Query and it also works fine:
Database name : "Pandimandata2002" Table name : "tblCrew"
Select CaseNo, Lastname,Vessel,Status from tblCrew where Pandimandata2002.dbo.tblCrew.CaseNo like '%CRW%' and (Status not like '%clos%' and Status not like '%settl%' and Status not like '%ca%cel%') and Status like '%court%' and ClubCode like '%TR%'

Result:

What i want to do is Add the column name "Judicial_level" from database "LIS" table "Legal_Records" to table "tblCrew" database "Pandimandata2002" when the CaseNo match to the other table.
I hope I made myself clear! thank you..

A: Select lr.Judicial_level, tc.*
FROM LIS.dbo.Legal_Records lr
INNER JOIN Pandimandata2002.dbo.tblCrew tc
ON lr.CaseNo = tc.CaseNo


text:
Q: Function for extracting the smallest value from data set [MATLAB] I have already made a function which extracts all temeperatures from a data-set for a certain time for a given month and year.
Which looks like:  exctractperiod(data, year, month, time)
This will as previously said extract all temperatures for a particular month at a time say 1400.
I now want to find a minimum temperature for a certain month say january across many years. For example if I look at the month january between the year 1997 and 2006. Now I want the lowest registered temperatue for Janauary between 1997-2006.
My progress so far is the code below:
function [algo] = getMiniserieone(data, startYear, endYear, time)

v = zeros(12,2);

for month = 1:12
  for year  = startYear:1:endYear

     p = extractperiodtwo(data, year, month, time);

     q = min(p);

    v(month,1) = v(month,1) + q;
    v(month,2) = v(month,2) + 1;

    algo = v(12,2);
  end
end
end

I do however get the error message:
    Unable to perform assignment because the size of the left side is
   1-by-1 and the size of the right
    side is 0-by-1.

When calling the function in the command window:
>> getMiniserieone(data, 1996, 2006, 1400)

Error in getMiniserieone (line 12)
    v(month,1) = v(month,1) + q;

But I have not been able remedy this.
My intention with the program above is to lets say for the years between 1996-2006 for a particular time extract the lowest temperature for all months between January and December. Meaning that between the years 1996-2006 for january for a certain time, say 1300, I want the lowest temperature for that month at that time. Then store it in my vector v column 1, column 2 will then denote the month.
My question is how I can fix this, i'm not really sure what the error message means? Does it maybe mean that q is not a single element value?
I hope the information given was ample enough to understand the problem, if not feel free to ask.

As requested, the code for extractPeriod()
function [mdata] = extractperiodtwo(data, year, month, time)

x = year*100 +month;

k = find( floor(TEMPUF(:,1)/100) == x & (data(:,2)==time));

mdata = data(k,3);

end

A: So there's two issues that you're running into. The first is the case when your extractperiodtwo() function doesn't find a value it returns a empty vector. You may write a check into the loop that reports that no data was found for a given entry and handles the error. I recommend a try-catch block (which I implement in the code below). The second issue has to do with how you're storing the minimum for each iteration.
Here is my solution:
function [algo] = getMiniserieone(data, startYear, endYear, time)
  %initialize output
  algo = [zeros(12,1), (1:12)']; %col1 = min(temps), col2 = month
  % loop through months
  yearsToTest = startYear:1:endYear;

  for month = 1:12
    %initialize a year storage, i.e. on the first iteration
    % this will be january minimum temps from startYear:endYear,
    % on iteration 2, it will be all february temps from startYear:endYear
    % and so on until it completes month == 12.
    lowTempsOverYears = nan(1,length(yearsToTest));

    for yearNum = 1:length(yearsToTest)
      %edit: forgot to paste this line, sorry.
      year = yearsToTest(yearNum);

      p = extractperiodtwo(data, year, month, time);

      q = min(p);

      try
        %try appending the min
        lowTempsOverYears(yearNum) = q;
      catch
        fprintf(2, ...
          '\nNo data found for month=%d, year=%d.\n  Skipping...\n', ...
          month, ...
          year);
      continue
      end
    end
    % inner loop is over, now we need the minimum of mins for the month
    algo(month, 1) = min(lowTempsOverYears,[],'omitnan');
  end

end

So what i've done is added a second vector, lowTempsOverYears that tracks the min(p) for each month over the startYear:endYear interval. Then I get the minimum of that and store it in the corresponding row of the month, in the output variable. I initialize lowTempsOverYears with nan() because it allows me to later take the min() with the 'omitnan' flag set to true, effectively ignoring any nan that appear in the vector.
Alternatively
You could capture all the temps over the years and months in a matrix and then perform the statistic of your choice. For example, the inside of your function could be:
function algo = getMiniserieone(data, startYear, endYear, time)
    algo = [zeros(12,1), (1:12)'];
    yearsToTest = startYear:1:endYear;
    % create local storage of values as matrix
    v = nan(12,length(yearsToTest));
    %loop
    for month = 1:12
      for yearNum = 1:length(yearsToTest)
        % current year to gather data from
        year = yearsToTest(yearNum);
        % p could be scalar, vector, empty
        p = extractperiodtwo(data, year, month, time);
        % q is scalar or empty
        q = min(p);
        try
          %try inserting the min temp
          v(month,yearNum) = q;
        catch
          fprintf(2,'\nNo data at month=%d, year=%d.\n  Skipping...\n', ...
            month, year ...
            );
        continue
        end
      end
    end
    % now all data is stored in a matrix perform statistic
    algo(:,1) = min(v, [], 2, 'omitnan');
end


text:
Q: React TypeScript: How to clear an input field const emailInput = document.getElementById("loginEmail");
emailInput.value = ''
...
<input
  id="loginEmail"
  value={state.email}
  type="input"
  className="input-text"
  name="email"
  placeholder={txt.emailAddress}
  onChange={formValue}
></input>

The error I'm getting on line 2 in the example above is `Property 'value' does not exist on type 'HTMLElement'.ts(2339)
`

A: This is how you should control the value of input in React
<input
  id="loginEmail"
  value={this.state.email}
  type="input"
  className="input-text"
  name="email"
  placeholder={txt.emailAddress}
  onChange={formValue}
></input>

In order to clear a value:
this.setState({
  email: ''
});

A: You have to assign the value for input element. To clear the value just reset the state variable.
this.setState({ email: "" });

Here is the small code for you
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputVal: "Clue Mediator"
    };
    this.onInputChange = this.onInputChange.bind(this);
    this.clearInput = this.clearInput.bind(this);
  }

  clearInput() {
    this.setState({ inputVal: "" });
  }

  // handle input change event
  onInputChange(e) {
    this.setState({ inputVal: e.target.value });
  }

  render() {
    return (
      <>
        <input
          placeholder="Enter your value here..."
          value={this.state.inputVal}
          onChange={this.onInputChange}
        />
        <input type="button" value="clear" onClick={this.clearInput} />
      </>
    );
  }
}

Here is the working demo for you
https://codesandbox.io/s/autumn-darkness-rybj2
Hope this will work for you!


text:
Q: Convert separate date and time to timestamp in React How can I convert date and time which are collected separately into a timestamp in react?
Currently, I'm changing the input type to date onFocus and time is collected the same way. I want to combine these 2 and make a timestamp. Any ideas?
<input
   placeholder="Pickup Date"
   onFocus={this.handleDate}
   type="text"
   id="pickupDate"
   onChange={this.handleChange}
   required />

A: Maybe the question is, how to do that with javascript, take a look on that:
Combine date and time string into single date with javascript
the most voted answer. These values you can take inside the handleDate method and you combine with your time value to apply the new Date(date + ' ' + hour)

A: if i understood clearly question you can use moment.js library
import moment from 'moment'

const date = '2019/02/02'
const time = '12:20'
const timestamp = moment.utc(`${date} ${time}`).unix()

A: Be more specific about what you want
Send picture or code


text:
Q: Understanding java memory management (Spring boot framework) I am running a Bulk API in Java (Spring boot Framework). I see in kubernetes memory and CPU usage is continuously increasing.
My code is like this:
  function(list <ids>){
       for each id in ids{

          expensiveFunction(id);

      }
  }

  expensiveFunction(id){
   //bring lot of data
    // process data
   //save data in db(transactional)
     }

So, I believe when expensive function is completed for one ID, memory(lot of data objects) should be released(Java's automatic Garbage Collection).
So, why is memory increasing continuously?
How can I avoid it, as it causing throttling of memory resulting in termination of application.
Is this is something to do with hiberante like caching data or something?


text:
Q: Error "Invalid job id" when DAG is triggered manually from UI using BigQueryInsertJobOperator I am trying to trigger a stored procedure from composer using "BigQueryInsertJobOperator". The Dag runs fine when triggered as per schedule but it fails with below error when it is triggered manually from Airflow UI.
Invalid jobID"airflow_DQ_create_stored_procedure_2021_11_02T01_36_02.229065_00_00_XXXXXXXXXXXXXXXXXX". Job IDs must be alphanumeric (plus underscores and dashes) and must be at most 1024 characters long.
There are alphanumeric and '_' only in the job id created. It is not 1024 characters long.
Both Manual triggering and scheduled triggering should be possible. Please help!
EDIT-1:
It works if we configure job id from our end. But, it throws error if BQ automatically generates the job id.
Below is the code snippet:
from airflow import models
from airflow.providers.google.cloud.operators.bigquery import BigQueryInsertJobOperator

yesterday = datetime.datetime.combine(
    datetime.datetime.today() - datetime.timedelta(1),
    datetime.datetime.min.time())

default_dag_args = {
    'start_date': yesterday
}

with models.DAG(
'DQ_create',
schedule_interval ='@daily',
default_args = default_dag_args
) as dag:

    Stored_Procedure = BigQueryInsertJobOperator(
        task_id='stored_procedure',
        configuration={
        "query": {
                "query": "CALL `project.dataset.procedure`() ",
                "useLegacySql": False,
            }
},
)

Stored_Procedure```

A: You've found a bug in the BigQueryInsertJobOperator class. This class is responsible for constructing the job_id, which it does by taking the values of your DAG variables and concatenating them:
  exec_date = context['execution_date'].isoformat()
  job_id = f"airflow_{self.dag_id}_{self.task_id}_{exec_date}_{uniqueness_suffix}"

The "execution_date" you're using appears to have millisecond-level accuracy, which makes the exec_date variable have a period in it.
You have four options to fix this:

*

*create a subclass of BigQueryInsertJobOperator that truncates its execution_date down to the second before it calls super().execute(context). The resulting job_id string will have no period.

*create a subclass of BigQueryInsertJobOperator that dynamically generates a unique job_id before it calls super().execute(context)

*schedule your DAG to run at the top of minute (or at least the top of the second!), thereby forcing your execution_date to not have millisecond accuracy

*upgrade to Airflow v2.0. They've fixed this bug by stripping out the period.(https://github.com/apache/airflow/commit/47b05a87f004dc273a4757ba49f03808a86f77e7#diff-529929b4ca60ce73b8da0f45d8a5c43c2d4e391b913fe78b39892899f812951e)


text:
Q: PHP pass a variable to Class and use it as prefix for constant or variable I have set a global variable $lang ($lang = 'de'), is there a way how I could get "Hallo!" by using, I'm using PHP 7.3:
L::HELLO('Mike');?

I'm not looking for a solution like:
sprintf(constant('L::' . $lang . '_HELLO'), 'Mike');

instead to got them by calling only:
L::HELLO('Mike');

or:
L::HI;

actual Class (I can change const by var if this would help or initiate class with set language):
<?php class L {
    const en_HELLO = 'Hello %s!';
    const de_HELLO = 'Hallo %s!';
    const fr_HELLO = 'Bonjour %s!';
    const it_HELLO = 'Ciao %s!';
    const en_HI = 'Hi...';
    const de_HI = 'Hi...';
    const fr_HI = 'Hi...';
    const it_HI = 'Hi...';

    public static function __callStatic($string, $args) {
        return vsprintf(constant("self::" . $string), $args);
    }
}

A: There are two ways I can see for this.  The first is the simplest - but also I would normally not recommend it.
This uses global to allow you to access the variable you already have and includes it as part of the key used to display the constant...
public static function __callStatic($string, $args) {
    global $lang;
    return vsprintf(constant("self::" .$lang."_" . $string), $args);
}

So
$lang = "de";
echo L::HELLO('Mike');

gives
Hallo Mike!

The second method involves setting the language into your class, so it's an extra step, but it's also more flexible (IMHO)...
class L {
    const en_HELLO = 'Hello %s!';
    const de_HELLO = 'Hallo %s!';
    const fr_HELLO = 'Bonjour %s!';
    const it_HELLO = 'Ciao %s!';

    protected static $lang = "en";

    public static function setLang ( string $lang )  {
        self::$lang = $lang;
    }

    public static function __callStatic($string, $args) {
        return vsprintf(constant("self::" .self::$lang."_" . $string), $args);
    }
}

So then you use it as...
$lang = "de";
L::setLang($lang);
echo L::HELLO('Mike');


text:
Q: Firebase Admin SDK network app/network-error I have the following nodejs script.
const admin = require("firebase-admin")

admin.initializeApp({
  credential: admin.credential.cert("./serviceAccountKey.json"),
  databaseURL: "https://<ProjectID>.firebaseio.com/"
})

const uid = "5mP5FvjjCKcJ1IBXfV3rpChd3ob2"

admin
  .auth()
  .setCustomUserClaims(uid, { role: 'admin' })
  .then(() => {
    // The new custom claims will propagate to the user's ID token the
    // next time a new one is issued.
    console.log(`Admin claim added to ${uid}`)
  })
  .catch((err) => console.log(err))

When I run the script I get the following error.
{
  errorInfo: {
    code: 'app/network-error',
    message: 'Error while making request: connect ECONNREFUSED 127.0.0.1:9099. Error code: ECONNREFUSED'
  },
  codePrefix: 'app'
}

What am I doing wrong here?
Also, my firebase project has the spark plan.


text:
Q: How to get user in systemd unit who caused an event Is it possible to get the name of an active user in systemd units? I guess I could parse output of who or do something like that, but I believe there should be a native way of doing that in systemd.
I also know there is logind which tells me a bit more information about the users, but if there were more seats, I would like to know who the single user who caused the event was, e.g. if someone wrote systemctl suspend to only lock his session at his seat and let the computer handle all the other seats. It is probably not the best example but I hope it illustrates the problem better, I only want the one user who caused systemd units to run.
Namely I wanted to create a systemd unit that will lock the user's current session when going to sleep and right now I resorted to trying to lock all sessions. I believe this to be a bad solution and would like to know how to do this properly.

A: I was wrong and now I know it. Everything systemd oriented is run by root and I just thought it was not because of some experiments I have done earlier.
There is no way to figure out who is sitting at the computer, I can only get the full list of logged users.


text:
Q: How do I load a Vue template from a hosted html file (no webpack, etc) I am trying a new way of writing my ui and I am using straight ESM loading with Vue. As such I am trying to load my HTML files like I would with say Webpack. I have a simple example of what I am talking about. I basically want to take...
export default {
    template: "
Here is the component. I want this template to be an html file without webpack
"
    // I want this to be from a url say mysite.net/viewport.html
}

I tried the simple things like
import Template from "/viewport.html"

But of course that didn't work
I think there might be something I can do with dynamic components. Has anyone tried this an come up with a good solution?


text:
Q: A place where clever questions that are flagged as off-topic/not-a-real-question can be migrated to?
Possible Duplicate:
Where can I ask questions that don't fit or are off-topic for Stack Overflow?

I know the Stack Exchange Q&As are a place for people to ask questions that have definitive answers. I had to put that out there in advance.
My question deals with what the best way is to address how it makes someone feel to contribute something, maybe even for the first or second time, and be met with overwhelming rejection. I don't mean someone asking for solutions to their homework through the Q&A, but users who contributed something that is off-topic, but that would make a very nice blog post.
Being a freshman in the Stack Exchange Q&As myself, I vividly remember an experience early on that almost put me off Stack Exchange for good.
Inspired by some of the questions that where the most popular at the time ("Great programming quotes" and the likes, which seem to have been deleted since,) I contributed an off-topic question that was met with harsh words telling me what Stack Exchange is and what it isn't. At the time I felt like there was a double standard, where seasoned members could get away with contributing off-topic blog bits, and newcomers where publicly hanged for it. It seems like that double standard is being addressed since those very popular questions like "Great programming quotes" are being deleted, but aren't we losing something in the process? First of all, we lose those posts that many users found amusing/entertaining/eye-opening. But we also might lose new talent, that maybe haven't figured out what exactly Stack Exchange websites are for specifically, but want to give back to the community with a well-thought-out comment/joke/..., maybe because they can't answer questions themselves yet, since that in itself is quite competitive, at least on Stack Overflow.
So here comes my question:
Could you guys envision a place where clever questions that are flagged as off-topic or not-a-real-question can go to be appreciated (maybe without gaining experience for them?) Posts that new talent has created could be moved to that place, without hurting someone's feelings, and we could all enjoy the posts.

A:
Could you guys envision a place where clever questions that are flagged as off-topic or not-a-real-question can go to be appreciated (maybe without gaining experience for them?)

You answered your own question.

...but users who contributed something that is off-topic, but that would make a very nice blog post.

As to

...how it makes someone feel to contribute something, maybe even for the first or second time, and be met with overwhelming rejection.

Closing a question isn't overwhelming rejection.  The reason that a question is closed is spelled out along with a link to the FAQ, so new users who don't quite get what Stack Exchange is about yet have a chance to learn.  They are encouraged to try and improve their question to fit within site guidelines so that it might be reopened and answered.


text:
Q: UMVUE estimates of uniform distribution mean and width Given are the uniformly distributed samples
$$x_n \overset{\text{iid}}{\sim} \mathcal{U}\left(\mu-\frac{w}{2}, \mu+\frac{w}{2}\right)$$
for $n = 1 \ldots N$.Then the UMVUE estimates of $\mu$ and $w$ are
\begin{align}
\hat\mu = \frac{1}{2} \Big( \max \{ x_n \} + \min \{ x_n \} \Big)
\end{align}
and
\begin{align}
\hat{w} = \frac{N+1}{N-1} \Big( \max \{ x_n \} - \min \{ x_n \} \Big).
\end{align}
I know that this is correct but even with an extensive search I could not find a specific source for this very statement or a short proof of it. Although I found/derived a lot of related information, e.g., that $(\min \{ x_n \}, \max \{ x_n \})$ constitutes a complete sufficient statistic, the ML estimates, and relation to the german tank problem. But not this specific thing.
If you could provide me with a source or a short proof, that'd be amazing. Thank you.

A: By the Lehmann-Scheffe theorem, unbiased estimators that are functions of complete and sufficient statistics are UMVUEs. So it suffices to check that $\hat{\mu}$
and $\hat{w}$ are unbiased. This can be done by writing $X_i = w (U_i-1/2) + \mu$ where $U_i\sim Unif(0,1)$ and noting that $U_{(i)} \sim Beta(i, n-i+1)$.

A: After finding a complete sufficient statistic, there isn't much to do. The main work has been done.
Suppose we have $X_j\stackrel{\text{i.i.d}}\sim\mathcal U\left(\mu-\frac{\omega}{2},\mu+\frac{\omega}{2}\right)$ for $j=1,2,\cdots,n$.
Denote $\displaystyle X_{(1)}=\min_{1\le k\le n} X_k$ and $\displaystyle X_{(n)}=\max_{1\le k\le n} X_k$.
Now, $(X_{(1)},X_{(n)})$ is complete sufficient for $(\mu,\omega)$. So we only need to find unbiased estimators of $\mu$ and $\omega$ which are functions of the complete sufficient statistic. By the Lehmann-Scheffe theorem, those unbiased estimators are bound to be the UMVUE.
Define $Y_j=\frac{X_j-(\mu-\omega/2)}{\mu+\omega/2-(\mu-\omega/2)}=\frac{X_j-\mu+\omega/2}{\omega}$, so that $Y_j\stackrel{\text{i.i.d}}\sim\mathcal U(0,1)$ for all $j=1,2,\cdots,n$.
Note that the parameter space is given by $\mu+\frac{\omega}{2}>\mu-\frac{\omega}{2}\implies-\infty<\mu<\infty\,,\,\omega>0$.
Knowing that the $r$th order statistic $Y_{(r)}\sim\mathcal{Be}(r,n-r+1)$, we immediately have $E(Y_{(r)})=\frac{r}{n+1}$, i.e., $E\left(\frac{X_{(r)}-\mu+\omega/2}{\omega}\right)=\frac{r}{n+1}$. Thus,
$$E(X_{(1)})=\frac{\omega}{n+1}-\frac{\omega}{2}+\mu\tag{1}$$  $$E(X_{(n)})=\frac{n\omega}{n+1}-\frac{\omega}{2}+\mu\tag{2}$$
Since we only need the expectations of $X_{(1)}$ and $X_{(n)}$, we could have found them directly from the respective densities also. But this was easier.
Simply adding and subtracting equations $(1)$ and $(2)$ we solve for $\mu$ and $\omega$ :
$$E\left[\frac{X_{(1)}+X_{(n)}}{2}\right]=\mu$$ and
$$E\left[\frac{n+1}{n-1}\left(X_{(n)}-X_{(1)}\right)\right]=\omega$$
This proves the claim.
(The question seems to have an extra $1/2$ factor for the UMVUE of $\omega$ though).
Although it is certainly not required for the problem at hand, to directly apply Lehmann-Scheffe, it can be shown that as $X_1$ is unbiased for $\mu$, UMVUE of $\mu$ is $E(X_1\mid X_{(1)},X_{(n)})=\frac{X_{(1)}+X_{(n)}}{2}$.


text:
Q: Films/Series that are extremely good to understand (and that are not...) Some time ago I asked "Why are movies so hard to understand (and what can you do about it)?"
To my surprise even many native speakers answered that they had difficulties understanding some movies and series.
My question:
Which films/series do you think are extremely good to understand (I don't mean learning videos or the like but "normal" films/series)
I for myself often find many of the Star Trek episodes (e.g. Voyager) very good to understand. Counterexamples, which are even for native speakers incomprehensible, are also welcome.

A: As a TV series maniac and a person who learns English, I would like to recommend to watch almost any sitcoms, such as "Friends", "How I met your mother", "Two and a half men". Also, "Futurama" and "Lost" were surprisingly easy to understand.

A: I think biopics can be wel understood. I used "Gifted hands" successfully with my elementary students (very good students, though).

A: Whenever it is available, you can try to use English subtitles (if possible, not those for the hearing-impaired).
Although hardly any subtitles are always exactly accurate, the visual feedback to what you (think) you are hearing really helps a lot in getting accustomed to the spoken language.
I have used this a lot (being in the lucky position that I get BBC with the "page 888 - subtitles option), and although it may take some effort to get used to reading while you are watching the film, you will find it easier to follow eventually.
Especially when it comes to (uncommon) names, I found that seeing the name written caused a lot less distraction when trying to understand the rest of the dialogue.

A: Go for Seinfeld. Simple language, plain story-line and pretty enjoyable. http://www.imdb.com/title/tt0098904/

A: There is another way to use films for learning language. It is a bit difficult to find scripts of films, I mean printed scripts of films, not scripts that you find as download on the Internet. These downloads can sometimes be dangerous and may cause a computer crash.
The film Casablanca, USA 1942, by director Michael Curtiz is a wonderful film with good language and there is a beautifully printed script in bookform which is offered by online booksellers:
Casablanca: Script and Legend: The 50th Anniversary Edition. I used the video and the script for teaching English to adults. And people liked it.
Another title is the musical My Fair Lady. The script is also available in bookform and contains exactly the text of the video.
But I must say it is hard work to find good and well-known films for which you can get a script in bookform.


text:
Q: The need of semaphore in python threading module Python threading module do not realize true parallel programming. Threads were switched one another. Then, is Semaphore necessary? Semaphore is for sending signal to other threads that should be processed at the same time. I think it is only useful in multiprocessing. Why is the Semaphore Class in threading module?

A: Because you can't be sure, when scheduler will switch threads. Consider SMP machine. It will always process one thread at a time. But nevertheless multithreaded code should use semaphores, mutexes, critical sections and other synchronization primitives.
Although CPython have GIL and can't execute more then one thread at a time, there can be other implementation without such a limitation. Also, even with GIL present, from thread POV all your threads are running simultaneously. You can't write piece of code that will prove opposite (yes, you can ask OS about this, but it is a cheating).
Strictly speaking, semaphore is used not for sending signals to other threads, but to protect access to a limited number of resources. For example, you can have 5 printers and 10 threads that want to print. You will have one Semaphore initialized with value 5 and it will protect access to your printers. So at any moment no more than 5 threads will print something.
Another example is connection pool. For example you have pool of N connections to DB. This means that no more than N threads can simultaneously execute queries to DB. In this case you will have Semaphore initialized with N. (N+1)'th thread will block on Semaphore and will wait for free connection.


text:
Q: Restrict user from accessing form Good day everyone! I'm a python Django web app developer and I ran into a problem recently which is to restrict a user from accessing a form twice untill after a given time. I've tried using Django sessions.accessed but I don't get what I want. I would appreciate if anyone could help me out with this.

A: Django session backend is working on cookies. So, when you are make something like this in your view:
def view(request):
    request.session["allow_access"] = False
    return HttpResponse(...)

the user can delete cookies or access via another browser or private mode.
So the best way is to use authentication of your users first and then you can work with sessions of your authenticated users with session backend.
def view(request):
    ...
    if request.session.get("allow_access"):
        return HttpResponse(...)
    else:
        ...


text:
Q: Prove that set is orthonormal set In vector space of all real polynomials with inner product $(x,y) = \sum_0^1x(t)y(t)dt$. $x_n(t) = t^n$ for $n = 0, 1, \dots $.
Show that functions:
$y_0(t) = 1, $
$y_1(t) = \sqrt(3)(2t-1), $
$y_2(t)=  \sqrt(5)(6t^2 -6t+1)$
are an orthonormal pair that span the same subspace as $\{x_0,x_1x_2\}$.
Plan of attack: (1) take inner product of $y_0,y_1$, $y_1,y_2$, and $y_2,y_3$. All 3 inner products should equal 0.
Question: how do I show that the functions $y_0,y_1,y_2$ are orthoNORMAL?

A: I think you mean the inner product on the space is $\langle x,y\rangle:=\int_{0}^1 x(t)y(t)\,dt$.
To show the set you stated is an orthonormal set, you want to show that it is an orthogonal set and each member of the set has unit norm. You can show orthogonality by showing that the inner product of each (distinct) pair is zero.
To show that each member as unit norm, recall that the norm induced by the inner product is $\|f\|:=\langle f,f\rangle^{1/2}=\sqrt{\int_0^1 f^2(t)\,dt}$, so you want $\|y\|=\sqrt{\int_0^1 y_i^2(t)\,dt}=1$ for $i=0,1,2$.


text:
Q: SES on node.js not sending the email although it return 'success' response I tried sending an email using SES. The to address is same as the from address, and is verified in AWS SES.
        usersList = [{
            "Destination": {
                "ToAddresses": [
                    "someuserthatisverifiedinSES@abc.xyz"
                ]
            },
            "ReplacementTemplateData": `{ "name":"User1", "message": "Hell no" }`
        }];
        defaultTemplateData = `{ "name":"Student", "message": ` + req.body.message + ` }`;

        var params = {
            Destinations: usersList,
            Source: "someuserthatisverifiedinSES@abc.xyz", /* required */
            Template: `SomeTemplate`, /* required */
            DefaultTemplateData: defaultTemplateData
        };
        // Create the promise and SES service object
        var sendPromise = ses.sendBulkTemplatedEmail(params).promise();

        // Handle promise's fulfilled/rejected states
        return sendPromise.then(
            function (data) {
                console.log('sent successfully');
                console.log(data);
                return data;
            }).catch(
            function (err) {
                console.log('error happened off');
                console.error(err, err.stack);
                return err;
            });
    }

I'm getting a successful response to this code.

{ ResponseMetadata: { RequestId:
  '14ada23f-someID-5be700be687f' },   Status:     [ { Status:
  'Success',
         MessageId: '010001619e8a79ed-someID-000000' } ] }

But the email is not being delivered.

A: From what I figured out, the email returns success although it didn't send when the template you created doesn't match the dataset yours sending. Maybe the template has a variable that isn't being addressed by the dataset you give it.
The return value will still be a success which it shouldn't. Upon fixing that bit, I started to receive emails. SES emails don't go to the junk too easily.


text:
Q: Communication over TLS/SSL failing with alert code 21? I am new to TLS/SSL. I am facing an issue with SSL/TLS connectivity.
I could see in tcpdump traces that the handshake is done succefully(clienthello,serverhello,certificate,certifcate request,server hello done, client certificate, client key exchange,certificate verify,change cipher suite exchange and finished message from both server and client side). My understanding is that if finished message exchnaged means handshake is completed. Is it correct?
After 'finished' message, Client sending application data which is http get request. There is no response from server for ~2 minutes and client is sending an alert close_notify after that.
"11905  14:51:54.122049 10.62.73.221    10.62.68.4  TLSv1   105 Alert (Level: Warning, Description: Close Notify)"
Alert message 21 is received by server.
could any one please explain why the alert message has been received by server.?
Thanks for support.

A: Well, with the details in your question, it could be that the GET request is not properly formed or the TLS Record is not proper - perhaps there is a discrepancy in the payload specified and what it is. Are  you constructing the TLS Record on your own or using an established library? It seems, that since you are new to SSL, an established library is being used. In this case, please make sure that the GET Request is formatted as per the HTTP spec with the necessary HTTP headers.

A: close_notify is normal. Nothing to be alarmed about. It is just the TLS version of close().


text:
Q: Error in JQuery html Hi please check my code:
$(function(){
    $('#username_change_submit').click(function(){
        var htmlText = '
Learnphp has been reserved for you.
[Reset Username]

                        <input type="text" id="guest_email" style="font-size:13px;width:140px;" onkeyup="validate_email(this.value)" placeholder="E-mail Address">

                        <input type="button" id="guest_signup_submit" value="Create Account" style="font-size:13px;" disabled="true" onclick="Javascript:guest_register()">';
        $('#right-register').html(htmlText);
    });
});

    <input type="button" value="Create Account" id="username_change_submit" name="username_change_submit">

Above code i am getting error.
I have little bit skill problem so i can't describe to you. Please check my screenshot.

Let me know the jquery error.

A: As i see here you didn't close the input tag. Put your input block like this;
<input />

Like;
<input type="text" id="guest_email" style="font-size:13px;width:140px;" onkeyup="validate_email(this.value)" placeholder="E-mail Address" />

A: You need to add \n\ at the end of every line for htmlText variable.
$(function(){
    $('#username_change_submit').click(function(){
        var htmlText = '
Learnphp has been reserved for you.
[Reset Username]
\n\
            <input type="text" id="guest_email" style="font-size:13px;width:140px;" onkeyup="validate_email(this.value)" placeholder="E-mail Address">\n\

<input type="button" id="guest_signup_submit" value="Create Account" style="font-size:13px;" disabled="true" onclick="Javascript:guest_register()">';
        $('#right-register').html(htmlText);
    });
});

A: You are preparing a string in multiple lines, So browser will treats as there is no semicolon(;) at end of each line, so you are facing unterminated string literal error. You have to do it as shown below:
var htmlText = '
Learnphp has been reserved for you.
[Reset Username]
';
htmlText += '<input type="text" id="guest_email" style="font-size:13px;width:140px;"';
htmlText += 'onkeyup="validate_email(this.value)" placeholder="E-mail Address">';
htmlText += '

';
htmlText += '<input type="button" id="guest_signup_submit" value="Create Account"';
htmlText += 'style="font-size:13px;" disabled="true" onclick="Javascript:guest_register()">';

A: it warns about multi-line strings without escape characters(\).
You have to do it as shown below:
var htmlText = '
Learnphp has been reserved for you.
[Reset Username]
\
                    <input type="text" id="guest_email" style="font-size:13px;width:140px;" onkeyup="validate_email(this.value)" placeholder="E-mail Address">\

\
                    <input type="button" id="guest_signup_submit" value="Create Account" style="font-size:13px;" disabled="true" onclick="Javascript:guest_register()">';

can do it as shown below, yet:
var htmlArr=[];
htmlArr.push('
Learnphp has been reserved for you.
[Reset Username]
');
htmlArr.push('<input type="text" id="guest_email" style="font-size:13px;width:140px;" onkeyup="validate_email(this.value)" placeholder="E-mail Address">');
htmlArr.push('

');
htmlArr.push('<input type="button" id="guest_signup_submit" value="Create Account" style="font-size:13px;" disabled="true" onclick="Javascript:guest_register()">');

var htmlText = htmlArr.join('');

A: Try this:
var htmlText = "
Learnphp has been reserved for you.
[Reset Username]
" + "<input type='text' id='guest_email' style='font-size:13px;width:140px;'" + "onkeyup='validate_email(this.value)' placeholder='E-mail Address'>" + "

" + "<input type='button' id='guest_signup_submit' value='Create Account'" + "style='font-size:13px;' disabled='true' onclick='Javascript:guest_register()'/>";


text:
Q: Capture href links with async method (crawler) problem My problem is that I have no result with this function. In fact, in my csv file or in my list I have no values. I spotted that the problem came from the line : if (htmlDocument != null && htmlDocument.DocumentNode.SelectNodes("//a[@href]")?.ToList() != null).
It says me that the DocumentNode is empty. Do you have any idea ?
public class LiensHtml
    {
        public List<string>? Links { get; set; }
    }
public async Task StartCrawlerasync(string url)
        {
            var httpClient = new HttpClient();
            var html = await httpClient.GetStringAsync(url);
            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(html);
            var All_Links = new LiensHtml();
            var writer = new StreamWriter("Tous_les_Liens.csv") ;
            var csv = new CsvWriter(writer, CultureInfo.InvariantCulture) ;

            HtmlNode test = htmlDocument.DocumentNode;

            Console.WriteLine(test.ToString());

            if (htmlDocument.DocumentNode.SelectNodes("//a[@href]").ToList() != null)
            {
                foreach (HtmlNode link in (List<HtmlNode>)htmlDocument.DocumentNode.SelectNodes("//a[@href]").ToList())
                {
                    All_Links.Links.Add(link.Attributes["href"].Value);
                    csv.WriteHeader<LiensHtml>();
                    csv.WriteRecords(link.Attributes["href"].Value);
                };

                foreach (string lien in All_Links.Links)
                {
                    Console.WriteLine(lien);
                }
            }
            else
            {
                Console.WriteLine("C''est vide");
            }
        }

A: It would help if you could give the site you are using, but I think:
htmlDocument.DocumentNode.Descendants("a").ToList()

should do the trick.
Edit:
After getting the site, I've rewritten your code:
public class LiensHtml
{
    public LiensHtml()
    {
        Links = new List<string>();
    }

    public List<string>? Links { get; set; }

    public async Task StartCrawlerasync(string url)
    {
        var httpClient = new HttpClient();
        var html = await httpClient.GetStringAsync(url);
        var htmlDocument = new HtmlDocument();
        htmlDocument.LoadHtml(html);

        var linkList = new LiensHtml();
        var writer = new StreamWriter("Tous_les_Liens.csv");
        var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);

        var links = htmlDocument.DocumentNode.Descendants("link").ToList();

        if (links.Count() != 0)
        {
            foreach (var link in links)
            {
                var linkValue = link.GetAttributeValue("href", "no link");

                linkList.Links.Add(linkValue);

                csv.WriteHeader<LiensHtml>();

               await csv.WriteRecordsAsync(linkValue);
               await csv.FlushAsync();
            }

            foreach (var lien in linkList.Links) Console.WriteLine(lien);
        }
        else
        {
            Console.WriteLine("C''est vide");
        }
    }
}


text:
Q: Simplifying complex equation with square root I need to  solve for either $x$ or $y$ the following equation, but the square roots are giving me real problems. Any help is very welcome:
$$
F=\frac{A+Bx+C(x^2+y^2)+\sqrt{(A+Bx+C(x^2+y^2))^2-4Dy^2}}{A+Bx+C(x^2+y^2)-\sqrt{(A+Bx+C(x^2+y^2))^2-4Dy^2}}
$$


text:
Q: function call between two components angular js I need to call function between two components.
This is just sample
@Component({
  selector: 'app-confirmation-dialog',
  templateUrl: 'confirmation-dialog.html',

})

export class ConfirmationDialog {
  clickme() {
    alert("hi")
  }
}

@Component({
  selector: 'app-summary',
  templateUrl: './summary.component.html',
  styleUrls: ['./summary.component.scss'],

})

export class ConfirmationDialog {
  clickme2() {
    clickme();
  }

}

I need to get 'hi' alert using clickme2() function.

A: You can call method of another component from a different component using Event Emitters if they have a parent child relationship or Shared Services or using ngrx redux pattern


text:
Q: How can I change default toast message color and background color in android? I want to create a toast message with background color is white and message color is black. My toast message is:
Toast.makeText(Logpage.this, "Please Give Feedback...", 3000).show();

I wanted to create it in another method not in onCreate().

A: Change Toast Colours without any additional Layouts, 2018
This is a very easy way I've found of changing the colour of the actual image background of the Toast as well as the text colour, it doesn't require any additional layouts or any XML changes:
Toast toast = Toast.makeText(context, message, duration);
View view = toast.getView();

//Gets the actual oval background of the Toast then sets the colour filter
view.getBackground().setColorFilter(YOUR_BACKGROUND_COLOUR, PorterDuff.Mode.SRC_IN);

//Gets the TextView from the Toast so it can be editted
TextView text = view.findViewById(android.R.id.message);
text.setTextColor(YOUR_TEXT_COLOUR);

toast.show();

A: Create a layout file toast.xml as to how your toast should look as below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/background_dark">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a custom toast."
        android:textColor="@android:color/white"
        android:layout_gravity="center_vertical" />

</LinearLayout>

To show the toast in the java file put the below code:
public void showCustomAlert()
    {
        Context context = getApplicationContext();
        // Create layout inflator object to inflate toast.xml file
        LayoutInflater inflater = getLayoutInflater();

        // Call toast.xml file for toast layout
        View toastView = inflater.inflate(R.layout.toast, null);

        Toast toast = new Toast(context);
        toastView.setView(toast);

        // Set layout to toast
        toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,
                0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.show();
    }

A: Toast toast=   Toast.makeText(YOUR ACTIVITY NAME ,Toast.LENGTH_SHORT);
View view =toast.getView();
view.setBackgroundColor(Color.GREEN); //any color your want
toast.show();

A: Change default toast message color and background color in JAVA. You can change toast message color and background color this way..
        Toast toast=Toast.makeText(MainActivity.this,"Signin button is clicked.",Toast.LENGTH_SHORT);
        View view =toast.getView();
        view.setBackgroundColor(Color.GREEN);
        TextView toastMessage = (TextView) toast.getView().findViewById(android.R.id.message);
        toastMessage.setTextColor(Color.RED);
        toast.show();

Just change toast text color this way..
        Toast toast = Toast.makeText(getApplicationContext(), "Signup button is clicked.",Toast.LENGTH_SHORT);

        TextView toastMessage=(TextView) toast.getView().findViewById(android.R.id.message);
        toastMessage.setTextColor(Color.BLUE);
        toast.show();

A: To keep round corners
val toast = Toast.makeText(context, "Text", Toast.LENGTH_SHORT)
toast.view.background.setTintList(ContextCompat.getColorStateList(context, android.R.color.darker_gray))
toast.show()

A: Heads Up, Updates to toasts in Android 11

Custom toasts from the background are blocked, Android 11 protects
users by deprecating custom toast views. For security reasons and to
maintain a good user experience, the system blocks toasts that contain
custom views if those toasts are sent from the background by an app
that targets Android 11.

addCallback() method added in Android R If you want to be notified when a toast (text or custom) appears or disappears.
The most important text in toast API changes that for apps that target Android 11 the getView() method returns null when you access it, So, ensure to protect your apps from FATAL EXCEPTION, you know what I mean :)

You can customize android native toast by using following code

/**
 * ShowToast
 */
public class ShowToast {
    public ShowToast(Context context, String info) {
        Toast toast = Toast.makeText(context, Html.fromHtml("" + info + ""), Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
    }
}

If you want to change the background you have to use custom layout in toast

A: Kotlin Version:
 val toast = Toast.makeText(this, getString(R.string.back_again), Toast.LENGTH_SHORT)
 val view = toast.view
 view.background.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_IN)
 toast.show()

A: Kotlin Version:
val toast:Toast = Toast.makeText(this, "Please enter your name !", Toast.LENGTH_SHORT)
val view = toast.view
view?.background?.setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN)
toast.show()

A: To Change the default Toast Text Color and Background color Try Like this.
 Toast toast = Toast.makeText(MainActivity.this, "Please Give Feedback...", Toast.LENGTH_LONG);
 View view = toast.getView();

 //To change the Background of Toast
 view.setBackgroundColor(Color.TRANSPARENT);
 TextView text = (TextView) view.findViewById(android.R.id.message);

 //Shadow of the Of the Text Color
 text.setShadowLayer(0, 0, 0, Color.TRANSPARENT);
 text.setTextColor(Color.BLACK);
 text.setTextSize(Integer.valueOf(getResources().getString(R.string.text_size)));
 toast.show();

A: You can create the custom toast message like below :
Toast toast = new Toast(context);
toast.setDuration(Toast.LENGTH_LONG);

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.your_custom_layout, null);
toast.setView(view);
toast.show();

One textview you can put inside the layout file and give the background and textcolor as you want.
Also you can do the following which won't need the extra custom layout file :
Toast toast = Toast.makeText(context, R.string.string_message_id, Toast.LENGTH_LONG);
View view = toast.getView();
view.setBackgroundResource(R.drawable.custom_background);
TextView text = (TextView) view.findViewById(android.R.id.message);
/*Here you can do anything with above textview like text.setTextColor(Color.parseColor("#000000"));*/
text.setTextColor(Color.parseColor("#000000"));
toast.show();

A: use this way
Toast toast = Toast.makeText(MainActivity.this, R.string.toastMessage, Toast.LENGTH_LONG);
toast.getView().setBackgroundColor(Color.parseColor("#F6AE2D"));
toast.show();

A: static void CustomToast(Context context, String text, int duration,
                                    @Nullable Integer backgroundColor,
                                    @Nullable Integer textColor){
        Toast t = Toast.makeText(context,text,duration);
        if (backgroundColor != null)
            t.getView()
                    .setBackgroundTintList(ColorStateList.valueOf(backgroundColor));
        if (textColor != null)
            ((TextView)t.getView().findViewById(android.R.id.message))
                    .setTextColor(textColor);
        t.show();
    }

A: Adding to @AndroidKiller's answer, you can also set the gravity and a custom TextView among other things like so:
Toast toast = Toast.makeText(context, context.getResources().getString(resID), Toast.LENGTH_LONG);
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
View toastView = li.inflate(R.layout.toast_hint_layout, null);
TextView text = (TextView) toastView.findViewById(R.id.hint_text_tv);
text.setText(resID);
toast.setView(toastView);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toastView.setBackgroundResource(R.drawable.toast_9_patch);
toast.show();

Note, your background drawable should be a nine-patch PNG
You can even put an ImageView, and multiple TextViews in with XML like this:
<LinearLayout android:id="@+id/layout_root"
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:orientation="horizontal">
    <ImageView
        android:layout_width="32dp"
        android:layout_height="43dp"
        android:src="@drawable/lightbulb"
        />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:orientation="vertical"
        >
        <TextView
            android:id="@+id/hint_text_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ccc"
            android:textSize="14dp"
            />

        <TextView
            android:id="@+id/hint_text_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="(disable hints in preferences)"
            android:textColor="#555"
            android:textSize="11dp"
            />
    </LinearLayout>
</LinearLayout>

A: I was able to do it by setting the background color filter color and finding the toast resource ID and setting the text color.
Android.Graphics.Color
    ///  Creates and displays a toast with the given text.
    public void Show(string message)
    {
        // Create the toast.
        Toast toast = Toast.MakeText(Android.App.Application.Context, message, ToastLength.Long);

        // Set the background color.
        Android.Graphics.Color c = new Android.Graphics.Color(122, 193, 66, 255);
        Android.Graphics.ColorMatrixColorFilter CMF = new Android.Graphics.ColorMatrixColorFilter(new float[]
            {
                0,0,0,0,(float)c.R,
                0,0,0,0,(float)c.G,
                0,0,0,0,(float)c.B,
                0,0,0,1,0
            });
        toast.View.Background.SetColorFilter(CMF);

        // Set the text color.
        toast.View.FindViewById<TextView>(Android.Resource.Id.Message).SetTextColor(new Android.Graphics.Color(0, 55, 103, 255));

        // Display the toast.
        toast.Show();
    }

A: Short java code that keeps the round shape:
Toast toast = Toast.makeText(context, "message", Toast.LENGTH_SHORT);
toast.getView().setBackgroundTintList(ColorStateList.valueOf(Color.RED));
toast.show();

A: Well here you can update the existing view of the toast class
because setting new background would remove rounded border and all you want is changing background color and text color without changing toast background decoration
        Toast toast = Toast.makeText(getActivity(), "Copied", Toast.LENGTH_LONG);
        TextView textView = toast.getView().findViewById(android.R.id.message);
        textView.setTextColor(Color.WHITE);
        textView.setTextSize(25);
        toast.getView().getBackground().clearColorFilter();
        toast.getView().getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.DARKEN);
        toast.show();


text:
Q: Sqlite null pointer exception I do not know what's wrong with my code, got really confused with it.
btnDone.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            enterproject1 obj1 = new enterproject1();
            String   pn = obj1.getprojectname();
            Connection conni = null;

            try {
                  String query=("insert into " + obj1.getprojectname() + " (engname,engpass,startingdate,estdate) values(?,?,?,?)");
                  PreparedStatement pst= conni.prepareStatement(query);

                  pst.setString(1, engineername.getText());
                  pst.setString(2, engpass.getText());
                  pst.setString(3, startingdate.getText());
                  pst.setString(4, estdatee.getText());
                  pst.execute();
                  JOptionPane.showMessageDialog(null, "Data Saved!");

                  System.out.println(pst.toString());

                  pst.close();
                } catch ( Exception e ) {
                  System.err.println( e.getClass().getName() + ": " + e.getMessage() );

                  System.exit(0);
                }
               dispose();
               WindowProjectAdmin blue = new WindowProjectAdmin();
        }
    });
    btnDone.setFont(new Font("Tahoma", Font.BOLD, 13));
    btnDone.setForeground(new Color(0, 255, 0));
    btnDone.setBounds(332, 327, 97, 38);
    contentPane.add(btnDone);
}

}
Should work right? Gives me Null pointer exception. The obj1 is a value from another class, I'm pretty sure the call is being made correctly too. Thank you for your time ^-^

A: It appears that you initialise your connection variable to null
Connection conni = null;

and then use it here:
PreparedStatement pst= conni.prepareStatement(query);

conni is still null at this point hence a null pointer exception.


text:
Q: How do I access the data from iframe in the parent window using jQuery? I wanted to access the contents of iframe in the main (parent) window..using jQuery

    <button>click</button>

I was trying with adding separate JSON file using Ajax jQuery its working fine,
I need the same thing when the JSON data are rendering inside the iframe.

A: var frameDoc = window.frames[ 0 ].document;

then you do $(frameDoc).find( <<selector>> );