Using a debugger and curses at the same time?

Question: I'm calling python -m pdb myapp.py, when an exception fires, and I'd normally be thrown back to the pdb interpreter to investigate the problem. However this exception is being thrown after I've called through curses.wrapper() and entered curses mode, rendering the pdb interpreter useless. How can I work around this?
Comment: I got a laugh at the title of this. Yeah debugging and cursing seem to go together in my mind.
Comment: i think there might be useful infomation http://wiki.python.org/moin/PythonDebuggers
Answer: James` answer is a good and I've upvoted it but I'd also consider trying to split the logic and presentation layers of my program. Keep the curses part a thin layer on top of a library and write a simple driver that invokes the correct routines to recreate the error. Then you can dive in and do what's necessary.
Another way I can think of is to create a function called debug or something that throws you back into the regular screen and invokes pdb. Then stick it just before the code that raises the exception and run your program. Something like
def debug(stdscr):
    curses.nocbreak()
    stdscr.keypad(0)
    curses.echo()
    curses.endwin()
    import pdb; pdb.set_trace()

Apparently, this is similar to what is done with the curses.wrapper function. It's mentioned briefly at http://www.amk.ca/python/howto/curses/.
Comment: A wise suggestion to keep the curses logic separated, and thanks for the `curses.wrapper` pointer.
Answer: Not being familiar with Python, this may not be exactly what you want. But apparently, winpdb can attach to a script - just like gdb can to a running process (IIUC).
http://winpdb.org/docs/launch-time/
Don't be mislead by the name, it is platform independent.
Comment: Good suggestion. You beat me to this. It would be the right way to go about this problem. Also useful for GUIs and daemon processes.
Comment: I don't suppose it's possible to attach using the core library's pdb?
Comment: I don't think so. You'll need to use winpdb on the 'client' and the 'server'.
Comment: As of Dec 2023, winpdb is gone, but look for winpdb-reborn instead. This is a Python3 port of winpdb.
Answer: use pyclewn
you can use pyclewn with vim.
or use pdb-clone,the core of pyclewn
its good ,its like gdb ,can remote debug
Comment: Pyclewn is not supported anymore according to that link.


Images of composed homomorphisms

Question: Let $R$ be a ring and $M,N,S$ be $R$-modules. Let $\varphi_1 : M\to N$ and $\varphi_2 : N\to S$ be homomorphisms.
Then $\operatorname{im}(\varphi_2\circ\varphi_1) \subseteq \operatorname{im}(\varphi_2)$ and $\ker(\varphi_1) \subseteq \ker(\varphi_2\circ\varphi_1)$, so we may form the quotients $\operatorname{im}(\varphi_2)/\operatorname{im}(\varphi_2\circ\varphi_1)$ and $\ker(\varphi_2\circ\varphi_1)/\ker(\varphi_1)$.
For the kernels, the application of the first isomorphism theorem to the homomorphism $\varphi_1|_{\ker(\varphi_2\circ \varphi_1)} : \ker(\varphi_2\circ \varphi_1) \to N$ yields the nice description
$$
\ker(\varphi_2\circ\varphi_1)/\ker(\varphi_1) \cong \operatorname{im}(\varphi_1) \cap \ker(\varphi_2).
$$
Now my question is:

Is there a similar description for the quotient
  $$\operatorname{im}(\varphi_2)/\operatorname{im}(\varphi_2\circ\varphi_1)?$$

I didn't succeed in finding a suitable application of the first isomorphism theorem in this case.
We may observe that the above reasoning for the kernels works exactly the same for homomorphisms of groups. However for the quotient of the images to make sense for groups, we need the additional property $\operatorname{im}(\varphi_2\circ\varphi_1)$ is a normal subgroup of $\operatorname{im}(\varphi_2)$.
This indicates that the situation might be a bit different for the quotient of the images. If needed, please assume some additional property on the ring $R$ to get a meaningful answer.
Comment: I guess $\operatorname{im}\varphi_2/\operatorname{im}(\varphi_2\circ\varphi_1) \cong N/(\operatorname{im}\varphi_1 + \ker \varphi_2)$ doesn't count as "nice"?
Comment: In the general case, why would this quotient be a submodule of $S$ at all? And if that can be false, what sort of nice description are you looking for?
Comment: @AsafKaragila: Thanks for your comment! I'm looking for a description similar to that for the kernels. Note that in general, the quotient of the kernels isn't a submodule of $M$, $N$ or $S$, and still it admits that nice description.
Comment: @DanielFischer: Thanks! This is "nice", in my opinion. Would you mind making an answer out of this, including a proof?
Answer: For ease of notation, let $A = \operatorname{im}\varphi_1 \subset N$, $T = \operatorname{im}\varphi_2 \subset S$, and $Q = T/\operatorname{im} (\varphi_2\circ\varphi_1) = T/\varphi_2(A)$. Consider the map $\psi = \pi \circ \varphi_2 \colon N \to Q$, where $\pi \colon T \to Q$ is the canonical projection.
The kernel of $\psi$ is
$$\ker \psi = \psi^{-1}(0) = \varphi_2^{-1}(\pi^{-1}(0)) = \varphi_2^{-1}(\varphi_2(A)) = A + \ker\varphi_2,$$
and $\psi$ is surjective because $\varphi_2$ and $\pi$ are ($\varphi_2$ considered as a homomorphism to $T$). By the homomorphism theorem, we have an induced isomorphism
$$\overline{\psi} \colon \frac{N}{\operatorname{im}\varphi_1 + \ker \varphi_2} \to Q = \frac{\operatorname{im}\varphi_2}{\operatorname{im}(\varphi_2\circ\varphi_1)}.$$
Comment: Many thanks for this answer! This is exactly the kind of representation I was looking for, but somehow I wasn't able to find it.

Images of composed homomorphisms


Difference between Numpy and Numpy-MKL?

Question: I wanted to test some signal processing and statistics using SciPy.
So I had to use scipy.signal and scipy.stats, but I always used to get an error:
ImportError: DLL load failed: The specified module could not be found.
I was using Numpy 1.7.1, scipy 0.12 and Python 2.7.3. I checked on the internet and asked about it on other forums too!
This problem got solved when switched my Numpy distribution with the Numpy-MKL distribution.
I want to know the difference between the two libraries ?
Comment: Now, maybe I am stating the obvious, but does this help to clarify? http://software.intel.com/en-us/articles/numpyscipy-with-intel-mkl
Answer: Numpy and scipy rely on lower level fortran libraries such as BLAS and lapack to perform many of their functions. These libraries come in many different versions, including the highly portable ones available from netlib, and other which are optimised for particular systems. In particular, Intel has one called "MKL" - Intel Math Kernel Library. So numpy-mkl just means a version of numpy compiled against the MKL fortran library.
Probably whichever version of numpy you previously had installed was somehow broken, and couldn't find the libraries it needed.
Comment: Which is faster mkl or the simple numpy?

Difference between Numpy and Numpy-MKL?


Go - How can I make sure there aren't empty fields being sent in this code via gRPC?

Question: I am writing some code to send logs with gRPC to a server. The problem I'm having is that the logs are different and not all have every field, but . I'm wondering how I can set only the fields they do have inside logpb.Log short of creating several different types of logs in the proto file?
This is all one methods, but the formatting on StackOverflow isn't with it.
The code:
func (*Client) SendWithgRPC(entry *log.Entry) error {

conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
    log.Fatalf("Could not connect: %v", err)
}

defer conn.Close()

c := logpb.NewLogServiceClient(conn)

stream, err := c.SendLogs(context.Background())
if err != nil {
    log.Fatalf("Error while calling SendLogs: %v", err)
}

logFields := entry.Data

category := ""
debug_id := ""
request_id := ""
tipi := ""
uri := ""
var user_id int32 = 0
ip := ""

if logFields["category"] != nil {
    category = logFields["category"].(string)
}

if logFields["debug_id"] != nil {
    debug_id = logFields["debug_id"].(string)
}

if logFields["request_id"] != nil {
    request_id = logFields["request_id"].(string)
}

if logFields["type"] != nil {
    tipi = logFields["type"].(string)
}

if logFields["uri"] != nil {
    uri = logFields["uri"].(string)
}

if logFields["user_id"] != nil {
    user_id = int32(logFields["user_id"].(int))
}

if logFields["ip"] != nil {
    ip = logFields["ip"].(string)
}

logEntry := &logpb.Log{
    Time:      entry.Time.String(),
    Level:     entry.Level.String(),
    Msg:       entry.Message,
    Category:  category,
    DebugId:   debug_id,
    Ip:        ip,
    RequestId: request_id,
    Type:      tipi,
    Uri:       uri,
    Id:        user_id,
}

logs := []*logpb.Log{logEntry}
logarray := []*logpb.SendLogsRequest{
    &logpb.SendLogsRequest{
        Logs: logs,
    },
}

fmt.Print(logarray)

for _, req := range logarray {
    stream.Send(req)
}

_, err = stream.CloseAndRecv()
if err != nil {
    fmt.Printf("Error with response: %v", err)
}
return nil
}

Answer: You can use something like https://github.com/go-playground/validator
It offers validation using tags. There is a lot more to this lib apart from basic validation. Do check it out.
Sample example https://github.com/go-playground/validator/blob/master/_examples/simple/main.go
As easy as it gets :
package main

import (
    "fmt"
    "github.com/go-playground/validator/v10"
)

type Name struct {
    First string `validate:"required"`
    Last  string
}

func main() {
    validName := Name{First: "John"} // Last name is empty and is not required
    invalidName := Name{Last: "Doe"} // first name is empty but is required

    validate := validator.New()

    err := validate.Struct(invalidName)
    if err != nil {
        fmt.Println("invalid name struct caused error")
    }

    err = validate.Struct(validName)
    if err != nil {
        fmt.Println("valid name struct caused error")
    }

    fmt.Println("GoodBye")
}

The output of above :
invalid name struct caused error
GoodBye

working code on go-playground : https://play.golang.org/p/S4Yj1yr16t2


How do I skip the tutorial?

Question: No matter the difficulty, except on Legendary, I have no option but to replay the tutorial. I'd like to skip through all of this as I've already done the tutorial more than twice, and I see no option to skip to Iron Man mode without doing the tutorial.
Is there a way to completely skip the tutorial as I don't want to do another tutorial again if I start a new game.
Comment: Ah mandatory tutorials, the greatest enemy of the  gamer. ;-)
Comment: Sounds like something to be fixed in a later patch after the hell the gamers will give them. Usual stuff.
Answer: Yes, you can disable the tutorial by unchecking the tutorial box on the start game screen. It's in the box of settings below the difficulty selection.

How do I skip the tutorial?


writing to /proc/net/xt_recent/ in python

Question: What is the best way to write to /proc filesystem from python3, specifically writing to /proc/net/xt_recent/
In shell, I would do:
echo +10.10.10.10 > /proc/net/xt_recent/BLOCKED

Which would add IP addresds to the list used by the iptables recent module
How can I do this in python3 ?
Comment: You could just use `os.system("echo +10.10.10.10 > /proc/net/xt_recent/BLOCKED")`.
Comment: You attached a bounty, and despite having an answer, didn't accept either/with no comment?
Answer: Why not just write to file?
with open('/proc/net/xt_recent/BLOCKED', 'a') as f:
  f.write('+10.10.10.10')

Comment: To mimic the shame bash behavior you need to create/truncate the file not append.
And also append a newline at the end.
Answer: You could do quite the same from Python:
with open('/proc/net/xt_recent/BLOCKED', 'w') as the_file:
  the_file.write('+10.10.10.10\n')

If you read this you'll see it's actually quite straightforward.
If you want to edit a file which requires permissions, run your python script as a super user.
sudo python yourcode.py
Answer: Just implement the same on python.
with open('/proc/net/xt_recent/BLOCKED', 'w') as f:
  f.write('+10.10.10.10\n')


How do I install Ubuntu Server on Foxconn Nano PC?

Question: As stated in the subject I am experiencing issues installing Ubuntu 12.04.2 server on a Foxconn nT-i2847 Intel NM70. I have tried both the i386 and amd64 with the same result - "problem reading from CD-Rom" / md5 check sum not matching up.
I am trying to install from a thumb drive as the nano PC does not have a CD-Rom.  I have read other threads stating work a around by including the ISO on the thumb drive and mounting it etc but non of these options have worked.
I have burned the same ISO files to disk and have had successful installs on my desktops but to no luck on this nano PC.
I have tried Unetbootin, linuxlive usb creator, universal USB installer and several other program for putting the ISO onto the USBthumb drive with the same result.  I have even tried multiple flash drive manufacturers - PNY, Scandisk etc.
I know people or going to state this question has been asked before however I have been combing through these and several other forums, and emulating fixes that worked for other people to no result.
Answer:
Hit Del on startup to get to BIOS
Make sure the first bootup device is "hard disk".
Click on "Hard disk bootup options"
If you have your USB inserted, you will see both your HDD/SSD and USB disk
Change hard disk boot order to boot from USB first
Press F10 to save BIOS settings.
When you boot with these settings, it should boot to the USB.


Can all positive real numbers be obtained by integral powers of a real number

Question: Can we write $x=y^q$ where x is a positive real number and y is any real number i.e. whether all positive real numbers can be formed by integral powers of any real number, In other words I want to find the range of the function $f(x,y)=x^y$ where y is a natural number and x is any real or you can say that atleast one qth root of a positive real is real. In more simple words for a given x and all integral values of q does there exist a y always?
I think it can be said but I dont know precisely why or cannot prove it.
Comment: What are your free variables?  Are you asking:  *given $x$ and $y$ does there exist a value of $q$ such that $x=y^q$*?  Or are you asking *given $x$ does there exist values of $y$ and $q$ such that $x=y^q$*?  Or are you asking for *given $x$ and $q$ does there exist a value of $y$ such that $x=y^q$*?
Comment: The last one ie for every q and a given x a y must always exist.
Comment: Note that $f(x,1) = x$.
Comment: As for the range of the function $f~:~\Bbb R\times \Bbb N\to \Bbb R$ given by $f(x,y)=x^y$, clearly it will be all of $\Bbb R$ since the function restricted to when $y=1$ is just $f(x,1)=x^1=x$ and $x$ ranges over all reals and the range of the function as a whole will be a superset of the range of the restricted function, the only superset of $\Bbb R$ that is also a subset of the codomain is again all of $\Bbb R$.
Comment: If you are asking for a proof as to why $\sqrt[q]{x}$ is real for all natural $q$ and all positive real $x$... by modifying the [proof for the existence of the square root of 2](http://math.stackexchange.com/questions/1319580/proof-that-square-root-of-2-exists-and-is-a-real-number) for arbitrary $q$ and $x$ one sees that indeed $\sqrt[q]{x}$ is indeed a real number.
Answer: What you're asking is: Given an integer $q \geq 1$ and a real number $x > 0$, does there exist $y > 0$ such that $y^q = x$?
The answer is yes. Take $y = \sqrt[q]{x}$.
The fact that a $q$th root exists is shown by proving that the function $f(t) = t^q$ defined for $t > 0$ has range $(0,+\infty)$, by using the intermediate value theorem.
Edit: Let $y > 0$. We have $\lim_{t \to +\infty} f(t) = +\infty$. Therefore there exists $B > y$ that is in the range of $f$. Similarly, $\lim_{t \to 0} f(t) = 0$, so there exists $A < y$ that is in the range of $f$.
The function $f$ is continuous, both $A$ and $B$ are in its range, and $A < y < B$. Therefore, by the intermediate value theorem, $y$ is in the range of $f$.
Comment: Can you show how ivt can be used ?
Comment: So y cannot be negative only positive ? If not how can we prove it ?
Comment: Well, you need to take into account signs in the usual way. For example, $-64$ has a cube root but no square root, since $3$ is odd and $2$ is even. These facts are not difficult to prove once you have the theorem about roots of positive numbers.


Is it possible to create a UTC Datetime from the date obtained from another UCT Datetime, in combination with a time string and timezone string?

Question: Consider the following input to a program:

time = 18:00
timezone = Europe/London (or any sensible representation of a timezone, possible examples include Europe__London, Europe.London, etc ... see note)
the date, which can be obtained by stripping out the date fields from chrono::Utc::now().

Is it possible to combine these data, or something similar, into a chrono::Datetime object?
Note: that the particular form of the string is not particularly important, and can be changed. This data just comes from a text file.
I think there may be two possible approaches.

Construct a string representation in rfc3339 format using format!, then parse this using the datetime parse_from_rfc3339 function. This seems like the wrong approach - creating bigger strings and then parsing them feels like an inefficient or "clumsy" approach. But it seems relatively easy to do.
The second option I am less confident on. I would guess there is a way to operate on some chrono types directly to create a datetime from each of these 3 pieces. But as for this option, I am somewhat lost and have no real idea how to approach the problem this way.

My attempts so far:

Option 1: Process strings
A chrono::DateTime object can be constructed using a string in rfc3339 format. Here is how that might be done:
let datetime_rfc3339_format_string =
    format!("{}T{}-{}",
        date_string, time_string, timezone_string);

let datetime_remote = chrono::DateTime::parse_from_rfc3339(datetime_remote_rfc3339_format);

The question then becomes how to build those three components in String format.
Timezone String
I previously managed to come up with a way of constructing a chrono_tz::Tz object from a string. See the following linked question.
let chrono_timezone = Tz::from_str(timezone.as_str())
    .expect("failed to convert string to chrono tz");

This works, assuming a string in the format of something like:
Europe/London

But in order to use something in rfc3339 format, we need to convert this "timezone name" into an "offset in number of hours". That depends both on the global datelines as well as local rules for things such as daylight savings.
So here I become stuck. I don't know how to convert a Tz object into an offset in numbers of hours, which in principle would depend on the current date.
Date String
This part is relatively easy. We can build a DateTime object from Utc::now() and extract the date using date_naive(). This can then be formatted as a String.
let datetime = chrono::Utc::now();
let date = datetime.date_naive();
let string_date = format!("{}", date);

Time String
I already have these in the required (String) format. For example, I can read these from a text file, and they are in the format of, for example:
08:00

Option 2:
Since I already have a timezone object, my thoughts were that it might be possible to use this to construct a DateTime object directly. It seems like the FixedOffset type has a with_ymd_and_hms function.
This suggests that somehow DateTime objects can be constructed from Timezone objects with this additional information, which I have access to.
But, this is where I get stuck. I do not know how to proceed here, or even if FixedOffset is the type I want to be working with. I don't know how it is related to Tz, if at all.
let chrono_timezone = Tz::from_str(timezone.as_str())
    .expect("failed to convert string to chrono tz");

Answer: This answer demonstrates a solution for Option 1:
Using the information presented in this question, we can solve the problem of how to convert a timezone into an offset, which can then be converted to the required String format.
fn get_todays_offset(tz: chrono_tz::Tz) -> chrono::Duration {

    let now = chrono::Utc::now().naive_utc();
    let offset = tz.offset_from_utc_datetime(&now);
    offset.base_utc_offset() + offset.dst_offset()
}

fn get_todays_offset_as_hh_mm(tz: chrono_tz::Tz) -> String {

    let todays_offset = get_todays_offset(tz);

    let todays_offset_sign = todays_offset.num_nanoseconds().unwrap().signum();
    let todays_offset_hours = todays_offset.num_hours();
    let todays_offset_minutes = todays_offset.num_minutes() % 60;

    let mut todays_offset_hh_mm_string = format!("{:02}:{:02}", todays_offset_hours, todays_offset_minutes);
    if todays_offset_sign >= 0 {
        todays_offset_hh_mm_string = format!("+{}", todays_offset_hh_mm_string);
    }
    else {
        todays_offset_hh_mm_string = format!("-{}", todays_offset_hh_mm_string);
    }

    return todays_offset_hh_mm_string;
}

From this, we can then construct the rfc3339 String.
let timezone_string = get_todays_offset_as_hh_mm(tz);

let datetime_rfc3339_format =
    format!("{}T{}-{}",
        date_string, time_string, timezone_string);

let datetime =
    chrono::DateTime::parse_from_rfc3339(
        datetime_remote_rfc3339_format.as_str())
            .expect("rfc3339 parse failed");


404 for Angular app located in .NET wwwroot folder after refresh

Question: I just create simple basic .NET Core 6 and Angular 16 applications.
I run
ng build --base-href=/ --output-path=D:\\myApp

and then I move all this build files to wwwroot folder in angular application.
my Program.cs class :
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseHttpsRedirection();
            app.UseCors(m => m.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            app.UseAuthorization();

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.MapControllers();

            app.Run();
        }

All is hosted on IIS, there is WebApplication with all dll's, web.config <for .NET app> files and wwwroot folder , in this wwwroot folder I also got web.config for angular application
<?xml version="1.0" encoding="utf-8"?>
<configuration>

<system.webServer>
  <rewrite>
    <rules>
      <rule name="AngularRule" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

</configuration>

What I'm doing wrong ?
Comment: If you are getting a 404 even with the StaticFiles enabled, can you check if you can access a single index.html file with some dummy content?
Comment: Your `<rule name="AngularRule" ` simply breaks every request because it's executed by IIS long before ASP.NET Core's static-file handler sees the request, and IIS _doesn't know_ that ASP.NET Core is handling the serving of static files under `$websiteRoot\wwwroot` but IIS thinks static files are directly under `$websiteRoot`.
Comment: @V.S Yes, with just index.html all works fine
Comment: @Dai okey but API works 100% fine.. just angular has 404 error after refresh..
Comment: @ruddnisrus AFTER REFRESH is veryimportant bit of info. I have updated my answer for thiat.
Answer: In the index.html, does the    match the folder in IIS? Typically  \inetpub\wwwroot\someapp   but in your case  d:\myapp
If you have a pluralsight subscribtion, there are videos by Shawn Wildermuth specifically on using .net and angular together.
Also, I am used to seeing Cors setup in two parts.
Setting up in services:

 services.AddCors(options =>
 {
  options.AddPolicy("MyAllowedOrigins",
  policy =>
  {
  policy
  .AllowAnyOrigin()
  .AllowAnyHeader()
  .AllowAnyMethod();
   });
});

Calling in app:
app.UseCors("MyAllowedOrigins");
UPDATE #1
The OP mentioned 404 on refresh. There are many ways to setup IIS, Angular, etc. This sounds like a redirect issue.
Using the hash in the Angular route will should address this issue.
RouterModule.forRoot(routes,
{
useHash: true
}
If this fixes it, please mark this as the answer.
Comment: from d:\myapp I just take staff and copy it to windows server environment, CORS are okey in that case, I also use it  but it's not that case, I just don't know how to configure this two web.configs , I also cannot find any useful staff related to IIS configuration on Shawn content;/
Comment: The IIS setup is very straightforward. You do not need / should create any additional web.config files. Just copy the files from the publish folder to appropriate folder on the IIS several. Create an appPool that is No Managed Services. Create an App that uses the newly created appPool. If the IIS server can host a default .net6 web app published straight from the template, it will have no issues hosting an angular app. The angular app requires less from the IIS Server than .net 6.
Answer: When building your Angular application, you specified --base-href=/. This means that your Angular application expects to be served from the root of your domain. Therefore, you don't need to rewrite URLs in your web.config. Instead, you can simply serve the Angular files directly from the wwwroot folder.
You don't need a separate web.config file for your Angular application in the wwwroot folder. The one you have in the root of your ASP.NET Core application should suffice.
Here's what you can do:
Remove the rewrite rule from the web.config in the wwwroot folder.
Make sure your Angular application is built with the correct base href. If your Angular application will be served from a subdirectory, you should specify that subdirectory as the base href during the build process.


Nvidia/Ubuntu Compatiblity problems

Question: I run a multi boot machine with XP, Windows 7 and ubuntu. Occasionaly ubuntu looses its marbles and drops the resolution to 640 X 480. I spend a month or two running on windows then ubuntu finds its marbles again and mysteriously resets the resolution back to normal...really flakey.
I have recently upgraded to 12.04 from 11.10, and am experiencing annoying drop outs to the login screen when on youtube. I have noticed a few ubuntu users experiencing the same issue. I tried the solution that has helped many. Ex. upgraded nVIDIA driver to 295.53, but it doesn't seem to make much difference. Has anybody found a solution other than upgrading the nvidia driver ?
System Specs = Nvidia GeForce 8500 GT, AMD Athlon(tm) 64 X2 Dual Core Processor 4800+ × 2
It appears to be a nvidia/ubuntu compatibility problem, because XP and windows7 are not affected
Any advice would be enormously appreciated.....Thanks
Answer: Install the x-swat repository to install the current nvidia driver 304.43 and that will solve the problem.
sudo apt-add-repository ppa:ubuntu-x-swat/x-updates
sudo apt-get update
sudo apt-get install nvidia-current

I found these instructions somewhere in this forum but I can't find it. I'm very happy with the person that posted them.

Nvidia/Ubuntu Compatiblity problems


Wordpress - Adding custom field to the post screen

Question: I was wondering if its possible to add a little box, like the 'excerpt' box to all posts in wordpress so that i can enter a URL.
Cheers,
Answer: You can use the add_meta_box function.  You also need a callback function that outputs the form html on the post screen and a save function.
Here is a basic example that adds a URL meta box to lower right hand side of the post screen.
<code>add_action( 'add_meta_boxes', 'c3m_sponsor_meta' );
        function c3m_sponsor_meta() {
                add_meta_box( 'c3m_meta', 'Sponsor URL Metabox', 'c3m_sponsor_url_meta', 'post', 'side', 'high' );
                }

            function c3m_sponsor_url_meta( $post ) {
                $c3m_sponsor_url = get_post_meta( $post->ID, '_c3m_sponsor_url', true);
                echo 'Please enter the sponsors website link below';
                ?>
                <input type="text" name="c3m_sponsor_url" value="<?php echo esc_attr( $c3m_sponsor_url ); ?>" />
                <?php
        }

add_action( 'save_post', 'c3m_save_project_meta' );
        function c3m_save_project_meta( $post_ID ) {
            global $post;
            if( $post->post_type == "post" ) {
            if (isset( $_POST ) ) {
                update_post_meta( $post_ID, '_c3m_sponsor_url', strip_tags( $_POST['c3m_sponsor_url'] ) );
            }
        }
        }
</code>
Edit:  Corrected namespace error in code above.
Comment: @Chris_O - Thats exactly what i need ... Only problems is that its not saving the value i enter into the box
Comment: @Chris_O - Ohh scrub that last comment, i just read the comment above the code hahaha, Thanks muchly :)
Comment: @BigJobbies I am updating the code above to one I have used for URL's.


How do I import files into a scoped style tag without it bleeding out?

Question: I'm importing a css file in a style tag using a .vue file. The scoped css file is affecting all the css on my page and I only want it to affect my current component.
<template>

        <router-view></router-view>

</template>

How do I import a css file that is scoped to my current component?
Comment: Insert scoped style into top level of your current component. https://css-tricks.com/saving-the-day-with-scoped-css/
Comment: @bigless raw css scoped was deprecated around 2014.
Answer: Can you use sass?
First you'd have to install sass-loader:
npm install sass-loader node-sass --save-dev

Then you can use it like this:
<template>

        <router-view></router-view>

</template>

Comment: Thanks but this doesnt seem to work. I'm using Laravel mix to handle my webpack.config file if that gives you any clues
Comment: You shouldn't really have to change anything in your config.
Comment: I cant get this to work. Without digging into it too much I think the sass loader doesn't support importing within a class.
Comment: I did a raw build just using scss and no vue to see what was going on. It rips out .container{} and just has the @import. Very weird.


Angular Material Tree - TreeControl selection model doesn't work for immutable data

Question: I needed a dynamically loading nodes in the angular material tree, so I created my own GeoDataSource which internally uses @ngrx/component-store to handle all the interaction between data source, TreeControl and the tree itself.
Now, the problem is the tree doesn't keep its expansion state because the abstract class BaseTreeControl<T, K = T> uses SelectionModel<T> class and this in turn uses Set<T> to keep track of items that are selected. So if node is expanded it just does this:
this._selection.add(value); // Set<T>.add(value)

When using immutable data (from the component store) those items are always new.
I tried to use trackBy optional function:
    this.treeControl = new FlatTreeControl<SomeEntityFlatNode, string>(
      (node) => node.nodeLevel,
      (node) => node.expandable, {
        trackBy: (node) => node.groupPath // *** groupPath is string (it's an ID) ***
      }
    );

and for this I had to change FlatTreeControl<SomeEntityFlatNode> to FlatTreeControl<SomeEntityFlatNode, string>, otherwise it doesn't compile. But then I got the following error in the template:

Type 'FlatTreeControl<SomeEntityFlatNode, string>' is not assignable to type 'TreeControl<SomeEntityFlatNode, SomeEntityFlatNode>'

Here's the template:
<mat-tree *ngIf="hasData$ | async" [dataSource]="geoDataSource" [treeControl]="treeControl">
</mat-tree>

Now what? How do I make all this work with immutable data from the store?
Answer: I figured I have to use trackBy function for TreeControl to make it work. But there's currently a bug (at the time of writing) which doesn't allow me to do it. The patch is coming though!
Comment: @Alvipeo Can you please provide a short code snippet of the final solution? I want to track nodes by their ID but somehow it doesn't work the same way as with *ngFor, the nodes always get re-created.
Comment: could you please link the bug or add some more insight into what the bug is?
Comment: I did and the fix is already merged. It should be available with the next material release. Waiting for it to try.


How to solve the error 'AttributeError: 'ir.http' object has no attribute 'webclient_rendering_context' - - -'?

Question: I got this error when i try to run odoo via terminal after configuring odoo and python in eclipse and created database. Here is the full error reference.
2021-06-08 13:51:17,499 14016 ERROR odoo_13A werkzeug: Error on request:

Traceback (most recent call last):

File "/home/davemax/.local/lib/python3.8/site-packages/werkzeug/serving.py", line 270, in run_wsgi
    execute(self.server.app)

File "/home/davemax/.local/lib/python3.8/site-packages/werkzeug/serving.py", line 258, in execute
    application_iter = app(environ, start_response)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/service/server.py", line 439, in app
    return self.app(e, s)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/service/wsgi_server.py", line 142, in application
    return application_unproxied(environ, start_response)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/service/wsgi_server.py", line 117, in application_unproxied
    result = odoo.http.root(environ, start_response)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/http.py", line 1287, in __call__
    return self.dispatch(environ, start_response)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/http.py", line 1257, in __call__
    return self.app(environ, start_wrapped)

File "/home/davemax/.local/lib/python3.8/site-packages/werkzeug/wsgi.py", line 766, in __call__
    return self.app(environ, start_response)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/http.py", line 1457, in dispatch
    result = ir_http._dispatch()

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/addons/base/models/ir_http.py", line 238, in _dispatch
    return cls._handle_exception(e)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/addons/base/models/ir_http.py", line 206, in _handle_exception
    return request._handle_exception(exception)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/http.py", line 750, in _handle_exception
    return super(HttpRequest, self)._handle_exception(exception)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/http.py", line 310, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/tools/pycompat.py", line 14, in reraise
    raise value

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/addons/base/models/ir_http.py", line 234, in _dispatch
    result = request.dispatch()

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/http.py", line 809, in dispatch
    r = self._call_function(**self.params)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/http.py", line 350, in _call_function
    return checked_call(self.db, *args, **kwargs)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/service/model.py", line 94, in wrapper
    return f(dbname, *args, **kwargs)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/http.py", line 339, in checked_call
    result = self.endpoint(*a, **kw)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/http.py", line 915, in __call__
    return self.method(*args, **kw)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/odoo/http.py", line 515, in response_wrap
    response = f(*args, **kw)

File "/home/davemax/odoo/workspace/odoo_13/odoo_13/addons/web/controllers/main.py", line 844, in web_client
    context = request.env['ir.http'].webclient_rendering_context()

AttributeError: 'ir.http' object has no attribute 'webclient_rendering_context' - - -

This is the full trace back. Please help me.
Comment: Please post the full traceback.
Comment: I have posted again the full trace back error above. Please help me.
Comment: Which version of odoo are you using?
Comment: I am using odoo 13 version
Answer: run your server using : -d cphhr_test -u all
just like :
/home/sadid/venv/bin/python3 /home/sadid/odoo-bin -c /home/sadid/odoo.conf -d cphhr_test -u all


How can a commutative algebra have more than one simple submodule?

Question: A result from representation theory:
-Let A be a commutative algebra over $\mathbb{C}$. Any simple A-module is a one-dimensional module over $\mathbb{C}$.
Is the following true or false? "A commutative group algebra $\mathbb{C}G$ can only have one simple submodule"
I feel like it should be true, as if we have a non-zero generating element "a" for one such submodule A, then since A is one-dimensional, ba=$\lambda$a for all b in $\mathbb{C}G$. An element "a" with such a property should be unique.
If the above statement is true, then this is where my confusion lies:
Consider $\mathbb{C}G$, where $G=C_{\large 3}$. This is a commutative group algebra. As a module over itself, it is 3 dimensional, and by the above reasoning, every simple submodule should be one-dimensional.
I can find one one-dimensional submodule, $S_1 = $ $ <e + g + g^2>$, and one two-dimensional submodule, $S_2 = $ $<e - g, g - g^2>$, but I can't find a submodule of $S_2$, so it appears as if $S_2$ is a simple, two dimensional submodule of a commutative algebra.
If anyone can help me at all it will be much appreciated!
Answer: In your example, you could have $S'=\left<e+\omega g+\omega^2 g^2\right>$
where $\omega=\exp(2\pi i/3)$. This is a one-dimensional module but not
isomorphic to $S_1$.
Comment: Thanks, my misunderstanding was in the assumptions I made about complex vector spaces, you answer highlighted this for me.
Answer:
"A commutative group algebra $\mathbb CG$ can only have one simple submodule"

Even for finite groups, this is almost always incorrect, the only exception that it works for being $|G|=1$.
If $|G|>1$ and you take $e=\frac{1}{|G|}\sum_{g\in G}g$, you have a nontrivial central idempotent $e$ such that $R=eRe\oplus (1-e)R(1-e)$ as a product of rings. Now if you take any maximal ideal $M_1\lhd eRe$ and a maximal ideal $M_2\lhd (1-e)R(1-e)$,  then $R/(M_1\oplus (1-e)R(1-e))$ and $R/(eRe\oplus M_2)$ are nonisomorphic simple modules.


Keycloak - Current language code in theme

Question: I would like to output the two letter language code (f.e. en) of the current language in the freemaker template of the login theme.
I already tried ${locale.current}, but this only outputs the name of the current language and not the code.
Answer: If you have enabled Internationalization for themes use:
${locale.currentLanguageTag}

${locale.currentLanguageTag} => en
${locale.current} => English
Comment: Thank you! I can confirm that this works, for example as ``
Comment: Thanks. Is there an easy way to check in the template if that is defined? So the page won't fail when internationalization is turned off.


How can I concat polars dataframes that have different columns

Question: In pandas it happens automatically, just by calling pd.concat([df1, df2, df3]) and the frame that didn't have the column previously just gets a column filled with NaNs.
In polars I get a 'shape error' with the message that the columns differ (11 cols in df1 vs 12 cols in df2).
Answer: Polars cares about schema correctness by default in operations and prefers throwing an error above silently succeeding as it might indicate a bug in your program.
If you want polars to add the columns, add the kwarg how="diagonal" to pl.concat.
df_a = pl.DataFrame({
    "a": [1, 2, 3],
    "b": [True, None, False],
})

df_b = pl.DataFrame({
    "a": [4, 5],
    "c": ["bar", "ham"]
})

pl.concat([df_a, df_b], how="diagonal")

shape: (5, 3)
┌─────┬───────┬──────┐
│ a   ┆ b     ┆ c    │
│ --- ┆ ---   ┆ ---  │
│ i64 ┆ bool  ┆ str  │
╞═════╪═══════╪══════╡
│ 1   ┆ true  ┆ null │
├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ 2   ┆ null  ┆ null │
├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ 3   ┆ false ┆ null │
├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ 4   ┆ null  ┆ bar  │
├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ 5   ┆ null  ┆ ham  │
└─────┴───────┴──────┘

Comment: Damn i am blind. As soon as my eyes saw 'diagonal' in the documentation they skipped the paragraph immediately thinking it's something completely different.

p.s. i love u (was starting to write spaghetti for loops with .lit() to get the job done)
Comment: I'm wondering why there are no similar keywords to the read_csv or read_parquet methods? As they do concatting under the hood if one specifies a mask...
Comment: @zacko yeah I knew diagonal existed but didn't consider it did what I want either. To be fair I'm not sure what I'd call it....


dialog box displays only the last item in the array list

Question: I am trying to display data from a an array list but after the marker onclick
it only displays the last element in the array list in the material dialog box
 DriverLocationDataManager gets all the data snapshots of the geopoints of the drivers in the database
after adding in all the driver data, i use the addMarker function which gets the geopoints and set the markers on the map.
<code>//Init data manager

    drivers = new ArrayList<>(0);

    dataManager = new DriverLocationDataManager(this) {
        @Override
        public void onDataLoaded(List<Driver> data) {
            if (data.isEmpty()) {
                Snackbar.make(container, "Sorry!. UG Shuttle service is currently unavailable",
                        Snackbar.LENGTH_INDEFINITE).show();
            } else {

                drivers.addAll(data);

                List<Marker> markers = addMarkers(data);
                for (int i = 0; i < markers.size(); i++){
                    markers.get(i);
                    Driver driver = drivers.get(i);
                    map.setOnMarkerClickListener(marker -> {
                        // Get custom view
                        View v = getLayoutInflater().inflate(R.layout.driver_popup, null, false);

                        //Assign props
                        TextView username = v.findViewById(R.id.driver_username);
                        CircularImageView profile = v.findViewById(R.id.driver_profile);
                        ImageView status = v.findViewById(R.id.driver_status);
                        TextView shuttle = v.findViewById(R.id.driver_bus_number);
                        ViewGroup viewGroup = v.findViewById(R.id.group);

                        //Init props
                        Glide.with(getApplicationContext())
                                .load(driver.getProfile())
                                .apply(RequestOptions.circleCropTransform())
                                .apply(RequestOptions.placeholderOf(R.drawable.avatar_placeholder))
                                .apply(RequestOptions.errorOf(R.drawable.avatar_placeholder))
                                .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
                                .transition(withCrossFade())
                                .into(profile);

                        username.setText(driver.getDriver());   //Driver's username
                        shuttle.setText(driver.getCarNumber()); //Driver's car number

                        //Attach to dialog
                        Builder materialDialog = new Builder(HomeActivity.this)
                                .customView(v, true)
                                .negativeText("Dismiss")
                                .onPositive((dialog, which) -> {
                                    dialog.dismiss();
                                    enableTracking(marker);
                                })
                                .onNegative((dialog, which) -> dialog.dismiss());

                        if (driver.isStatus()) {
                            status.setImageResource(android.R.color.holo_green_light);  //Online

                            //Enable tracking when driver is online
                            materialDialog.positiveText("Track")
                                    .onPositive((dialog, which) -> {
                                        dialog.dismiss();
                                        enableTracking(marker);
                                    });
                        } else {
                            //Tracking is disabled
                            status.setImageResource(android.R.color.holo_red_light);    //Offline
                        }

                        materialDialog.build().show();
                        return true;
                    });

                }
            }
        }
    };
</code>
Comment: You have build `Dialog` inside for loop . Build it outside loop when data is processed .
Comment: that doesnt help since i want all the instance of the driver objects
Comment: i dont want to show multiple dialogboxes, each marker click shows one dialog box inflated by the data from the driver object,
Comment: i dont want to show multiple dialogboxes, each marker click shows one dialog box inflated by the data from the driver object,
Answer: I invite you to read the official developer guide here. It explains how to properly use Dialogs, how to display a list in it, and even how to implement a custom view if you need one to display your list.


Internal links in Jekyll using Org mode

Question: I saw this question about linking to internal content using markdown. How can I link to other posts using Org mode?
I tried the markdown format and I get the following error:
...error:
             Error: Unknown tag 'post'
             Error: Run jekyll build --trace for more information.

Answer: You can get a relative URL to another blog post inside a jekyll post with {% post_url 1025-08-26-blog-post-name %} (with no trailing .html or .org on the post name).
To actually make it a link, you'll need to wrap it in an html link. Assuming you've got your org-publish settings set up to write HMTL, this can be a little tricky, since it seems that the standard org-mode link syntax doesn't work properly for jekyll-inserted links. Instead, you can just insert the anchor html directly into your org file using an org-mode HTML escape:
Blah blah surrounding text
@@html:@@Text describing link to my other post@@html:@@ more surrounding text

Comment: Brilliant! `@@Text describing link to my other post@@html:`

Internal links in Jekyll using Org mode


Spectrum vs eigenvalues

Question: Easy question about linear operators - in physics (often) the terms spectrum and (set of) eigenvalues of an operator are used interchangeably.
I'd like a simple compare and contrast to know the difference according to mathematicians.
Many thanks!
Answer: The other answers adequately address the finite-dimensional case. If we consider a Hilbert space $\newcommand{\Hil}{\mathcal{H}}\Hil$ of countable dimension with orthonormal basis $(e_i)_{i \in \mathbb{N}}$, we can define an operator $T : \Hil \rightarrow \Hil$ by
$$
T(e_n) = \frac{1}{n}e_n
$$
It is clear from this definition that each $e_n$ is an eigenvector with eigenvalue $\frac{1}{n}$, and as $(e_i)_{i \in \mathbb{N}}$ is an orthonormal basis, this is a complete set of eigenvectors. So the set of eigenvalues is $\{ \frac{1}{n} \mid n \in \mathbb{N} \}$.
However, $T$ is not invertible (one way to see this is that if we try to define an inverse we get an unbounded operator, another is that the vector $\sum_{n=1}^\infty \frac{1}{n}e_n$ is in $\Hil$ but not in the image of $T$), so $0$ is an element of its spectrum that is not an eigenvalue. In fact $\{ 0 \} \cup \{ \frac{1}{n} \mid n \in \mathbb{N} \}$ is exactly the spectrum of $T$.
The spectrum is always a non-empty closed subset of $\mathbb{C}$, while the set of eigenvalues does not need to be. Also, the set of eigenvalues can be empty (for example, this is the case for the operator $S(e_n) = e_{n+1}$).
Comment: Regarding $S$, it is more usually known as the "unilateral right shift". Its spectrum is the unit disc (*i.e.* the set of all complex numbers $\lambda$ such that $|\lambda| \leq 1$).
Comment: +1 for great, simple example and explanation. Question: is the inverse of T unbounded because it would seem to require $T^{-1}(e_n) = n e_n$? Also I see why S has no eigenvalues but what is its spectrum then? (can you give me a hint to figure it out for myself?)
Comment: @lux Yes, the operator $T^{-1}(e_n) = ne_n$ is unbounded (and therefore partially defined - if you evaluate it on the vector $\sum_{n=1}^\infty \frac{1}{n}e_n$ you get a sum that doesn't converge in $\mathcal{H}$).
Comment: OK, thanks! But is it obvious that the vector you propose to act upon with the inverse operator converges in H? And can you help me with the spectrum of your operator S?
Comment: @lux To show $\sum_{n=1}^\infty \frac{1}{n}e_n \in \mathcal{H}$, use the fact that $\sum_{n=1}^\infty \frac{1}{n^2}$ converges (to $\frac{\pi^2}{6}$). This is enough to show that the original sum converges in norm in the Hilbert space $\mathcal{H}$. If it makes things easier, set $\mathcal{H} = \ell^2$ and let $(e_i)_{i \in \mathbb{N}}$ be the standard basis.
Answer: The spectrum of a linear operator $T$ on a finite dimensional space is exactly the set of its eigenvalues.
It's defined as $\{\lambda:T-\lambda I$ is not invertible$\}$, and $T-\lambda I$ is not invertible in a finite dimensional space iff its kernel is nonzero, meaning exactly that $\lambda$ is an eigenvalue of $T$.
Comment: OK great - what about on an infinite dimensional space?
Answer: I'd like to add something further in the infinite-dimensional case than the other responses, which I think is important if we're going to talk about eigenvalues vs. spectrum. I'm going to specify how they're related.
As mentioned by @RobertFurber, we can have elements of the spectrum which are not eigenvalues. Let $T:X\rightarrow X$ be a bounded operator on a Banach space. The spectrum $\sigma(T)$ can be decomposed into three pieces:

The point spectrum: this consists of $\lambda\in\sigma(T)$ so that $T-\lambda I$ is not injective. In this case, $\lambda$ is called an eigenvalue of $T$.

The continuous spectrum: this consists of $\lambda\in \sigma(T)$ such that $T-\lambda I$ is one-to-one, and the range of $T-\lambda I$ is dense in $X$, but it is not equal to $X$.

The residual spectrum: this consists of $\lambda\in \sigma(T)$ such that $T-\lambda I$ is one-to-one, and such that $T-\lambda I$ is not dense in $X$.

While the spectrum is always non-empty, we can have elements with empty point spectrum. As an example, if $X=L^2([0,1])$ and $M:X\rightarrow X$ is the multiplication operator defined by sending $f\in X$ to the function $Mf(x)=xf(x)$ with $x\in[0,1]$,  then $\sigma(M)=[0,1],$ and each $\lambda\in [0,1]$ is part of the continuous spectrum (this is an easy exercise, and you can also find it on this site).
An example where every element of the spectrum (except potentially zero) is an eigenvalue is the case of a compact, self-adjoint operator on a Hilbert space.
Comment: @timur $Mf(x)=xf(x)$.
Comment: What does the multiplication operator do exactly?
Answer: OK, so in mathematics the spectrum of a matrix is the set of its eigenvalues.
I know it's confusing, so let me explain.
The spectrum of a matrix is basically a linear map of the matrix. You can imagine it as some kind of finite number line, but with eigenvalues as the numbers.
Actually, there is a much more better answer on Wikipedia:
"Let V be a finite-dimensional vector space over some field K and suppose T: V → V is a linear map. The spectrum of T, denoted σT, is the multiset of roots of the characteristic polynomial of T. Thus the elements of the spectrum are precisely the eigenvalues of T, and the multiplicity of an eigenvalue λ in the spectrum equals the dimension of the generalized eigenspace of T for λ (also called the algebraic multiplicity of λ).
Now, fix a basis B of V over K and suppose M∈MatK(V) is a matrix. Define the linear map T: V→V point-wise by Tx=Mx, where on the right-hand side x is interpreted as a column vector and M acts on x by matrix multiplication. We now say that x∈V is an eigenvector of M if x is an eigenvector of T. Similarly, λ∈K is an eigenvalue of M if it is an eigenvalue of T, and with the same multiplicity, and the spectrum of M, written σM, is the multiset of all such eigenvalues."
( Taken from wikipedia, link here: https://en.wikipedia.org/wiki/Spectrum_of_a_matrix)
But it's full of technical terms, so if you're new to this field, I would suggest you think of it as a simple number line. That's it!
Hope this helped you! :)
(Please upvote.)
Comment: @lux: An operator on an infinite-dimensional space may have additional elements in its spectrum, and may have no eigenvalues.
Comment: Hope this helped!

Spectrum vs eigenvalues


Too much bootup time

Question: So i have Ubuntu 22.04.2 LTS installed on my laptop. It takes more than 2 mins to bootup which seems too much for me. When i had installed Ubuntu on my machine a couple of months ago it didnt take this much time. Here are the logs generated by "systemd-analyze" and "system-analyze blame" respectively
isaac@Isaac-Lenovo-IdeaPad-S145-15AST:~$ systemd-analyze

Startup finished in 4.979s (firmware) + 8.472s (loader) + 4.847s (kernel) + 1min 59.732s (userspace) = 2min 18.032s graphical.target reached after 1min 59.606s in userspace
isaac@Isaac-Lenovo-IdeaPad-S145-15AST:~$ systemd-analyze blame

1min 22.046s fstrim.service
 57.290s plymouth-quit-wait.service
 37.756s systemd-journal-flush.service
 33.487s dev-mapper-vgubuntu\x2droot.device
 31.672s apt-daily.service
 26.775s snapd.service
 23.608s logrotate.service
 21.060s networkd-dispatcher.service
 20.841s snap-bare-5.mount
 19.967s snap-core18-2714.mount
 19.579s NetworkManager-wait-online.service
 19.316s snap-core18-2721.mount
 18.666s udisks2.service
 18.013s snap-core20-1778.mount
 16.502s snap-core20-1852.mount
 13.452s snap-core22-583.mount
 13.435s ModemManager.service
 13.344s accounts-daemon.service
 13.160s dev-loop28.device
 13.022s dev-loop19.device
 12.719s dev-loop18.device
 12.715s dev-loop23.device
 12.713s dev-loop26.device

Also here are my specs
CPU : AMD® A6-9225 radeon r4, 5 compute cores 2c+3g × 2
GPU : No external. iGPU (STONEY (stoney, LLVM 15.0.6, DRM 3.42, 5.15.0-69-generic))
HDD : 1TB
RAM : 4GB
OS  : Ubuntu 22.04.2 LTS (64 bit)
SSD : No SSD

So is there any solution to this problem? Also is there any fault in my system or do i just need to upgrade my hardware...?
[Solved] Thanks to @Archisman Panigrahi i was able to remove all the snap apps and the snap itself which decreased my bootup time at a noticable degree. Here are the logs after removing snap
isaac@Isaac-Lenovo-IdeaPad-S145-15AST:~$ systemd-analyze
Startup finished in 5.810s (firmware) + 5.990s (loader) + 5.145s (kernel) + 1min 35.600s (userspace) = 1min 52.547s
graphical.target reached after 1min 35.524s in userspace

isaac@Isaac-Lenovo-IdeaPad-S145-15AST:~$ systemd-analyze blame
49.362s plymouth-quit-wait.service
31.030s systemd-journal-flush.service
23.653s dev-mapper-vgubuntu\x2droot.device
17.721s systemd-udevd.service
16.684s networkd-dispatcher.service
15.613s NetworkManager-wait-online.service
13.481s udisks2.service
10.818s accounts-daemon.service
 8.654s ModemManager.service
 7.616s power-profiles-daemon.service
 7.567s polkit.service
 7.249s cups.service
 7.019s gdm.service
 6.680s NetworkManager.service
 6.674s bluetooth.service
 6.170s switcheroo-control.service
 6.134s thermald.service
 6.133s systemd-logind.service
 5.845s wpa_supplicant.service
 4.695s systemd-resolved.service
 3.518s rsyslog.service
 3.078s apparmor.service
 2.785s e2scrub_reap.service

Comment: HDDs are slow to boot from, get an SSD.
Comment: Some settings to review, and more links to additional suggestions. https://askubuntu.com/questions/1284302/is-it-possible-to-make-ubuntu-20-04-boot-faster I find Kubuntu a bit faster, but still has everything I want. And SSD does make a huge difference. They are not as expensive anymore and you still can use an HDD for backup or data.
Comment: @Tenkyless I don't think the boot speed can be improved any further (unless you disable important system services which you may not use). You don't have to upload new logs.
Comment: A combination of only 4GB RAM and a slow hard disk.
Comment: A previous comment I made had my server booting at 2 minutes 43 seconds.  But following through and removing unnecessary snaps (like in the answer below) from the system I was able to cut down the boot time of my server with HDDs only to 1 minute 28 seconds.
Comment: Old HD so why is fstrim. service active?
Comment: @nobody dont know why fstrim.service was active before. Though after removing snap i cant find it in the logs generated by 'systemd-analyze blame'. Feeling kinda weird...
Comment: @Tenkyless Can you check out the updated answer, and confirm if removing the log files as I described helps to speed up?
Comment: @ArchismanPanigrahi well i did. I didnt see any change in my bootup time. Its still around 1 min 55 sec ( 1 min 56.22s to be exact ). But i did see some noticeable change in my 'systemd-analyze blame' log. Dont know why my bootup time didnt change though. I can upload the logs if you want.
Comment: @ArchismanPanigrahi ahh i see... Also is there a possibility that my fstab file is causing the bootup issue..? Except for the /boot/efi no other mount point have any UUID associated with them... Also my fstab looks kinda messed up compared to others....
Comment: @Tenkyless You can ask a new question about fstab
Answer: The logs say that snap events take a lot of time in boot. I too have personally experienced this issue in older computers with HDDs, where removing snap improved the boot speed considerably. Replace all snap apps with apt apps, and uninstall snapd.
Here is how to replace Firefox snap, if you use Firefox, and here is how to remove snapd altogether.

You can also disable apt-daily.service (then you will have to regularly check for updates manually, and keep your system updated).
sudo systemctl disable apt-daily.service

Also, systemd-journal-flush.service is taking a lot of time. So, clearing the systemd logs can speed up the boot process further.
sudo journalctl --flush --rotate
sudo journalctl --vacuum-size=20M

You can also safely disable NetworkManager-wait-online.service
sudo systemctl disable NetworkManager-wait-online.service

Comment: My point being is that I really dislike snaps, but Canonical is making this tough on those of us that prefer LTS releases but don't want to reboot servers as often.
Comment: Great answer here!  +1  However, it is yucky that Canonical Livepatch is only available via Snap.  Grrrr!! But removing all the other garbage like the Snap Firefox, etc I was able to cut the boot time of my server by over half!  :)
Comment: OP seems to be using an old Ideapad. It is unlikely that they would need livepatch.
Comment: @Terrance Hmmm.

Too much bootup time


Angular2 RxJs: simple take() from http returned observable

Question: I simply try to .take(5) from an http returned observable:
this.dataObservable = this._service.getData()
                                   .take(5);

and use it in HTML like so:

This works. But I get all the records, I just want 5. What am I doing wrong? Thanks.
In the _service I return the http observable:
getData(): Observable<any> {
  url = '/getData';
  this._data = this._http.get(url)
    .map(response => this.extractData(response));
  return this._data;
}

Answer: This .take(5) will take 5 emits of your Observable, not 5 elements of that containing data.
You should limit it to 5 in your .map function.
Or .subscribe to that observable and in that function you will limit incoming data in store it in a local variable which will be bound to your template.
getData(): Observable<any[]> { // returns an array, right??
  url = '/getData';
  this._data = this._http.get(url)
    .map(response => this.extractData(response));
  return this._data;
}

// in your component
this.yourService.getData().subscribe(
   dataArray => this.data = dataArray.slice(0, 5),
   err => console.log(err)
);

this.data will be bound to your template.
Comment: Thank you, that makes sense. Could you expand how to limit the response in the .map with equivalent of .take what I'm trying to achieve?


Windows file API CloseHandle function throws an exception: "An invalid handle was specified"

Question: I've written function (in Visual C++ in MS VS 2013) not unlike as on
Recursively searching for files in the computer
Below is my function's source code:
wstring FolderPathValidator::FindRequiredFolder(const wstring& p_InitialPath, wstring p_RequiredFolderName)
{
    wstring foundFolder = L"";
    wstring folderPath = p_InitialPath + L"\\*";
    WIN32_FIND_DATAW folderInfo;
    HANDLE search_handle = FindFirstFileW(folderPath.c_str(), &folderInfo);
    if (search_handle != INVALID_HANDLE_VALUE)
    {
        vector<wstring> folders;

        do
        {
            if (folderInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                if ((!lstrcmpW(folderInfo.cFileName, L".")) || (!lstrcmpW(folderInfo.cFileName, L"..")))
                    continue;
            }

            folderPath = p_InitialPath + L"\\" + wstring(folderInfo.cFileName);

            if (folderInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                if (folderInfo.cFileName == p_RequiredFolderName)
                {
                    foundFolder = folderInfo.cFileName;
                    return foundFolder;
                }
                folders.push_back(folderPath);
            }
        } while (FindNextFileW(search_handle, &folderInfo));

        CloseHandle(search_handle);

        for (vector<wstring>::iterator iter = folders.begin(), end = folders.end(); iter != end; ++iter)
            FindRequiredFolder(*iter, p_RequiredFolderName);
    }

    return foundFolder;
}

The funcion begins to work without problems. But when it try to execute the line
CloseHandle(search_handle);

then the following exception has place:
First step of exception handling on address 0x76D712C7 в WordsCounter.exe: 0xC0000008: An invalid handle was specified.

Where 'WordsCounter' is the name of application executable file. The FindRequiredFolder function is the member of The FolderPathValidator class. FolderPathValidator class is located in static class library project. Both projects: the class library and C++ console application wich consumes the library are in the same solution. Among files and folders names sometimes occur Russian names in Cyrillic alphabet. But I don't think that Cyrillic folder or file names is the reason of this error. What the reason of this error? How can I correct it? Please help.
Comment: Offtopic: Instead of `if (folderInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)` use `if ( (folderInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 )`. This will prevent compiler warning in some cases.
Answer:
Use FindClose instead of CloseHandle. Where you read that you have to use CloseHandle?
Use T() or TEXT() macro, insteaf of L" prefix for unicode strings (TEXT( "" )).
Use lstrcmp without W. It is macro and calls lstrcmpW if your project is Unicode.
Comment: `2` and `3` are unrelated to the problem. Whether you explicitly use the Unicode APIs (with a `W` suffix) together with `L`-prefixed string literals, or the `_T`-macro with unspecified API versions (i.e. without an `A` or `W` suffix) is a matter of coding conventions, project goals, and personal taste. As long as you match API-calls and string literal encoding. The code is fine in this respect.
Comment: Ok, `2` and `3` were postscriptum. `1` is the answer of question.
Comment: Thanks FindClose helps!
Comment: I disagree with 2 and 3. However, 1 cannot be argued.


C++ Randomly change var to enum that is not itself

Question: At the moment, I can randomly choose from an enum and assign it to my variable:
(*itL).setDirection(static_cast<LadyDirection>(rand()% NUM_DIRECTIONS));

void Ladybug::setDirection(LadyDirection temp_direction)
{
    this->direction = temp_direction;
}

enum LadyDirection
{
    North,
    East,
    South,
    West,
    NUM_DIRECTIONS
};

What I want to do is make this change to a random enum value, that isn't what it currently is. Eg. If the direction is == North, set it to East, West or South, randomly.
I know I could do this with a few if/elseif statements, but I'd rather know if there's someway to do this nicer.
Thanks.
Comment: just  change direction to any random direction (different then actual) So just pick any random direction as you have and if different then original stop if not loop ...
Comment: I may not have made myself clear then, sorry for the confusion. I want to change this->direction to a value in enum that isn't what it already is. I think what you wrote above should work, I'll give it a try.
Comment: When I read it 3th time it was clearer :) (ignore the deleted comment part)
Comment: Thanks, one of the answers gave a good solution, which was also your solution. :) Any idea why this got a -1? I don't really see a problem with my question........
Comment: hard to say but most likely someone got the same impression of your text as I at the first read
Answer: Think of the list of directions as a circular list, generate a random number between (and including) 1 and NUM_DIRECTIONS - 1 and use it as a number of steps to move into the list:
void LadyBug::setDirection(int nSteps)
{
    this->direction = static_cast<LadyDirection>(
                     (this->direction + nSteps) % NUM_DIRECTIONS
    );
}

(*itL).setDirection(1 + rand()%(NUM_DIRECTIONS - 1)));

Answer: You could do this instead of your first line of code
r = rand() % (NUM_DIRECTIONS - 1); // limit the random to 0..2
new_direction = (old_direction + r + 1) % NUM_DIRECTIONS;

Answer:
could do this with a few if/elseif statements

I think you overestimate the complexity: just use rand() % (NUM_DIRECTIONS - 2) (so you'll never get West directly) and if you happen to hit on the current direction, use West instead, something like:
LadyDirection dir = itL->getDirection();
itL->setDirection(static_cast<LadyDirection>(rand() % (NUM_DIRECTIONS - 2));
if (itL->getDirection() == dir)
    itL->setDirection(West);

It would be simpler as a member function.


How to configure Linphone?

Question: How do I configure Linphone with managed SIP accounts when using Ubuntu? I cannot see the preferences button on the Linphone UI.
Answer: You can check this link http://www.voipbuster.com/en/sipp.html
Source : http://ubuntuforums.org/showthread.php?t=1737373

How to configure Linphone?


Cstring message contains the same character \n and it does not extract newline

Question: strPrompt is my input string that can be texts, numbers or symbols and has 2 lines:
- pause("this\n try is\n a test")
- pause("this try is the second try ")
I expect that \n  make new  line in CString message, but it doesn't happen and I see exactly the same text contains \n.
How can I extract newline to the message?
FTry Pause::ExecuteMyFunction() const
{
FTry try;
std::string strPrompt;

if( arg > 1)
    return ArgError( "The number of arguments are too much!");

if( arg == 1 && !arg( PROMPT, strPrompt))
    return ArgError( "Invalid message");

CString message = ( arg == 0 ? "Run the script?" :  strPrompt.c_str() );

return try;
}

Comment: I have already tried \r\n, but I got the same result . I see \r\n in the printed message.
Comment: Show the code in which you create the CStrings. The backslashes must be escaped somehow for this to happen.
Comment: @eran : THis is the way I create the CString.
Comment: `CString::CString(const CString& stringSrc)
{
 if (stringSrc.GetData()->nRefs >= 0 && stringSrc.GetData() != _afxDataNil) {
  m_pchData = stringSrc.m_pchData;
  GetData()->nRefs++;
 }
 else {
  Init();
  *this = stringSrc.m_pchData;
 }
}`
Comment: The CString constructor is not the issue. If the `arg` function assigns `PROMPT` into strPrompt, then how does PROMPT gets its content? I.e., is it a string literal with hardcoded `\n`s, or does it get its content from the console, command line or some text file? To make this simpler, create a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). The irrelevant code in your question is a distraction for both of us.
Answer: Windows require line ends to be the combination of \r\n, and not just \n. Add the \r and your lines will break properly.
(You mention you see the \n in the printed string. I'm assuming you see it as a space or weird char, and not as a backslash followed by an n. If the latter is the case, your strings contain an extra backslash)


Run c# commands remotely

Question: I am new to C# and one of my intentions in my program is to know a remote machine system architecture.
I found this command:
System.Environment.Is64BitOperatingSystem

that essentially gets the value of the environment property, but this only on the local machine i am developing from.
Is there a way to run this commnad, or any other command remotely?
Or, I know how to do that in PowerShell, by querying with Get-WMIObject with -ComputerName Parameter that gives my the option the query WMI remotely.
So maybe there another simple way to do that also in C#?
Thank you
UPDATE:
I used that link: https://learn.microsoft.com/en-us/windows/desktop/wmisdk/connecting-to-wmi-remotely-with-c- what Alex gave me, and in the article I need to use the assembly:
Microsoft.Management.Infrastructure

But I just can't reference it, or find it in my computer...
The microsoft article doesn't say anything about that assembly where I can find it.
Comment: with c# you also query WMI
Comment: [Connecting to WMI Remotely with C#](https://learn.microsoft.com/en-us/windows/desktop/wmisdk/connecting-to-wmi-remotely-with-c-)
Comment: See: [Win32_OperatingSystem](https://learn.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-operatingsystem). Often combined with [Win32_ComputerSystem](https://learn.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-computersystem) (useful to *extract* UserName / Domain / WorkGroup of a machine). See [here](https://stackoverflow.com/questions/49118708/get-serial-number-of-usb-storage-device-in-net-core-2-1?answertab=active#tab-top) (at the bottom of the code section) how to setup the WMI  ConnectionOptions for authentication
Comment: @AlexK. For some reason I cannot reference the Microsoft.Management.Infrastructrue assembly. I also cannot reference it. after searching online, no answer on where to download it :(
Comment: [Microsoft.Management.Infrastructure - NuGet](https://www.nuget.org/packages/Microsoft.Management.Infrastructure/). You should use it for monitoring purposes. If you just need to test a machine's system *bitness*, `System.Management` gives the same results.
Answer: I recommend you use PowerShell to run remote command since it's very common used . you can do it run it something like this :
Invoke-Command -ComputerName Server01, Server02 -FilePath c:\Scripts\yourPowerShellScript.ps1
You can run powershell scripts from c# as we can see here https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/
you can find more information in https://learn.microsoft.com/es-es/powershell/scripting/learn/remoting/running-remote-commands?view=powershell-6

Run c# commands remotely


PushStreamContent using SqlDataReader.ExecuteReaderAsync to stream CSV or delimited file to client

Question: I'm trying to utilize WebAPI to stream a large amount of data from SQL Server to a delimited file without waiting for the entire result set to return from the database.  I'm really terrible with Async and Await, haven't wrapped my head around it.  It seems what I'd like to do should be possible using the PushStreamContent and the SqlDataReader async methods.
This is at my DataAccessLayer:
<code>   Public Async Function ExecuteToResponseStream(command As SqlCommand, responseStream As IO.Stream) As Threading.Tasks.Task
      Using responseStream
         Dim newConString As String = _conString
         Using con As SqlConnection = New SqlConnection(newConString)
            Await con.OpenAsync()
            'Add params
            command.Connection = con

            Using ms As IO.MemoryStream = New IO.MemoryStream
               Using ts As IO.StreamWriter = New IO.StreamWriter(ms)

                  Using reader As SqlDataReader = Await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess)
                     While Await reader.ReadAsync()
                        Dim loValues As New List(Of String)
                        For i = 0 To reader.FieldCount - 1
                           loValues.Add(reader(i).ToString)
                        Next
                        Await ts.WriteAsync(String.Join(vbTab, loValues.ToArray))
                        Await ms.CopyToAsync(responseStream)
                     End While
                  End Using
               End Using
            End Using
         End Using
      End Using
   End Function
</code>
My repository has a method with signature of:
    Function ExportAsync(id As String, responseStream As IO.Stream) As Task
Finally, the WebAPI Client:
<code>   Public Function Export(id As String) As HttpResponseMessage
      Dim resp As New HttpResponseMessage(HttpStatusCode.OK)
      Dim onStreamAvailable As Action(Of IO.Stream, HttpContent, TransportContext) = Async Sub(responseStream, content, context)
        Await repository.ExportAsync(rc, responseStream)
     End Sub

      resp.Content = New PushStreamContent(onStreamAvailable)
      resp.Content.Headers.ContentType = New Headers.MediaTypeHeaderValue("application/octet-stream")
      resp.Content.Headers.ContentDisposition = New Headers.ContentDispositionHeaderValue("attachment")
      resp.Content.Headers.ContentDisposition.FileName = "Somefilename"

      Return resp
   End Function
</code>
The client function seems to exit appropriately and return the response, eventually.  The eventual response to the browser does indeed look like an attachment, it's empty, I suck at streams, but it seems like it not happening in that magical asynchronous way.
Also, it seems to me that this would be a somewhat simple exercise though I can't find a good implementation out there on the webs.  Perhaps I'm going about this completely wrong.
Answer: I've found something that used to / doesn't work.
Update
Repository Method
<code>Public Async Function ExportToCSV(inputParameters, stream As IO.Stream) As Threading.Tasks.Task
   'Build SqlCommand from inputParameters
   Await sqlClient.ReaderToDelimitedAsync(","c, _SqlCommand, stream)
End Function
</code>
Custom SqlClient Wrapper Method
<code>   Async Function ReaderToDelimitedAsync(delimiter As Char, command As SqlCommand, stream As IO.Stream) As Threading.Tasks.Task
  Try

     Await command.Connection.OpenAsync
     Using rdr As SqlDataReader = Await command.ExecuteReaderAsync
        Using sw As New IO.StreamWriter(stream, Text.Encoding.GetEncoding("Windows-1252"))
           Dim los As New List(Of String)
           For i = 0 To rdr.FieldCount - 1
              los.Add(String.Format("{0}{1}{0}", ControlChars.Quote, rdr.GetName(i)))
           Next
           Await sw.WriteLineAsync(String.Join(delimiter, los.ToArray))
           Await sw.FlushAsync

           While Await rdr.ReadAsync
              Dim loVals As New List(Of String)
              For i = 0 To rdr.FieldCount - 1
                 Dim strVal As String = rdr.GetValue(i).ToString
                 strVal = strVal.Replace(ControlChars.Quote, Chr(39)).Trim(Chr(10), Chr(13), Chr(32)) '.Replace(Chr(13), " ").Replace(Chr(10), " ")
                 strVal = strVal.Replace(vbCrLf + vbCrLf, vbCrLf).Replace(vbCrLf + vbCrLf, vbCrLf)
                 strVal = strVal.Substring(0, Math.Min(strVal.Length, 32000))
                 loVals.Add(String.Format("{0}{1}{0}", ControlChars.Quote, strVal))
              Next
              Await sw.WriteLineAsync(String.Join(","c, loVals.ToArray))
              Await sw.FlushAsync()
           End While

        End Using
     End Using
  Catch ex As Exception
     Throw ex
  End Try
   End Function
</code>
And to use it:
<code>  <HttpPost, ActionName("Download"), ValidateAntiForgeryHeader(False)> Public Function DownloadReport(postparameters) As HttpResponseMessage

      Dim resp As New HttpResponseMessage(HttpStatusCode.OK)

         resp.Content = New PushStreamContent(Function(stream, http_content, transportcontextcontext)
                                                 Return repository.Export(postparameters, stream)
                                              End Function, "text/csv")
         resp.Content.Headers.ContentType = New Headers.MediaTypeHeaderValue("text/csv")
     resp.Content.Headers.ContentDisposition = New Headers.ContentDispositionHeaderValue("attachment")
      resp.Content.Headers.ContentDisposition.FileName = reporttemplate.Filename

      Return resp

   End Function
</code>
I've also tried it like:
<code>   <HttpPost, ActionName("Download"), ValidateAntiForgeryHeader(False)> Public Function DownloadReport(postparameters) As HttpResponseMessage

      Dim resp As New HttpResponseMessage(HttpStatusCode.OK)

         resp.Content = New PushStreamContent(Async Function(stream, http_content, transportcontextcontext)
                                                 Await repository.Export(postparameters, stream)
                                              End Function, "text/csv")
         resp.Content.Headers.ContentType = New Headers.MediaTypeHeaderValue("text/csv")
     resp.Content.Headers.ContentDisposition = New Headers.ContentDispositionHeaderValue("attachment")
      resp.Content.Headers.ContentDisposition.FileName = reporttemplate.Filename

      Return resp

   End Function
</code>
The problem is that the download doesn't start at the client until the SqlDataReader closes (the End Using statement).  My understanding is that the PushStreamContent should return upon the first Await it encounters, and the subsequent calls to FlushAsync should start the delivery of the stream to the client.
I'm still terrible understanding this Async Await pattern.  Any thoughts?


multiple-level menu

Question: I have an app where I need a multiple level menu.
Think of this problem:

I have 5 bags (orange, blue, pink, red and green) in car 1
I want to copy more than one to car 2 and 3.

What do you think of this kind of menu?
First, the user selects the bags after that is possible to copy to multiple cars…

EDIT:
My bags are tabs, where I manage products.
I want a way of copying without needing new enviroment, a new click...
I tried this, but I want something more immediate.
Comment: Is this even considered a menu? A menu is a navigational component while this is a semi complex interaction for editing attributes to other attributes.
Comment: If I where a user with no experience in complex menu's/computers I would need a tutorial for this "form" / "menu". This is too complex
Answer: This is an option too, use this for every car you have. You could change the width of the input venster too.

When you click on it:

Use this live (just for how it looks).

multiple-level menu


Put on the bottom elements in an App on Android Studio

Question: I have an issue with my App on Android Studio.
I want to know how can I put on the bottom of my layout (in a fixed position) without ruining the structure on various smartphones. I'm using a Linear Layout and the elements to put at the bottom are :
Edit-text (comments area) + Button "Send comment" in the right of the Edit-Text. Thank you.
Comment: Post your layout
Comment: https://pastebin.com/NaiSVz3D <-- Here is my layout.
Answer: Ideal approach is to use a ConstraintLayout, because it will give you a lot of options to do that. Using a LinearLayout if the linear layout height is match parent. You can set the item property of gravity=bottom.
Sample Code of constraint layout
<androidx.constraintlayout.widget.ConstraintLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="16dp"
        android:background="@drawable/bg_input"
        android:hint="Taper votre message"
        android:padding="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/button"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:background="@drawable/bg_button"
        android:text="Send"
        android:textColor="@android:color/white"
        app:layout_constraintBottom_toBottomOf="@+id/editText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>

Comment: https://ibb.co/ZfcsDYQ (Tested with my phone)
https://ibb.co/w4v01sK (Tested with AVD on Android Studio). I used constraints but I don't know what the problem is..
Comment: @Davencode can you please share the xml for the layout? It will help to understand the problem. You can edit your question and add code.
Comment: @Davencode - I checked your layout the one without constraintLayout, it is a very complicated, nested and over-engineered layout - 4 levels of LinearLayoutCompat inside a LinearLayout. They have 2 recyclerViews and other views. You should check the Android guidelines and use fragments for sections and include layouts, etc. Also, I checked the images you provided. what is the issue in the layout? The editText and Button are aligned to the bottom of the page. Can you explain the problem?
Comment: The problem is that I want to put on a fixed bottom position the 2 elements (edit-text and button) but when I see that on my phone I saw the two elements more up like this https://ibb.co/ZfcsDYQ . And when I see the https://ibb.co/w4v01sK on my AVD manager, There's no moving up and I wanted that positioning. My question is.. why this thing happen? It's about the size screen? ho can I fix this?
Comment: Share the layout code, we can try to find the reason.
Answer: Maybe you can use a new Layout called ConstraintLayout. You have to put this new layout at the same level as your linear layout and it will not destroy your work.


React router scrolls new page down

Question: I came across an issue using react-router ^2.4.1 where if I scroll down on my home page and afterwards go to a new page it will also be scrolled down, as opposed to being at the top (expected behaviour).
I am using this starter pack: react-webpack-node and my routes.jsx looks like this
import React from 'react'
import { Route, IndexRoute } from 'react-router'
import cookie from 'react-cookie'

import App from 'containers/App'
import HomePage from 'containers/HomePage'
import WaitingListPage from 'containers/WaitingListPage'
import NotFoundPage from 'containers/NotFoundPage'
import SupportPage from 'containers/SupportPage'

/*
 * @param {Redux Store}
 * We require store as an argument here because we wish to get
 * state from the store after it has been authenticated.
 */
export default (store) => {
  const hasQueueToken = (nextState, replace, callback) => {
    if (cookie.load('queueToken')) {
      replace({
        pathname: `/waiting-list/${cookie.load('queueToken')}`,
        state: { nextPathname: nextState.location.pathname }
      })
    }
    callback()
  }

  return (
    <Route path='/' component={App}>
      <IndexRoute component={HomePage} />
      <Route path='/w_ref/:ref' component={HomePage} />
      <Route path='/waiting-list/:token' component={WaitingListPage} />
      <Route path='/waiting-list' onEnter={hasQueueToken} component={WaitingListPage} />
      <Route path='/support' component={SupportPage} />
      <Route path='/terms-and-conditions' component={TermsConditions} />
      <Route path='/privacy-policy' component={PrivacyPolicy} />
      <Route path='*' component={NotFoundPage} />
    </Route>
  )
}

Answer: React Router does not include scroll state management starting in version 2.0.0.
The recommended approach is to decorate the router with scroll-behavior using react-router-scroll as seen in this example:
import { applyRouterMiddleware, browserHistory, Router } from 'react-router';
import useScroll from 'react-router-scroll';

/* ... */

ReactDOM.render(
  <Router
    history={browserHistory}
    routes={routes}
    render={applyRouterMiddleware(useScroll())}
  />,
  container
);

Comment: Thanks I have this working great. Just wondering if there's a way to scrollToBottom on page load of route X.
Answer: @John Trichereau:
scrolling to bottom can be done by giving a callback to useScroll, your callback would look like:
function customScroll (prevRouterProps, location) {
  // on route /foo scroll to bottom
  if (location.pathname == '/foo') return 'fooBottomDiv';
  // on all other routes, follow useScroll default behavior
  return prevRouterProps && location.pathname !== prevRouterProps.location.pathname;
}

and you would pass it to your router like this:
<Router render={ applyRouterMiddleware(useScroll((prevRouterProps, { location }) => customScroll(prevRouterProps, location))) }>

In your page, you would need to insert an invisible div with id fooBottomDiv. If you don't want to insert such a div, then you can have customScroll return a 2-element array [x, y] which could be [0, Number.MAX_SAFE_INTEGER] to scroll to bottom.
Documentation here
Note however that if your page has a component which loads data and displays it, it will most likely not work as the customScroll function is only called upon route matching, whereas your data is probably called asynchronously and received after route matching.
In this case, it's most convenient to use
ReactDOM.findDOMNode(this.refs.fooBottomDiv).scrollIntoView({ behavior: 'smooth' });

in React lifecycle methods componentDidMount and componentDidUpdate, where your component would contain an empty div with ref attribute ref='fooBottomDiv.

React router scrolls new page down


When there is the following entity, how should I write find where nestjs typeorm?

Question: I want to use the typeorm to find the desired value in the technical -> mapping table <-item relationship.
However, the error "Unknown column 'tnItem.itemId' in 'where cause' occurs.
I know that an error occurs because it is an item rather than an itemId in tnItem, but I don't know how to write a query.
my entity
<code>
@Entity("tn_item")
export class TechnicianItem extends BaseModel {
    @ManyToOne(() => Technician, (technician) => technician.tnItem, {
        primary: true,
        lazy: true
    })
    @JoinColumn([{ name: "tn_id", referencedColumnName: "tnId" }])
    technician: Technician;

    @ManyToOne(() => Item, (item) => item.tnItem, {
        primary: true,
        lazy: true
    })
    @JoinColumn([{ name: "item_id", referencedColumnName: "itemId" }])
    item: Item;

    @Column("int", { nullable: false, name: "period" })
    period!: number;
}
</code>
my method
<code>    async findAllTechnician(searchDto: SearchDto): Promise<Technician[]> {
        const findTechnician = await this.find({
            relations: ["tnItem", "tnConcept"],
            where: (qb) => {
                qb.where(`tnItem.itemId IN (${searchDto.items})`).andWhere(
                    `tnConcept.conceptId IN (${searchDto.concepts})`
                );
            }
        });
        return findTechnician;
    }
</code>
Answer: I was solved using the createQueryBuilder.
<code>    async findAllTechnician(searchDto: SearchDto): Promise<Technician[]> {
        const findTechnician = await this.createQueryBuilder("tn")
            .innerJoinAndSelect(TechnicianItem, "tni", "tni.tnId = tn.tnId")
            .innerJoinAndSelect(TechnicianConcept, "tnc", "tnc.tnId = tn.tnId")
            .where("tni.itemId IN (:items)", { items: searchDto.items })
            .andWhere("tnc.conceptId IN (:concepts)", {
                concepts: searchDto.concepts
            })
            .getMany();
        return findTechnician;
    }
</code>


Django Rest Framework - Can't specify seconds on DateTimeField HTML form

Question: I'm using the Django REST framework and trying to POST a DateTimeField on the HTML form, I can write everything but the seconds.
Here is a printscreen that shows what I mean:

I've tried to update the serializer to:
timestamp = serializers.DateTimeField(input_formats='%Y-%m-%dT%H:%M:%SZ')

But it didn't work.
Answer: Here is a reference to input formats and I think you can make your example work like this
DateTimeField(input_formats=['%Y-%m-%d %H:%M:%S'])

Comment: Thanks for answering but it doesn't exactly works.
Now when I try to input a different format it says it's wrong but the form doesn't let me write seconds yet. It "truncates" all numbers after I write the minutes. Here: https://imgur.com/aD4bhOq


Is there a way to turn off sections of script without just hiding it in comments?

Question: So I have built some custom macros within my main script (where I cobble together my usual tools) triggered by hotkeys. I am starting to accumulate these macros and would like to turn off certain sections of the script so I can use the hotkey again and can collapse the code section in my editor. I don't want to create separate scripts for these custom functions (no particular reason tbh).
I have tried wrapping the section of script in an if statement but it simply executes the code regardless of the condition (see below)
if(0){
   ^!s::
        <my script>
   return
}

From how I understand it the ^!s:: hotkey is compiled even if it is within a failed conditional and triggers the actions of the script regardless. Would this be the correct understanding? Is there a way to "turn off" that section of script without commenting it out?
Comment: Just a note about your code snippet, you need to have a `#` in front of the `if` for it to work that way (also braces aren't required, see link). More info here: https://www.autohotkey.com/docs/commands/_If.htm
Comment: `#If` or `Hotkey, If, [..]` is definitely the way to go if you want conditional hotkeys.
Comment: You could also just wrap everything in `/*` multiline `*/` comments, if you're editing the script anyway.
Answer: @EJE & @Joe DF
I believe the #If was what I was looking for. Thank you.