If i use one ground wire for two outlets, will my equipment get damaged?

Question: If i use one ground wire for two outlets, will my equipment get damaged?
Here is what I want to do:

If my air conditioner sends voltage through the ground wire shared with the outlet powering my computer, would my computer short out and or get damaged?
Comment: Just to be clear here: You have two 3-prongs in different boxes, but on the same circuit and you want to know if a ground fault on one will affect equipment on the other?
Comment: Possible duplicate of [Is it OK to borrow a ground wire from a different circuit?](http://diy.stackexchange.com/questions/10602/is-it-ok-to-borrow-a-ground-wire-from-a-different-circuit)
Comment: Where is this ground coming from? A wire in the cable? A separate ground you run to a cold water pipe? Other?
Comment: Just get a UPS with an always on battery and call it a day man.
Answer: Generally, adding a ground wire is always better for electronic equipment.  It helps surge suppressors do their job by providing a ground reference.   It provides real chassis grounding which among other things gives a solid route for  static electricity to go to ground instead of getting inside equipment.  It also provides a fault path if any hot wires short to ground, which assures you get a breaker trip.  And it makes sure equipment chassis is not energized so it electrocutes someone. I'm glad you're doing it - it will help.
That said, grounds will not cause cheap electronics with poor components  to suddenly become quality.  Grounds will not themselves "clean up" dirty, noisy AC power, although they will help surge suppressors do that.  Dirty power is often caused by your own equipment - for instance the air conditioner in your drawing.  You may want to protect the PC from the air conditioner.
Grounds also don't fix potential overloads, and you might have one here.  Fancy PC's aren't necessarily power hogs (the Mac Pro is only 2.5 amps) but "850 watt" PC power supplies are popular and they can draw 10 amps full bore (the difference being inefficiency).  A typical window air conditioner is 5-8 amps.  Loads which are continuous should only run at 80% of circuit capacity, that's 12A on a 15A breaker and 16A on a 20A breaker.  I would encourage you to investigate further to make sure those loads (and the other loads on that circuit) aren't too much.   To measure a device's actual current draw, gadgets like the Kill-A-Watt do nicely.
Answer: I think your concern is justified.  It is not uncommon to see a AC window unit dedicated with its own receptacle.  This is because of substantial startup current to get the thing a juggin'...
Always consult the manufacturer of the appliance in question.  Generally they will tell you if it's okay or not to share with another small appliance.
For general non-critcal computing with a small footprint you're probably ok with a small window unit.  But if you add a laser printer on the same circuit....forget about it!!


Practical applications of computer algebra systems

Question: (Sorry if this is not the correct place for the question)
Are there practical applications of symbolic computation systems like Mathematica, Sage, Maxima and the like in software development? To clarify what I mean - is there any point using CAS engines for developing end-user software (for example - machine learning in desktop and web software)?
Symbolic regression seems like something very beautiful, but it's current applications seem to be mostly theoretical.
Arguments like "It never rounds numbers unless it is told to do so" or "It can find antiderivatives" don't seem to impress people and "It does arbitrary precision calculations" doesn't seem to make much sense with available libraries like GMP (GNU multiple precision).
I have seen many people using symbolic computation engines for homework mathematical research, but it doesn't seem to make actual sense when it comes to using them to develop other software (mostly because these systems add much overhead). Yet there are Mathematica bindings for many programming languages.
Comment: It's not clear what you mean by "non-scientific".
Comment: I hope I've fixed it
Comment: You may be interested to see this link: [Groebner_basis#Applications_in_Science_and_Engineering](http://www.scholarpedia.org/article/Groebner_basis#Applications_in_Science_and_Engineering)
Comment: Another one is here: [New Maplesoft project for Toyota leverages symbolic computation in control systems engineering](http://www.maplesoft.com/company/publications/articles/view.aspx?SID=143072)
Comment: Both seem very interesting, thank you.
Answer: There are, at least, two ''practical'' kinds of situations where using symbolic computation is useful:
When exact values and calculations are required. If they are inaccurate, errors could amplify and lead to very bad results.
See the following Java code, which represent numeric values and operations according with the IEEE 754 floating-point standard:
<code>double x = 16    + 0.025;
double y = 16.05 - 0.025;
System.out.println(y - x);

output:
3.552713678800501E-15
</code>
The $x$ and $y$ values are mathematically identical, but in floating-point representation , they differ by a single bit, at the least significant position.
Arbitrary precision does not solve the problem, because $0.025$ in binary has an infinite representation $0.0000011001100...$ = $0.00000\overline{1100}$ so no matter how much precision is used, it had to be unavoidably either truncated or rounded.
I faced this problem when working with calculations of an interest rate with data from several banks. The single bit error had made that a bank had to pay -erroneously- an amount of money as penalty.
The solution was to delegate the calculations to a CAS (mathematica in my particular case, but another one should had worked as well) in order it can do the operations in symbolic form. Before calculations, the numbers were immediately converted to their rational form, so for example, the number $16.05$ is converted to $321/20$ -any CAS supports this simple operation-. At the end of calculations the results were converted back to floating point, but all  intermediate operations were performed not numerically but symbolic. It also worked because the CAS provides a way to be connected with an external program (through an API for example). Almost every CAS has support for it.
When is desirable to separate calculations from the main software There can be several reasons for it:

A large set or calculations is required, too many to be
hardcoded in a program. It could end with lot of mixed code (calculations and syntax required by the programming language) that could affect the readability of code, makes difficult its maintenance and is very error-prone.
The team that define and maintain the calculations (i.e. analysts) is different than the team that write programs. The first group usually does not deal with code.
The set of calculations changes frequently, or when changes, it must be available in a short time, too fast for programming work (coding, testing, deploying, etc.), specially if dealing with problems of type (1).
Calculations require functionality unavailable, or hard to code in the main program.

A typical applications is a payroll system, where conditions can vary at any moment, there are several external factors that change -i.e. taxing calculations- and yes, there is not enough time to change code.
I am writing a payroll program, it delegates all the calculations to a CAS named Fōrmulæ (http://www.formulae.org). The edition of the calculations is also delegated because it let expressions to be shown in pretty-print fashion and edited in a human style -it does not parse lines of text, as usual-.
Answer: Mathematica has extensive means of interface design and visualization, and there are thousands of demonstration notebooks around. They even designed their own "Computable Document Format".
Basically, it means that it can do all that can be done in Excel plus besides diagrams also complicated 3D and 2D dynamic graphics, high-speed networking and parallelization, operations on images, sounds and videos, including complicated integral transforms and after-effects.


Spring Boot & Angular 2: downloading a file from server

Question: I have app with Angular frontend and Spring Boot backend. In frontend I have html button, via I want to download file. Proble is that it behaves differently on remote server and on localhost:

localhost - after pressing button file is downloaded
<button download="output.txt" href="http://localhost:8080/output/output.txt"> Download </button>

remote server: after pressing button nothing happens
<button download="output.txt" href="https://www.bla.com/output/output.txt"> Download </button>

However, if I copy the url https://www.bla.com/output/output.txt into a browser the file is downloaded.
Answer: Solution was to used:
Download


How project/wizard is associated with perspective?

Question: After we create a new project in eclipse, a dialog will be showed as following picture if our current perspective is not associated with this kind of project. So how do Eclipse make this programmatically?

I think it depends on the project nature but the perspective extension point has nothing to connect with the project nature.
Tks for your time :-)
Answer: You have to set the finalPerspective attribute in your wizard. See
Associating a Wizard with a Perspective for reference:

Add the finalPerspective attribute to the definition of our wizard element in the extension.
Make the Wizard class implement the interface IExecutableExtension. This interface has only one method setInitializationData. Implement the method in the class and assign the parameter IConfigurationElement to a field in the method.
In the performFinish method of the Wizard, call BasicNewProjectResourceWizard.updatePerspective method.


Can I accelerate rendering an image from a ray cloud using a GPU?

Question: Start with a precalculated "ray cloud" - the starting point and direction of a large number of rays, most of which will not contribute to the image. The image plane's position and orientation are then specified, and the task is to search the ray cloud for rays that intersect the image plane without occlusion by other objects, and output the resulting pixel values. No ray reflections would be required, as all of the work has already been done in generating the ray cloud. The only step left is to convert the rays to an image. This means that a single ray cloud can be used to generate images from arbitrary view angles.
How could I go about accelerating this process using a GPU? The decision for each ray of whether it intersects the image plane is parallelisable as these decisions are independent, but each requires access to the objects in the scene as some rays will reach some potential image planes but not others. The final step of sampling the relevant rays across the pixels of the image requires each ray to contribute to a number of the surrounding pixels. Is this also parallelisable using a GPU?

To clarify, RichieSams' understanding is correct:

Start with a set of rays pointing in arbitrary directions.
Find which of these rays intersect with the image plane, taking into account occlusion.
Calculate the colour of each pixel based on the rays that hit the image plane.

Ideally I would like to be able to accelerate this process sufficiently to move around a scene in real time, given a precomputed ray cloud over the whole scene.
Comment: I'm going to give you a straightforward answer: GPU are turing complete. what do you conclude from this ? second answer: lux render http://www.luxrender.net/wiki/SLG
Comment: The best way to do this is probably using atomic operations for the scattered accumulation operations (when multiple rays may hit the same point), but you could render your entire "ray cloud" as points and do the intersection and occlusion calculations in a vertex shader, use a passthrough pixel shader and let the HW blender do the accumulation.
Answer: I'm not quite sure I fully understand the problem, this is what I think you're asking:

You start with a set of rays pointing a all sorts of directions
You want to know which of these rays intersect with the image plane, taking into account occlusion.
I'm going to assume these rays carry some kind of color information along with them. IE. when they hit the image plane, they will accumulate color.

With that goal in mind, I would do the following:

Create 2 image buffers

For accumulated color
To keep track of the number of hits

Clear the accumulation buffer to black, and the hitCount buffer to all zeros
Create a kernel per ray

Use classic ray tracing math to find the nearest intersection

Here you can do anything from a simple 'iterate through all the object in the scene' to something like BVHs, or kd-trees.

If the closest intersection is the image plane, use the WorldView matrix for the image plane to transform the intersection point from world coordinates to view space coordinates.
Use the x, y coordinates of the image space intersection point to get the pixel coordinates of the image buffer
Add the color of the ray to the corresponding pixel in the accumulation buffer
Increment the value of the corresponding pixel in the hitCount buffer

For 4 and 5 you could also use a filter in order to apply the color to multiple pixels, rather than just one. In that case, you would add a value less than 1 to the hitCount buffer

On the CPU, or in another pass per pixel:

Divide the accumulated color buffer by the hitCount buffer

I don't see any problem with doing these steps on the GPU. Any of the compute languages should handle it fine. You might get some divergence in the actual ray tracing code, but it should be ok. The biggest potential problem is that you have to store the entire scene in VRAM.
Answer: It sounds like the tricky part is that last step where each ray affects neighboring pixels. I would consider an approach where you do the first steps as normal (parallelized as on the CPU) without the last step, and then you do that last bit in a new pass. I'm not sure exactly how your ray contributions work so it's tough to say, but it seems like you should be able to use the results from the first part as input and then do your operation in a second pass.
Blur is done in a similar manner. The blur is done in one dimension, and then the output of that pass is used as the input of the second pass to blur the other dimension. The result is that the value of some pixel ends up contributing to neighboring pixels, so it's similar to your problem.


High memory usage with little swap space used

Question: I have 8Gb usable memory and 10Gb swap space available
My memory usage is 90-95% used while only +/- 1gb swap space is used.
Do I misunderstand the purpose of swap space or is there some issue on my side?
Thanks
Comment: Check my comment below.
Comment: You want to avoid swap, not using more of it. Swap is a partition on your HDD or SSD. Any are slower than RAM.
Comment: @CelticWarrior I am familiar with SWAP being a partition on your HDD, I check and have swap 12Gb actually. That which I do not understand is Linux running at 6Gb usage (atm), a few chrome tabs, QT Creator Studio, Plex, Atom and a few nautilus instances, all taking up 5.7Gb ram.  It seems that Windows has much beter memory management...(Yes I just said Windows MM > Linux MM :p)
Comment: With 8GB of RAM you could go without swap but it's better to have some, let's say ~2GB. I cannot and will not compare it to Windows and it's irrelevant for your question. In it you seem to imply you should be having more swap used which is nonsense. And the list you gave can easily take that much memory and more. FYI, any modern web browser will gulp as many as it can and what the tabs are matters way more than how many they are.
Answer: If you'd run the top command, you'd see something in line with this:
KiB Mem:  32868436 total, 32695528 used,   172908 free,       20 buffers
KiB Swap:        0 total,        0 used,        0 free. 31194124 cached Mem

In this particular case, we have 32 gigs of RAM, of which just 172 MiB is shown as "free".
We do not have swap at all in our case.
Yet, to calculate the "real" free memory, add "cached Mem" to "free" and you would see that almost all of the memory is free.
The trick is that "cached Mem" is basically disk cache - Linux would use most of available free memory just for that to speed up disk operations. Do not worry - should a necessity for extra memory arise, Linux can instantly reduce the disk cache and use that for whatever purposes are needed. You only need to start worrying once both "free" and "cached Mem" are very small - that would mean you probably need a RAM upgrade to keep things running smoothly.
As to swap, I would agree with the previous replies that you don't want to use it in vain in cases where you have plenty of RAM. And 8 gigs are plenty for a desktop, if you are not using some heavy graphics processing software or such.


How to map through an object but separate into sections based on an object property?

Question: Practicing my react and javascript to build a football app
I can map each object out from the api one after the other in this component but I would like to insert an extra row in, or start a new div when it is a new round of fixtures
(see results[key].round in the object being mapped out)
that will contain "Regular Season - 38" or so on for each one.
I tried using a for loop but couldn't insert it in ResultsTable and have the map continue
this is my data
const results = {
    340: { round: "Regular Season - 34", awayTeam: "Arsenal", statusShort: 'FT',...etc}
    341: { round: "Regular Season - 34", awayTeam: "Liverpool", statusShort: 'FT',...etc}
    342: { round: "Regular Season - 34", awayTeam: "Man City", statusShort: 'FT',...etc}
    343: { round: "Regular Season - 35", awayTeam: "Arsenal", statusShort: 'FT',...etc}
}

this is how
 render(){

let results = Object.keys(this.props.league_fixtures)
    .filter( key => this.props.league_fixtures[key]
    .statusShort !== 'NS' )
    .reduce( (res, key) => (res[key] = this.props.league_fixtures[key], res), {} );

const ResultsTable = Object.keys(results).map((key) =>

    {results[key].homeTeam}
     this.props.getFixture(results[key].fixture_id, results[key].league_id) }>{results[key].final_score}
    {results[key].awayTeam}

)

return(

      Home
      x
      Away

    {ResultsTable}

)
}

I want it to appear something like this
round 38

fixture
fixture
fixture

round 37

fixture
fixture
fixture

etc
Answer: The better way to get what you want, IMO, using lodash groupBy function to convert your array to the object with all keys are round
I assume your data will look like this:
const data = [
  {
    awayTeam: "Arsenal",
    awayTeam_id: "2",
    elapsed: "0",
    event_date: "2019-04-15T19:00:00+00:00",
    event_timestamp: "1555354800",
    final_score: "0 - 1",
    firstHalfStart: "1555354800",
    fixture_id: "fixture_id1",
    goalsAwayTeam: "1",
    goalsHomeTeam: "0",
    halftime_score: "0-1",
    homeTeam: "Watford",
    homeTeam_id: "18",
    league_id: "2",
    penalty: "-",
    round: "Regular Season - 33",
    secondHalfStart: "1555358400",
    status: "Match Finished",
    statusShort: "FT"
  },
  {
    awayTeam: "Arsenal",
    awayTeam_id: "2",
    elapsed: "0",
    event_date: "2019-04-15T19:00:00+00:00",
    event_timestamp: "1555354800",
    final_score: "0 - 1",
    firstHalfStart: "1555354800",
    fixture_id: "fixture_id2",
    goalsAwayTeam: "1",
    goalsHomeTeam: "0",
    halftime_score: "0-1",
    homeTeam: "Watford",
    homeTeam_id: "18",
    league_id: "2",
    penalty: "-",
    round: "Regular Season - 34",
    secondHalfStart: "1555358400",
    status: "Match Finished",
    statusShort: "FT"
  },
  {
    awayTeam: "Arsenal",
    awayTeam_id: "2",
    elapsed: "0",
    event_date: "2019-04-15T19:00:00+00:00",
    event_timestamp: "1555354800",
    final_score: "0 - 1",
    firstHalfStart: "1555354800",
    fixture_id: "fixture_id3",
    goalsAwayTeam: "1",
    goalsHomeTeam: "0",
    halftime_score: "0-1",
    homeTeam: "Watford",
    homeTeam_id: "18",
    league_id: "2",
    penalty: "-",
    round: "Regular Season - 35",
    secondHalfStart: "1555358400",
    status: "Match Finished",
    statusShort: "FT"
  }
 ]

Using lodash groupBy
const groupedData = _.groupBy(data, 'round'); // _ is community standard for lodash object

You will get the object looks like this:
{
  'Regular Season - 33': [{...}, {...}] // Array objects with round is 33
  'Regular Season - 34': [{...}, {...}] // Array objects with round is 34
  'Regular Season - 35': [{...}, {...}] // Array objects with round is 35
}

Then you will iterate over the groupedData and Object.keys(groupedData) to render
const keys = Object.keys(groupedData);

return (

    {keys.map(key => (

{key}

        {groupedData[key].map(data => (

{data.fixture_id}

        ))}

    ))}

)

My render function does not render table as you want but you got the idea.
Hope this help.
Comment: my data is more of a object of objects, see my edit, I tried converting it to an array but how do I bypass the key?
Comment: did you try my approach ?
Comment: ye but I made a spelling mistake, this is perfect, thank you


Ubuntu 16.04/14.04 + Pro-Ject DS2 Ultra external DAC doesn't work

Question: i'd like to ask for some help, at the moment i'm struggling with that, maybe someone already knows this problem and/or even got a solution for that...
i bought an external DAC (Pro-Ject DAC Box DS2 Ultra) and i'd like to use it with my computer...based on the description from the company it doesn't need any drivers on Linux-systems, kinda "plug-n-play" device...but in my case it doesn't work...no sound, nothing even the system doesn't recognize this device...after some re- and unplugging alsamixer recognizes this as an external sound card, but refuses to use because of some kind of "protocol failure"
any ideas about what could be wrong? thanks in advance!
i tried it with Ubuntu 14.04 LTS (32bit), Ubuntu 16.04 LTS (64bit) and with Ubuntu Studio 16.04 LTS, resulkts are the same, no differences.
this is what i get till now:
ubuntu-studio@ubuntu-studio:~$ lsusb
Bus 002 Device 003: ID 04f2:b008 Chicony Electronics Co., Ltd USB 2.0 Camera
Bus 002 Device 002: ID 0951:1603 Kingston Technology DataTraveler 1GB/2GB Pen     Drive
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 007 Device 002: ID 0930:0508 Toshiba Corp. Integrated Bluetooth HCI
Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

ubuntu-studio@ubuntu-studio:~$ dmesg | grep -i usb
..
..
..
[ 247.431215] usb 2-2: new high-speed USB device number 5 using ehci-pci
[ 247.550578] usb 2-2: New USB device found, idVendor=2772, idProduct=0201
[ 247.550585] usb 2-2: New USB device strings: Mfr=1, Product=3, SerialNumber=0
[ 247.550589] usb 2-2: Product: DAC Box DS2 USB Audio 2.0
[ 247.550593] usb 2-2: Manufacturer: Project
[ 247.727218] usbcore: registered new interface driver snd-usb-audio
[ 252.898343] usb 2-2: 1:1: usb_set_interface failed (-110)
[ 252.902941] usb 2-2: 1:1: usb_set_interface failed (-71)
..
..
..

Comment: @Félicien Thanks for editing my question, indeed looks way better (i had no time, i'm in my workplace)
Comment: no pb, sorry I can't help you more
Answer: I am using a JRiver Id as my music server which initially failed to recognise the DS2 Ultra as a USB DAC. I eventually was given a firmware update by Henley Audio which after installing allowed the Id to recognise the DAC. However the DAC is unable to control the jitter when outputting 44.1 files at 44.1 via JRiver from the Id and also from my MBP. As a fix for this issue I am outputting 44.1 files at 88.2 which seems to eliminate the Jitter. Outputting 44.1 files at 44.1 via a chord Hugo 2 and Hegel HD30 show none of the jitter issues of the DS2 Ultra. Even though Project insist they cannot replicate the jitter issue my belief is that the firmware is not fully up to scratch yet with the DS2 ultra.
Answer: home site https://www.project-audio.com/en/product/dac-box-ds2-ultra/
download firmware update utitlity
https://www.project-audio.com/wp-content/uploads/2018/06/Pro-Ject_Firmware_Update_Utility.zip
Please uprade the firmware of your unit to minimum version 1.04 (in Downloads). After that your DAC Box DS2 ultra should work normal.
Comment: Does this Windows .exe program run in Linux and if so, how to run it?
Comment: upgrade firmware on windows only :(  ....run *.exe file in windows PC
Comment: hello alex alex, thanks for your answer! so is seems like there is no other way than upgrade this DAC via using a Windows PC and then after the firmware update it'll work wih Ubuntu flawless as it should be...sounds a bit weird, but if it works it's more than okay with me. i'll definately try it, thanks


Given an $n$, are there infinitely many finite fields $F$ such that none of the orders of $PSL_n(F)$ divide each other?

Question: Given an integer $n$, is there an infinite set of finite fields $F_i$, $i\in \mathbb{N}$ such that for $i\neq j$ we have that $|PSL_n(F_i)|$ does not divide $|PSL_n(F_j)|$.
The motivation is that then any finite group can be embedded in infinitely many finite simple groups without any of these simple groups embedding in each other.
Comment: Do you have a formula for the order of these groups?
Comment: Given that motivation, don't you only need this to be true for some specific $n \ge 2$?
Comment: Well, I just need it to be true for large enough $n$, as otherwise, we might not have the group embedded in the $PSL_n$. Just from the group perspective, one could indeed require quite a lot less than I ask.
Answer: This should be a comment, but as I cannot comment yet, I give it as an answer (made community wiki):
Given your motivation, it should be much easier to prove that for two finite fields $\mathbb{F}$ and $\mathbb{F'}$ of different characteristic the group $\mathop{PSL}_n(\mathbb{F})$ usually does not embed into $\mathop{PSL}_n(\mathbb{F'})$.
For this, look at the structure of $p$-Sylow subgroups for $p$ the characteristic of $\mathbb{F}$ rsp. not the characteristic of $\mathbb{F}$.
You can make your life easier by choosing the order of $\mathbb{F}^\times$ to be $\ne 1 \bmod n$ (and work with prime fields if it suits you better).

For instance, if G is the group you are embedding, take n to be max(|G|,3), and then for your Fi take all prime fields of size pi congruent to 1 mod n. Then the Sylow pi-subgroup of PSL(n,Fi) is non-abelian, while the Sylow pj-subgroup of PSL(n,Fi) is abelian, hence PSL(n,Fi) cannot embed in PSL(n,Fj).
The important part is solely that p > n, to ensure we get Sylows contained in a maximal torus.  The n ≥ 3 requirement makes the defining characteristic Sylow non-abelian, and avoids some issues when Fi is of size 4 or 5 and n is only 2, where one does get some embeddings, and when Fi is of size 2 or 3 and n is only 2 (or in general if n is 1), when we do not get simple groups.
Comment: I specialized your very good comment to an answer. As long as the field is big compared to the dimension, and the dimension is not too small, we can just check "abelian Sylow" versus "nonabelian Sylow" and be fine.  Your comments on making life easier are definitely true if one was taking smaller fields or dimension 2.
Comment: This certainly makes things easier. One thing I am uncertain of (a very small detail). Can we always embed a group of order $n$ in $PSL_n(F)$? I could only find an argument for how to embed it into $PSL_{n+1}(F)$
Comment: @Tobias: I think so, but I'm not completely sure. A group of order $n$ acts (regularly) on $n$ points. If you take these points to be the basis of an $n$-dimensional vector space over the field $\mathbb{F}$, the linear action of $G$ fixes the $1$-dimensional subspace generated by the sum of all $n$ basis vectors. If you take the quotient of the $n$-dimensional vector space by this one-dimensional subspace, you get an embedding of your group of order $n(>1)$ into $\mathop{GL}_{n-1}(\mathbb{F})$. Probably you can build your embedding using this, but I think it's worth another question.


Bash regex matching "0xffffffc0006e0584 is in some_function (/path/to/my/file.c:93)."

Question: In a Bash script I'm writing, I need to capture the /path/to/my/file.c and 93 in this line:
0xffffffc0006e0584 is in some_function (/path/to/my/file.c:93).
0xffffffc0006e0584 is in another_function(char *arg1, int arg2)  (/path/to/my/other_file.c:94).

With the help of regex101.com, I've managed to create this Perl regex:
^(?:\S+\s){1,5}\((\S+):(\d+)\)

but I hear that Bash doesn't understand \d or ?:, so I came up with this:
^([:alpha:]+[:space:]){1,5}\(([:alpha:]+):([0-9]+)\)

But when I try it out:
line1="0xffffffc0006e0584 is in some_function (/path/to/my/file.c:93)."
regex="^([:alpha:]+[:space:]){1,5}\(([:alpha:]+):([0-9]+)\)"
[[ $line1 =~ $regex ]]
echo ${BASH_REMATCH[0]}

I don't get any match. What am I doing wrong? How can I write a Bash-compatible regex to do this?
Comment: Try it like this `^([[:alnum:]_]+[[:space:]]){1,5}\(((\/[[:alpha:]]+)+)\.[[:alpha:]]:([[:digit:]]+)\)\.$` https://regex101.com/r/Lra9ue/1 The values are in group 2 and 4 `echo ${BASH_REMATCH[2]}` and `echo ${BASH_REMATCH[4]}`
Comment: Thanks @Thefourthbird, any reason why you had to partition the filename and the extension ?
Comment: That is because the repetition of `/` and 1+ alpha chars in a group to match a path like structure. The last repetition of the group will hold the match, in this case `/file`
Answer: In the first pattern you use \S+ which matches a non whitespace char. That is a broad match and will also match for example / which is not taken into account in the second pattern.
The pattern starts with [:alpha:] but the first char is a 0. You could use [:alnum:] instead. Since the repetition should also match _ that could be added as well.
Note that when using a quantifier for a capturing group, the group captures the last value of the iteration. So when using {1,5} you use that quantifier only for the repetition. Its value would be some_function
You might use:
^([[:alnum:]_]+[[:space:]]){1,5}\(((/[[:alpha:]]+)+\.[[:alpha:]]):([[:digit:]]+)\)\.$

Regex demo | Bash demo
Your code could look like
line1="0xffffffc0006e0584 is in some_function (/path/to/my/file.c:93)."
regex="^([[:alnum:]_]+[[:space:]]){1,5}\(((/[[:alpha:]]+)+\.[[:alpha:]]):([[:digit:]]+)\)\.$"
[[ $line1 =~ $regex ]]
echo ${BASH_REMATCH[2]}
echo ${BASH_REMATCH[4]}

Result
/path/to/my/file.c
93

Or a bit shorter version using \S and the values are in group 2 and 3
^([[:alnum:]_]+[[:space:]]){1,5}\((\S+\.[[:alpha:]]):([[:digit:]]+)\)\.$

Explanation

^ Start of string
([[:alnum:]_]+[[:space:]]){1,5} Repeat 1-5 times what is captured in group 1
\( match (
(\S+\.[[:alpha:]]) Capture group 2 Match 1+ non whitespace chars, . and an alphabetic character
: Match :
([[:digit:]]+) Capture group 3 Match 1+ digits
\)\. Match ).
$ End of string

See this page about bracket expressions
Regex demo
Answer: You are right, Bash uses POSIX ERE and does not support \d shorthand character class, nor does it support non-capturing groups. See more regex features unsupported in POSIX ERE/BRE in this post.
Use
.*\((.+):([0-9]+)\)

Or even (if you need to grab the first (...) substring in a string):
\(([^()]+):([0-9]+)\)

Details

.* - any 0+ chars, as many as possible (may be omitted, only necessary if there are other (...) substrings and you only need to grab the last one)
\( - a ( char
(.+) - Group 1 (${BASH_REMATCH[1]}): any 1+ chars as many as possible
: - a colon
([0-9]+) - Group 2 (${BASH_REMATCH[2]}): 1+ digits
\) - a ) char.

See the Bash demo (or this one):
test='0xffffffc0006e0584 is in some_function (/path/to/my/file.c:93).'
reg='.*\((.+):([0-9]+)\)'
# reg='\(([^()]+):([0-9]+)\)' # This also works for the current scenario
if [[ $test =~ $reg ]]; then
    echo ${BASH_REMATCH[1]};
    echo ${BASH_REMATCH[2]};
fi

Output:
/path/to/my/file.c
93


performance issues with React-Native flatlist with 100+ list items

Question: I am trying to use RN flatlist to show a large list of contact names (100+ items). I keep getting the following warning:

VirtualizedList: You have a large list that is slow to update - make
  sure your renderItem function renders components that follow React
  performance best practices like PureComponent, shouldComponentUpdate,
  etc.

Certain animated UI items get very sluggish whenever the list has more than 50 items in it, however the sluggishness gets a lot better once I scroll all the way down to the bottom of the list
I grab all the contacts in one go and store them in an array in a redux store. I have tried using props like initialNumToRender but cant seem to improve performance. Is there anything I can do to improve my list? I have never used RN FlatList before so any tips would be appreciated
Here is my list related code:
renderRow = ({item}) => {

 return (
  <ListItem
   title={item.firstName}
   chevronColor={colors.tertiary}
  />
 )
}

  <FlatList
   data={this.props.contacts}
   renderItem={this.renderRow}
   keyExtractor={item => item.id}
   initialNumToRender={10}
   removeClippedSubviews={true}
  />

this.props.contacts is the array of contact objects in the redux store
Comment: Maybe you can use this https://github.com/Flipkart/recyclerlistview
Comment: can you show the full implementation ! i think that is something relevant to your code  implementation!
Comment: you should see if you have the INFAMOUS QOUTE FOLLOWED "convert your components to PureComponents"
Comment: I will try implementing the recyclerlistview component. Documentation is lacking but ill try and get it working. Thanks
Comment: Possible duplicate of [react native 100+ items flatlist very slow performance](https://stackoverflow.com/questions/44384773/react-native-100-items-flatlist-very-slow-performance)
Answer: I ended up implementing recyclerlistview and followed this tutorial which explained how to get it working since the documentation is lacking. Its working miles better than flat list did. Very fast and smooth.
Comment: is it worthy? bcoz I'm in the deadline and want to refactor all flatList inside my app? it'll take a long time?
Comment: I have followed tutorial you provides and used it but it is taking too much time for rendering, is there any alternative ?
Answer: You can follow these code implementations.
For VIEWABILITY_CONFIG follow this link
const VIEWABILITY_CONFIG - {
  minimumViewTime: 300,
  viewAreaCoveragePercentThreshold: 100,
  waitForInteraction
}
const yourItemHeight = 108;
class yourClass extends React.PureComponent
...

_getItemLayout(data, index) {
return { lenght: yourItemHeight, offset: yourItemHeight * index, index }
}
 <FlatList
   data={this.props.contacts}
   renderItem={this.renderRow}
   keyExtractor={item => item.id}
   getItemLayout: {this._getItemLayout}
   initialNumToRender={10} // Vary According to your screen size take a lumsum according to your item height
   removeClippedSubviews={true}
   viewabilityConfig={VIEWABILITY_CONFIG}
  />


Catastrophic backtracking for largetext

Question: Hi I have regular expression to allow alphanumeric, comma(,) and FullStop(.) and for small words (like 10 characters) it is working fine. But for big words around 850 characters the application is hanging.
Below is my regex expression.
<code>/^(([a-zA-Z0-9\s]+[\s,])*\s?[a-zA-Z0-9]+){1}\.{0,1}$/
</code>
Some example text:

Excellent communication skills, Currently working with Infosys as
  member L and D team,Conducts V and A trainings, process trainings for
  new hires, involves in call monitoring, soft skill, email etiquettes
  training Identifies training needs and prepare action plans and is
  involved in preparing training contents,Has experience managing
  Competency Based training calendar each month across verticals,Very
  energetic, sincere and has right attitude towards career,Confident in
  her approach and has clear aspirations,Conversation and very good at
  listening,Seems to be a team player and believes in taking extra
  initiatives,Recommending a bit higher salary as she is going through
  her appraisals.Good education background, scored first class
  throughout,Very stable candidate working with Infosys since more than
  5 years

Could you please help me on this?
Comment: Edited your question and changed the tags accordingly.
Comment: Please provide some text input. Eventually, you could use anchors to let the regex engine come to an end (and fail) faster. Additionally, nested quantifiers (like your `+`, followed by a `*`) are often the cause of catastrophic backtracking.
Comment: @Jan I added the texts in two comments as it is not allowing to enter in one try.
Answer: The nested quantifiers and the fact that the same <code>\s</code> can be matched in many different ways by the regex open it up to catastrophic backtracking. Also, some simplifications are possible.
The following fails a lot faster:
<code>^([a-zA-Z0-9]+[\s,]+)*[a-zA-Z0-9]+\.?$
</code>
This matches a sentence of one or more alphanumeric words, separated by whitespace and/or commas, with an optional final period. The text you posted as a test subject fails because there is a period in the middle which is not allowed by the regex. If you want to allow periods there as well, just add it to the character class:
<code>^([a-zA-Z0-9]+[\s,.]+)*[a-zA-Z0-9]+\.?$
</code>
Comment: I am new to regx. Could you please provide complete regx here?

Catastrophic backtracking for largetext


Take $G$ to be a group of order $600$. Prove that for any element a in $G$ there exist a $b$ in $G$ such that $a = b^7$

Question:
Take $G$ to be a group of order $600$. Prove that for any element $a$ $\in$ G there exist an element $b$ $\in$ G such that $a = b^7$.

My thought process: since $a = b^7$ $\implies$ $|a| = |b^7|$. Consequently
 $\operatorname{lcm}(1,|a|) = \dfrac{1}{7}\operatorname{lcm}(7,|b|)$ implies  $7|a| = 7|b|$ so $|a| = |b|$. I don't know where I would go from here or if this is even the right approach.
Answer: Take the cyclic subgroup generated by $a$. It has some order $k$ so $a^{1+kn}=a$ for all $n$. Let $b=a^l$
$$
b^7=a^{1+kn}\\
a^{7l}=a^{1+kn}\\
$$
$7l \equiv 1 \; (mod \; k)$
Suppose $k=2$, then $l=1$ works and $b=a$ satisfies $b^7=b=a$.
Suppose $k=20$, then $l=3$ work $b=a^3$ satisfies $b^7=a^{21}=a$
What are the possible $k$ and what can you then say about the solvability of $7l \equiv 1$?
Answer: Hint: $\gcd(600,7)=1 \implies 1=600m+7n$. Indeed, $ 1 = 3 \cdot 600 - 257 \cdot 7$.
Comment: Don't understand this. The only thing I got from here is that you could have $a = a^{7n}$ I dont know how you can conclude from that $a^{7n} = b^{7}$ for some $b  \in G$ from your hint.
Comment: Well, if you can conclude that, then isn't $a^{7n} = (a^n)^7$...?
Answer: Proposition Let $G$ be a finite group and $n$ a positive integer. Then the map $f: G \mapsto G$ defined by $f(g)=g^n$ is a bijection if and only if gcd$(|G|,n)=1$.
Proof (sketch) Bézout yields $1=k|G|+mn$, for some integers $k, m$. Then $g=g^{k|G|+mn}=g^{mn}$. Hence if $g^n=h^n$, then $g=g^{mn}=h^{mn}=h$. So $f$ is injective and since $G$ is finite it must be bijective. Conversely, assume gcd$(n,|G|)\neq 1$. Then we can find a prime $p$ with $p \mid n$ and $p \mid |G|$. By Cauchy's Theorem there is a non-trivial $g \in G$ with order$(g)=p$. Then $g^n=g^{p \cdot \frac{n}{p}}=1^\frac{n}{p}=1=1^n$. Since $f$ is injective this yields $g=1$, a contradiction.
Comment: $g=g^{mn}=(g^{m})^n$ proves that $f$ is surjective.
Comment: Yes true, short cut.
Comment: Readers might be interested to know that the relevant direction $(\Leftarrow)$ in the above proof may be viewed as a special case of the *universality* of  *linear* gcds - see the remark in my answer.
Answer: First I show how to reduce it to computing $\,7^{-1}\!\pmod{\!600};$ then I explain why this reduction works so universally due to persistence of GCDs having linear (Bezout) representation.
$\langle a\rangle$ has order $\,n\mid 600\,$ so $\langle a\rangle$ is an image of $\,\Bbb Z/600,\,$ so it suffices to solve it mod $600;\,$ said more concretely $\,a\equiv 7b\pmod{\!600\!=\!nk}\,\Rightarrow\,a\equiv 7b\pmod{\!n}.$ $\,7^{-1}$ exists by $(7,600)=1;\,$ explicitly
$\!\bmod 600\!:\ 7b\equiv a\iff b\equiv a/7\equiv\color{#c00}{343}\,a,\ $ by $ \underbrace{\ 7^{\large 4}\equiv 1\,\Rightarrow\, 1/7\equiv 7^{\large 3}\!\equiv \color{#c00}{343}}_{\Large\ \ 7^{\LARGE 2}\, \equiv\ \pm1\ \bmod\, 24\ \,\&\, \ 25\qquad}$
Remark $\  $ The proof requires only the coprimality of $\,k,n = 7,600\,$ since then we have a Bezout equation $\, k'k - n' n = 1\,$ $\,\Rightarrow\,\bmod n\!:\   k'\equiv k^{-1} =: (1/k)_n\,$ so we can proceed as above, i.e.
$$\begin{align} \color{#c00}{na = 0}\,\Rightarrow&\,\  k'(ka) = (1\!+\!n'n)a = a\! +\! n'(\color{#c00}{na}) = a\ \quad\rm Additive\ Form\\[.4em]
\color{#c00}{a^{\large n} = 1}\,\Rightarrow&\,\ (a^{\large k})^{\large k'} =  a^{\large 1\ +\ n'n}\ \ \  =\ \  a\,(\color{#c00}{a^{\large n}})^{\large n'} =\ a\ \quad\rm Multiplicative\ Form\end{align}\quad$$
hence $\quad\ \   \bbox[5px,border:1px solid #c00]{\begin{align}
\text{if $\,\ n\,a = 0 = n\,b\ $ then }\ kb = a &\iff b = (1/k)_n\, a\\[.4em]
\text{if $\:\!\  a^n\, =\, 1\, =\, b^n \ $ then }\ b^{\large k} = a &\iff b =  a^{\large (1/k)_n}
\end{align}}$
This works so nicely because whenever a gcd has a linear representation (Bezout) it is universal,  i.e. the gcd persists in extension rings /algebras / modules  - just as above

Note $\ $ Alternatively we can invert $7$ mod $\ 600 = 24\cdot 25\ $ using Easy CRT as below
$\!\bmod 24\!:\ \dfrac{1}7\ \equiv\ \dfrac{49}7\ \equiv\ 7\qquad\qquad\qquad\ $
$\!\bmod 25\!:\ \dfrac{1}7\equiv \dfrac{-49}7\equiv-7\ \ {\rm so}\  \smash{\ \dfrac{1}7\equiv \overbrace{-7\!+\!25\left[\dfrac{14}{25}\bmod 24\right]}^{\text{by Easy CRT}}\! \equiv -7\!+\!25[14]\equiv \color{#c00}{343}\pmod{600}}$
Comment: Why should $G$ be cyclic? It could also be a non-abelian group of order $600$.
Comment: @Nicky Thanks for catching the conflicting notation. Now fixed, with elaboration.
Comment: See also [here](https://math.stackexchange.com/a/905196/242).


Not receiving OTP from Firebase Phone Auth(India)

Question: I'm creating an android app which uses signIn from Firebase Phone Auth.I was previosly using email verification , that worked like charm, now i'm migrating to Phone Auth on the same project. I'm writing my auth on a Fragment, when i was following the givenlink https://firebase.google.com/docs/auth/android/phone-auth, i got compilation error saying "None of the following functions can be called with arguments supplied" ON "PhoneAuthProvider.getInstance().verifyPhoneNumber", Following is the code,
gradle

    apply plugin: 'com.android.application'

    apply plugin: 'com.google.gms.google-services'

    apply plugin: 'kotlin-android'

    apply plugin: 'kotlin-android-extensions'

    apply plugin: 'kotlin-kapt'

    apply plugin: "androidx.navigation.safeargs.kotlin"

    android {
        compileSdkVersion 29
        buildToolsVersion "29.0.2"
        defaultConfig {
            applicationId "com.sstech.racemanager"
            minSdkVersion 22
            targetSdkVersion 29
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            }
        }
        // Enables data binding.
        dataBinding {
            enabled = true
        }

    }

    dependencies {
        // def versions
        def nav_version = "2.1.0"
        def lifecycle_version = "2.1.0"

    //    kapt("groupId:artifactId:version")
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
        implementation 'androidx.appcompat:appcompat:1.1.0'
        implementation 'androidx.core:core-ktx:1.1.0'
        implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
        implementation 'androidx.legacy:legacy-support-v4:1.0.0'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'androidx.test.ext:junit:1.1.1'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
        // Add the Firebase SDK for Google Analytics
        implementation 'com.google.firebase:firebase-analytics:17.2.1'

        // Add the SDKs for any other Firebase products you want to use in your app
        // For example, to use Firebase Authentication and Cloud Firestore
        implementation 'com.google.firebase:firebase-auth:19.2.0'
        implementation 'com.google.firebase:firebase-firestore:21.3.1'
        implementation 'com.google.firebase:firebase-storage:19.1.0'
        implementation 'com.google.firebase:firebase-database:19.2.0'

        // Fragment
        implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
        implementation "androidx.navigation:navigation-ui-ktx:$nav_version"

        // LifeCycle
        implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
        kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

        // Circle Image View
        implementation 'de.hdodenhof:circleimageview:3.0.1'
    }

Fragment Class

    class RegisterPage : Fragment() {
        lateinit var binding: FragmentRegisterBinding
        lateinit var callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks
        lateinit var mAuth: FirebaseAuth
        lateinit var otpPin: String
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?): View? {
            mAuth= FirebaseAuth.getInstance()

            binding = DataBindingUtil.inflate(inflater,
                R.layout.fragment_register,container,false)

            binding.loginAlready.setOnClickListener { view: View->
                view.findNavController().navigate(R.id.action_registerPage_to_logPage)
            }

            binding.register.setOnClickListener {
                    registerAUser(binding)

            }

            binding.loginImage.setOnClickListener{
                    selectimage()

            }

    //        view.findNavController().navigate(R.id.action_registerPage_to_logPage)

            return binding.root
        }

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
        }

        private fun selectimage(){
    //        val intent = Intent(Intent.ACTION_PICK_ACTIVITY)
    ////        intent.type="image/*"
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.type="image/*"
            startActivityForResult(Intent.createChooser(intent,"pick an image"),0)

        }
            var selectedImageUri : Uri?= null

        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)
            Toast.makeText(activity,"entered result",Toast.LENGTH_SHORT).show()
            if(requestCode==0 && resultCode== Activity.RESULT_OK && data != null){
                // image ok
                try {
                     selectedImageUri = data.data
                    val bitmap: Bitmap =
                        MediaStore.Images.Media.getBitmap(activity?.contentResolver, selectedImageUri)
                        binding.loginImageRound.setImageBitmap(bitmap)
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                        binding.loginImage.alpha=0f
                    }else{
                        binding.loginImage.visibility=INVISIBLE
                    }
    //                val bitmapDrawable = BitmapDrawable(bitmap)
    //                binding.loginImage.setBackgroundDrawable(bitmapDrawable)
                }catch(ex:Exception){
                    Toast.makeText(activity, ex.localizedMessage,Toast.LENGTH_SHORT).show()
                }

            }else{
                if(requestCode==0){Toast.makeText(activity,"resultCode ok",Toast.LENGTH_LONG).show()}
                if(resultCode== Activity.RESULT_OK){Toast.makeText(activity,"resultCode error",Toast.LENGTH_LONG).show()}

                if(data==null){
                    Toast.makeText(activity,"Data is empty",Toast.LENGTH_LONG).show()
                }

            }
        }

       private fun registerAUser(binding: FragmentRegisterBinding){
           val phno : String = binding.loginPhno.text.toString()
           val name : String = binding.loginName.text.toString()
            if(phno.isEmpty() || name.isEmpty() ){
                Toast.makeText(activity,"Phone number/Name should not be empty",Toast.LENGTH_SHORT).show()
                return
            }
           if(phno.length!=10) {
               Toast.makeText(activity,"Phone number should be 10 numbers",Toast.LENGTH_SHORT).show()
               return
           }

           verify("+91$phno")

       }

        private fun verify(phno: String) {
            verificationCallbacks()
            Log.i("ph",phno)
            PhoneAuthProvider.getInstance().verifyPhoneNumber(
                phno, // Phone number to verify
                60, // Timeout duration
                TimeUnit.SECONDS, // Unit of timeout
                this, // Activity (for callback binding)
                callbacks) // OnVerificationStateChangedCallbacks
            Log.i("ph","Code Sent")
        }

        private fun verificationCallbacks (){
            callbacks= object : PhoneAuthProvider.OnVerificationStateChangedCallbacks(){
                override fun onCodeSent(p0: String, p1: PhoneAuthProvider.ForceResendingToken) {
                    super.onCodeSent(p0, p1)
                    Log.i("ph","On Code Sent Cred $p0")

                }

                override fun onCodeAutoRetrievalTimeOut(p0: String) {
                    super.onCodeAutoRetrievalTimeOut(p0)

                }

                override fun onVerificationCompleted(p0: PhoneAuthCredential) {
                    Log.i("ph","Sign in verification callback")
                   signInWithPhoneAuthCredential(p0)
                }

                override fun onVerificationFailed(p0: FirebaseException) {
                    if (p0 is FirebaseAuthInvalidCredentialsException) {
                        Toast.makeText(activity,"Invalid request",Toast.LENGTH_SHORT).show()
                    } else if (p0 is FirebaseTooManyRequestsException) {
                        Toast.makeText(activity,"Quota Over contact Developer",Toast.LENGTH_SHORT).show()
                    }
                }
            }

        }

        private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential){
            mAuth.signInWithCredential(credential)
                .addOnCompleteListener { task: Task<AuthResult> ->
                    if (task.isSuccessful) {
                        // Sign in success, update UI with the signed-in user's information

                        val user = task.result?.user
                        // ...
                    } else {
                        // Sign in failed, display a message and update the UI
                        if (task.exception is FirebaseAuthInvalidCredentialsException) {
                            // The verification code entered was invalid
                        }
                    }
                }

        }

    }

After Trail and error my error goes away after i put MainActivity() in the "activity" place, but i'm not receiving OTP if and the code is not going into OnCodeSent function.(I've enabled phone Auth on my console)
Can someone help here.
Answer: When i changed my authtication system from mail to phone number, I've forget to reconnect my app to firebase.
After reconnecting everthing works fine


The "username" field below is not populating in my Mysql database

Question: I'm trying to create an image gallery for a social networking site that I am working on for a college project but I can't seem to get the "username" field to populate in my database. The galleryimage field populates fine, but the username field just displays "0". I have 3 fields in my "gallery" table (id, username, and galleryimage). I'm using MVC with CodeIgniter framework. Seems to be a problem with my Active Record code. Any help would be greatly appreciated.
Here are the get/set functions in my model:
        private $galleryTable = 'gallery';

          function Gallery()
          {
            parent::__construct();
          }

The putProfileGallery populates the gallery table in my database.
         function putProfileGallery($username, $image)
          {
            $record = array('username' => $username, 'galleryimage' => $image);

            $this->db->where('username', $username)->insert('gallery', $record);
          }

The getProfileGallery function loops through the table and is supposed to output to the screen.
         function getProfileGallery($username)

          {
            $this->db->select('*')->from('gallery')->where('username', $username);
            $gallerySet = $this->db->get();

            $gallery = array();
            foreach ($gallerySet->result() as $row)
            {
                $gallery[] = array('username' => $row->username, 'galleryimage' => $row->galleryimage);
            }
            return $gallery;
          }
         }

Answer: You can't combine where and insert.
$this->db->where('username', $username)->insert('gallery', $record); should be only $this->db->insert('gallery', $record);
You should use update if you want to update a row.
Comment: Hi Shomz, I have removed the where() but still not having any luck, any suggestions?
Comment: Hi, what does `echo $this->db->last_query();` output if you put it right below the insert part?
Comment: Hi Shomz, it outputs:  INSERT INTO `gallery` (`user`, `galleryimage`) VALUES (0, 'http://localhost:8080/ci/spacebook2/assets/images/thumbnails/lisasax167.gif')
Comment: Hi, then there's a problem right where you're calling the `putProfileGallery` function - check what is the first parameter you're sending. You haven't shown that part of the code.
Comment: Hi, this is where I'm calling the function in the controller: $username = $this->session->userdata('galleryimage');
    $image_data = $this->upload->data();
    $filename=$image_data['file_name'];
    $this->gallery->putProfileGallery($username, base_url()."spacebook2/assets/images/thumbnails/".$filename);
    redirect('mygallery');
Comment: Got it - just needed to change "$this->session->userdata('galleryimage')" to $this->session->userdata('username')  --> thanks a million for your help - happy xmas :)
Comment: No problem, I'm glad I could help! Enjoy your holidays :)
Answer: Have you tried doing this before you invoke the insert function, in order to make sure that $username has a correct value
var_dump ($username);

Besides that, I see that you have a where() before insert(), which does not seem correct.
Comment: @imac23 What datatype is "name" in your table?
Comment: Thanks for your response tomor, I removed the where() and ran the var dump - it threw up: string(4) "Bart" (Bart being the user loggged in) still no joy :( --> any suggestions? cheers!
Comment: Hi Damien, it's a VARCHAR - it has populated in the past, but doesn't want to work for me for now...


Read from text1 and write to text2

Question: I'm new to shell scripting.
I would like to write a script to read from text1 file and get a value from this file.
This is the content of the text file:
L_T4000-Level3-Ouerdia  6679088203.600000   1523.208000
L_T4000-Level3-Ouerdiaa 8230141220.800000   1526.263200
L_T4000-nodeATI_Wardiaa 444039671.536000    4091589798.080000
L_T4000-node_TIS    6663189651.680000   2080241494.000000
L_T4000-node_TISa   6636796103.440000   2044580242.080000
L_International_node-globe  115911592756.879990 22433604426.723553
L_CRS_X-node06788   4801933455.200000   1329.232178
L_CRS_X-node06852   7100165206.800000   1630.996089
L_CRS_X-node06852a  7841650889.760000   1176446198.640000

I want to get the first value from the line with L_International_node-globe and format this value to float, and write the new value to text file2
In this example the output should be the value '115911592756,879990' and this value should be stored in another text file.
What do you think about this code:
#!/bin/bash

text1="/path/to/filename1"
text2="/path/to/filename2"
var=0
grep 'L_International_node-globe' text1|tr -s ' ' '\t'|cut -f 2 | sed 's/\./,/' > $var
$var=$var/1000000000        #the result should be in Gigabits
echo $var > text2           #on every execution text2 should have a new value

This script should be executed every 5 minutes, so what do you think about the resource utilisation?
Comment: Welcome to Ask Ubuntu! Please [edit] and show what you got so far, where you encountered any problems and what exactly they are.
Comment: Have you tried the command lines in the answers yet? If not, please try them and let us know if they do what you want.
Comment: Do you want to write to the file or append to the file (write a new file or add a line at the end of an old file)?
Comment: every execution text2 should have a new value
Comment: I think that the edited command line (at the end of my answer) should do what you want. Comments on your edited question: 1. Variables should be preceded with `$` when their values are *used*,  so in the 'grep command line' `$text1` and in the 'echo command line' `$text2`; An integer division can be done in the shell with `var=$((var/1000000000))`, but I would recommend a tool with floating point capability, for example install and use `bc`.  I will look more into the details and after that edit my answer.
Comment: I think a script like this is OK to run every 5 minutes.
Answer: Original answer
The following command line should do what you want,
grep 'L_International_node-globe' text1|tr -s ' ' '\t'|cut -f 2 > text2

print the line with the keyword (and value) you want from the file text1
convert space separation to TAB
print the second field (first field after the keyword)
redirect the output to the file text2

I am not sure what you mean by float. The shell will print the character string, and various programs can interpret it as a number in float format.
Edit 1
OK, you want a comma as decimal separator. That is done with sed substitution.
grep 'L_International_node-globe' text1|tr -s ' ' '\t'|cut -f 2 | sed 's/\./,/' > text2

Edit 2
In response to your suggested shellscript I suggest the following modified version,
#!/bin/bash

if [ $# -ne 2 ]
then
 echo "
 Usage:    $0 <path/infile> <path/outfile>
 Example:  $0 text1 text2"
 exit
fi

# extracting the value

var=$(grep 'L_International_node-globe' "$1"|tr -s ' ' '\t'|cut -f 2)

echo "debug1: $var"

# install and use 'bc'
# calculation; 'scale' sets the number of decimals in the output (truncated)

var=$(echo "scale=3
$var/1000000000" | bc)  #the result should be in Gigabits

echo "debug2: $var"

# conversion to comma as decimal separator

var=${var/./,}

echo "debug3: $var"

echo "$var" > "$2"   # after every execution the output file should have a new value

Examples with data from your original question,
$ ./scriptname

 Usage:    ./scriptname <path/infile> <path/outfile>
 Example:  ./scriptname text1 text2

$ ./script-name text1 text2 ; echo '-----------';cat text2
debug1: 115911592756.879990
debug2: 115.911
debug3: 115,911
-----------
115,911

Comment: @MekkiBenyounes, You are welcome :-)
Answer: Assuming by "floating point" you mean [-]d.ddde±dd "scientific notation" you could use awk
awk '/L_International_node-globe/ {printf("%e\n", $2)}' text1 > text2

You can use specifier %g if you want the format to change between %f and %e depending on the size of the exponent.
Comment: OP just wants to have the decimal point replaced by comma, how about `{$0=$2;sub(/\./,",");print}` instead?

Read from text1 and write to text2


Calculate double integral of ...

Question: I was doing a homework problem but now I'm stuck. The problem says:
Calculate $\iint_{S} \frac{dx dy}{\sqrt{2a - x}}$ where S is a circle of radius $a$ which is tangent to to both coordinate axes and is in the first quadrant
The cartesian equation for a circle of radius a, and center C(a,a) is:
$$(x-a)^{2}+(y-a)^{2} = a^{2}$$
Sketching this equation for different values of $a$ I obtained the limits of integration for the double integral:
$$4\int_{a}^{2a} \int_{a}^{a+\sqrt{2ay-y^{2}}} \frac{1}{\sqrt{2a-x}}dx dy$$
It is multiplied by 4 because that double integral only calculates a quarter of the desired area. Then evaluating the double integral I obtained this:
$$4 \left ( 2a^{3/2}+2\int_{a}^{2a} \sqrt{a+\sqrt{2ay-y^{2}}} dy \right )$$
But I was stuck on this (I've tried to put the indefinite  integral$\int \sqrt{a+\sqrt{2ay - y^{2}}} dy$ into Wolfram Alpha and I obtained this ), then I said "why I don't use polar coordinates?" and I used them, and I obtained this double integral:
$$4\int_{0}^{\pi /2} \int_{0}^{a}\frac{r}{\sqrt{2a-rcos\theta}} dr d\theta$$
I evaluated it, and I obtained:
$$4\left ( \int_{0}^{\pi/2} -\frac{2}{3}\left ( \sec ^{2} \theta \sqrt{2a-\arccos {\theta}} \left ( 4a + acos\theta \right ) \right ) d\theta  \right )$$
But Wolfram says this for the indefinite integral so... What can I do? Am I wrong in something? Is there another way to do it? I would appreciate any help.
Answer: Change the order of integration.
$$\begin{align}
\iint_S \frac{dx\,dy}{\sqrt{2a-x}} &= \int_0^{2a} \frac{1}{\sqrt{2a-x}}\left(\int_{a-\sqrt{a^2-(x-a)^2}}^{a+\sqrt{a^2-(x-a)^2}}dy\right) dx\\
&= \int_0^{2a}\frac{2\sqrt{2ax-x^2}}{\sqrt{2a-x}}\,dx\\
&= \int_0^{2a} 2\sqrt{x}\,dx.
\end{align}$$
You can take it from there, I'm sure.

Calculate double integral of ...


Store the nmServerStatus () result in a variable in python

Question: I am writing a python file which checks the current status of weblogic server and perform the required action(start/stop).
I am using nmServerStatus to get the status of weblogic status.
How can I store the the result of nmServerStatus in a variable ?
it's syntax is nmServerStatus (ServerName).
Let me know if any other information required.
Answer: Did you just try ? :
<code>adminServerStatus= nmServerStatus('AdminServer');
if( adminServerStatus != 'RUNNING'):
...
</code>


sql rows containing column twice (or more)

Question: using PhpMyAdmin, I am trying to retrieve a list of rooms that have all of a given set of facilities. I am able to query a table of rooms with facilities that I want, but I don't know how to filter out the rooms that appear for every facility.
Here is what I query:
SELECT distinct * FROM `Facilities` WHERE `Facility` = 'DVD Player' UNION
SELECT distinct * from `Facilities` WHERE `Facility` = 'Computer';

When I use    Group By 'Room' Having Count(Distinct 'Room') = 2 I get the right table with this order but if i select Computer and then union it and select DVD Player, I don't get the correct table.
My initial query before any grouping shows this:
Room    | Facility
A.0.0.1   Computer
G.0.02    Computer
HH.0.23   Computer
G.0.02    DVD Player
HH.0.23   DVD Player

I want the rooms that have both Computer and DVD Player. I have 22 Facilities in my table and I may want to be able to query any combination of them to find the matching rooms.
Answer: If you want rooms that have a particular set of facilities, try something like this:
select f.room
from facilities f
where f.facility in ('Computer', 'DVD Player')
group by f.room
having count(distinct f.facility) = 2;


Objects in a NSArray being set to nil under ARC

Question: I have an NSMutableArray that I store two objects in but they get replaced with nil in the array after a short while.  Why is that happening?  The array object is still around and shows it contains two objects, but they are both nil.
Doesn't the fact that they are in an array mean they are referenced and should not be deleted?
What is odd is that the objects I placed in the array are not being deleted as they are referenced by other objects, they are just being replaced with nil in the array.
-(void)addRender:(id)theRender
{
    if (renderArray == nil)
        renderArray = [NSMutableArray array];

    // Leaving this function and for a while afterwords, the object is in the array.
    // By afterwords, I think is until the autorelease pool is drained, but I can't
    // be sure but the objects are there as I am stepping though code.

    [renderArray addObject:theRender];
}

-(void)render
{
    // By the time this is called, renderArray has 2 nil objects in it.

    if (renderArray)
        [renderArray makeObjectsPerformSelector:@selector(render)];
}

The -(void)addRender function is being called from the objects init function.  I don't know if that matters, but self is set by then.
The objects themselves are not being deleted, just replaced with nil in the array.  What condition causes ARC to do that?  I've read about zeroing weak references, which does something like this, but I'm not declaring anything a weak reference, besides, the objects are still around and referenced places.
I've spent the last two hours beating my head against this.
Comment: How is renderArray variable defined?
Comment: It's defined as follows:  `NSMutableArray *renderArray;`
Comment: [NVM it's late]. Can you log NSLog(@"%@",renderArray) at the end of `addRender:` and the beginning of `render` and post the results?
Comment: Disregard my comment about recursion. I get it now. I was just confused by the same method name.
Comment: Does ARC have the ability to set an objects "name" to `nil`? (I don't do any iX programming/usage, but most of the time the object can be cleared, but *not* the pointers to such objects... if there were such pointers they should keep the object alive or now point to an invalid object? Or is there some magic in ARC that escapes me?)
Comment: OK, this is odd.  I added the NSLog statements as requested above and the object pointers are no longer being replaced with nil.  I removed the NSLog statements and it is still working correctly.  I didn't change anything else.  I wonder if some files just need to be (re)compiled.  I have no idea.  Still doesn't make any sense that the pointers would become nil in an NSMutableArray like that.  Wouldn't surprise me if there are still some small bugs in ARC.  It's pretty new and somewhat 'magical'.
Answer: renderArray is an autoreleased object and if you're only defining it as NSMutableArray *renderArray;, it's being released before you get a chance to use it in your render method.
Try defining it as __strong NSMutableArray *renderArray; which will tell ARC to keep it around for you.
Comment: renderArray is not being deleted, it is fine.  It's the objects inside the array that are being set to nil in the array.  I did try the __strong at one point and it didn't have any effect.
Comment: Yeah, as soon as I posted my answer I thought about it and realized I was probably not right. Overlooked the fact that you said the variable seemed to be valid.


Are there any items you can combine to make potions, food or equipment?

Question: Aside from combining items for quests and side quests, are there any items you can combine to make potions, food, weapons, et cetera?  I remember obtaining anvils and glass bottles from enemies, but I have no idea what they are for.  Any ideas?
Comment: I guess everyone's busy answering starcraft 2 questions :(
Answer: I don't know of any thing you can combine to make the weapons and food.
I did find that you can use the anvil to make the cherries fall down off the tree (see this GameSpot forum post for details).
From what I've seen, nobody's been able to figure out what to do with the glass bottles.
Comment: Well thanx for answering, I guess it will remain a mystery


calculating height of UITabBar

Question: I'm writing an app that uses UITabBar for parts of the navigation. I'm also using UIScrollView for presenting more information than what the screen can typically handle. Because of this, I'm needing to set the scroll view to take into account the height of the UITabBar so that all of the information is displayed.
Is there a way to calculate the height of the UITabBar?
Answer: If the view controller has an ancestor that is a tab bar controller, you can retrieve the height from that tab bar.
CGFloat tabBarHeight = self.tabBarController.tabBar.frame.size.height;

Answer: It is 320 x 49.
If you want to test, open Interface Builder, add a UITabBar, go into the ruler, you will see it
UITabBar is inherited from UIVIew so you can use the frame.size.height to get the height
Comment: Is it guaranteed to stay that way for all time? I would rather use the API to get the value than rely on using IB and inserting magic numbers into the app.
Comment: Assuming that your app delegate has a tab bar controller variable tabBarController the height can be accessed by
((YouAppDelegate *)UIApplication.sharedApplication.delegate).tabBarController.tabBar.frame.size.height
Comment: UITabBar is inherited from UIView, so you may try with frame.size.height of UIView
Comment: Will give that a shot when I get back from work. Do you know if I can get that without creating an instance of an object? Further, would it be better to create a dummy instance or to pass the in use UITabBar from the application delegate to the view I'm using so that it has a more accurate value?
Comment: When I use IB, I can not change the height of the UITabBar, so I think it would be fixed. If you want to use API, there is no class method for that:(
Comment: Many thanks. Still to be verified, but enough information to resolve the issue.
Comment: Just an update to Matt Delves solution, there's no need to expose tabBarController member in your app delegate. You can always access tabBarController from a UIViewController object which is a child (or one of its ancestors is a child) of your tabBarController like this: self.tabBarController.tabBar.frame.size.height
Comment: 320 & 49 are "magic numbers", both confusing and prone to error (example: wrong in iOS7 and on iPad.)  It also doesn't answer the question, which was: how to calculate these values (implied: **programmatically**.)  As I type this, Vladamir's answer seems best.
Comment: Hi Olie, I also mention that UITabBar is inherited from UIVIew so you can use the frame.size.height to get the height. So, if anybody who wants to go with promatically, they can go with it :)
Comment: It's still the same height on iOS 9.
Answer: In Swift:
let height = self.tabBarController?.tabBar.frame.height ?? 49.0

Relying on the actual height of the tab-bar, and using the magic number as a fallback.
Comment: this is wrong because the magic fallback number isn't 49 if the iPhone has  a notch, it's 83
Comment: Should have been `frame.size.height`
Answer: Swift 3+
let tabBarHeight = tabBarController?.tabBar.frame.size.height
print(tabBarHeight ?? "not defined")

It should print 49.0 (Type CGFloat)
Answer: I was looking to do something similar with centering a label in the VISIBLE portion of a ViewController's view. This ViewController belonged to a UITabBarController.
Here's the code I used to center my label:
UILabel *roomLabel = [[UILabel alloc] init];
CGRect frame = [[self view] bounds];
float tabBarHeight = [[[super tabBarController] tabBar] frame].size.height;
frame.size.height -= tabBarHeight;
[roomLabel setFrame:frame];
[[self view] addSubview:roomLabel];
[roomLabel release];

Notice that I used [[self view] bounds] not [[self view] frame] because the latter includes the 20 pixel top bar as the Y offset (which throws off the vertical centering).
Hope this helps someone!
By the way: I'm using iOS 4.3 and XCode 4 and the "hard-code" value for the TabBar's height is still 49 for me!
Answer: I know this isn't ideal, but I really didn't want to have a magic number constant anywhere.  What I did was create a throwaway UITabBarController, and get the height from there.
I did this also because [UITabBar initWithFrame:] works as desired, but doing a [bar setFrame:] doesn't.  I needed the frame to be correct at creation.
UITabBarController *dtbc = [[[UITabBarController alloc] init] autorelease];

CGRect tabRect = [[[self navigationController] view] frame];
tabRect.origin.y = tabRect.size.height - [[dtbc tabBar] frame].size.height;
tabRect.size.height = [[dtbc tabBar] frame].size.height;

tabBar_ = [[UITabBar alloc] initWithFrame:tabRect];

What I like about this is that it will correctly place the tab bar at the bottom of the parent regardless of the parents size.
Answer: This should work in most cases on any instance of UIViewController:
bottomLayoutGuide.length

Comment: Deprecated in iOS 11.0. I'm not sure what to use instead.
Answer: In swift 4 and 5. self.tabBarController?.getHeight()
extension UITabBarController{

    func getHeight()->CGFloat{
        return self.tabBar.frame.size.height
    }

    func getWidth()->CGFloat{
         return self.tabBar.frame.size.width
    }
}

Answer: Others can also try to get the height using the intrinsicContentSize property of the tab bar.
let tabBarHeight = self.tabBarController.tabBar.intrinsicContentSize.height

Answer: This is how I got it to work in swift 4.1
let tabBarHeight = CGFloat((self.tabBarController?.tabBar.frame.size.height)!)

Answer: Swift 5
    if let tabBarController = tabBarController {
        let tabBarSafeAreaHeight = tabBarController.tabBar.frame.size.height -
            tabBarController.tabBar.safeAreaInsets.bottom
    }

This calculates the height of the UITabBar taking into account the safeAreaInsets (UIEdgeInsets)
At the time of writing this equals 49 on iPhone portrait
Answer: let screenHeight = UIApplication.shared.statusBarFrame.height +
            self.navigationController!.navigationBar.frame.height + (tabBarController?.tabBar.frame.size.height)!

This works perfectly, based it of a few ppls answer here
Answer: SWIFT 5 UPDATE :
AS this thread is old, I am posting here the update from another thread: https://stackoverflow.com/a/25550871/14559220. To sum things up,

in portrait and regular landscape, the height is still 49 points. In
compact landscape, the height is now 32 points.
On iPhone X, the height is 83 points in portrait and 53 points in
landscape.

calculating height of UITabBar


View component doesn't update when row is added to list

Question: I have this view with a viewmodel too. I have an issue when I click on the add button the setRowView doesn't update with a new row. I have tried to change med my @StateObject to an @ObsvervedObject, but that didn't helped...
My SetViewModel is a class which also conform to the ObservableObject.
Exercise is also a class where the set property is and @Published.
class ExerciseCardViewModel: ObservableObject {

    @Published var execise: Execise

    init(execise: Execise) {
        self.execise = execise
    }

    func addSet() {
        execise.sets.append(DBSet(number: execise.sets.count + 1))
    }

    func deleteSet() {
        execise.sets.removeLast()
    }

    func createSetViewModel(sets: DBSet) -> SetViewModel {
        SetViewModel(sets: sets)
    }
}

struct ExerciseCard: View {
    @StateObject var viewModel: ExerciseCardViewModel

    var deleteExercise: (Execise) -> Void

    var body: some View {
        VStack {
            ForEach(viewModel.execise.sets) { set in
                SetsRowView(sets: viewModel.createSetViewModel(sets: set))
                    .listRowBackground(Color.theme.TBBlack)
            }

            HStack(spacing: 30) {
                button(action: {
                    viewModel.addSet()
                },
                       icon: "plus.circle",
                       title: "Set",
                       backgroundColor: .green)

                if !viewModel.execise.sets.isEmpty {
                    button(action: {
                        viewModel.deleteSet()
                    },
                           icon: "minus.circle",
                           title: "Set",
                           backgroundColor: .red)
                }
            }
            .padding(.horizontal)
        }
        .foregroundColor(Color.theme.TBLightGray)
        .padding()
        .background(RoundedRectangle(cornerRadius: 8)
            .foregroundColor(.theme.TBBlack))
    }

    private func button(
        action: @escaping () -> Void,
        icon: String,
        title: String,
        backgroundColor: Color) -> some View {
        Button {
            action()
        } label: {
            Text("\(Image(systemName: icon)) \(title)")
                .frame(width: 100, height: 30)
                .padding(.horizontal)
                .background(backgroundColor.opacity(0.3))
                .cornerRadius(8)
        }
    }
}

I hope you guys can help me :D
Comment: On the Exercise card is that how you init your VM? If so I think it should be @StateObject var vm: ExerciseCardViewModel = ExerciseCardViewModel()
Comment: No I actually init it from another view
Comment: https://stackoverflow.com/questions/68710726/swiftui-view-updating/68713038#68713038
Comment: StateObject should always be private but my guess is that Excercise and are sets are reference types and not value types or something along the chain. Every ObservableObject needs a property wrapper to observe changes.
Comment: If I changed it too value types, the data is only alive within that view. which means I don't have acces to it in the parent view...
Comment: Try adding objectWillChange.send() in the addSet function before appending the new object. Maybe it is that. I answered I similar question some time ago: https://stackoverflow.com/questions/77802118/what-is-the-correct-approach-to-refresh-a-view-based-on-changes-to-objects-insid/77802207#77802207. You should also consider injecting the ExcerciseCardViewModel from its parent view instead of passing it down directly, retrieving it as an @EnvironmentObject.
Comment: Binding is a two way connection between a source of truth and a value type. if you use reference types you have to observe them at every level. But you can try the new `@Observable`. Calling `objectWillChange` on `ExerciseCardViewModel` every time and exercise or a set changes will become unscalable and full of bugs. You would be redrawing everything every time instead of targeted redraws.
Comment: https://developer.apple.com/documentation/swiftui/migrating-from-the-observable-object-protocol-to-the-observable-macro
Comment: Good to know. You are right. Although I imagined it was doing something like that behind the scenes. I've actually never used it in my projects. I suggested it just because it worked for another user. By the way @Observable is only available on iOS 17+, we don't know the minimum deployment target the guy is using.
Comment: @MatBuompy a lot of people recommend that because it is "easy". It just overlooks all the hard work SwiftUI does to maintain efficiency. SwiftUI has its own set of rules and we just have to play by them, lol.
Comment: @MatBuompy the link I posted has samples for ObservableObject too very detailed old vs new.
Comment: @loremipsum I've seen it :)
Answer: Dear Frederik Hjorth, you seem to be facing a problem with nested @Published variables. I experimented with something very similar:
class ExerciseProgram: ObservableObject  {
    @Published var currentExercise: Exercise
    @Published var currentSet: Int
}

The name of the currentExercise is not a problem since it only changes when a whole new Exercise class is assigned and ExerciseProgram is automatically aware when the object referenced  by currentExercise changes.
In the case of currentExercise.currentSet (on the code above, I needed to make the ExerciseProgram itself contain a @Published property mirroring the data of my set.)
If you have @Published data nested in different layers of your code it becomes very messy. I personally like to use a ViewModel which is the only ObservedObject the View knows of, and make this class fetch/adapt and return data directly to the View, who's only aware of the ViewModel and the values it provides, everything else being transparent.
Related thread
Comment: So I just have to understand. Do I make a new object which going to look like this or similar maybe:
```
    class ExerciseProgram: ObservableObject {
        @Published var currentExercise: Exercise
        @Published var currentSet: Set
    }
```
And then my viewModel ExerciseCardViewModel contains my new object?
Comment: Yes, that's the idea. You can have a lot of layers and different objects/services behind `ExerciseProgram`, but everything `@Published` must be right under `ExerciseProgram`.
Comment: @Frederick Hjorth, did my suggestion work (or even made sense to you)? I can try to write more code here or communicate in another manner. Cheers,
Comment: Sorry have been on vacation so haven't look much on it. But I have it a bit hard to figured out how to link sets and exercises, if I can't have nested @published properties?
Comment: Is there any way I can show you some more context? about my setup so far?
Comment: I think you've shown enough context, I've created objects with a similar interface to your code and found the same problem as you did. It turns put you can't have and @ObservableObject inside another one, I've found there's quite some discussion on the web about it. Ive found this on linkedin
https://www.linkedin.com/posts/mohammad-azam-5537993_swiftui-activity-7158961708688891904-5aak?utm_source=share&utm_medium=member_ios
Comment: Okay, I think I have solve that problem for now. but what I don't understand is, if I for instance make a change in another child view, every child view in the parent view will be redrawn
Comment: @FrederikHjorth does the redraw cause any problem? It's very common on SwiftUI, and I wouldn't really worry about it unless it looks weird or causes unwanted animations etc. It it does, then I'd need more context like the code for the View and the Exercise. Otherwise feel free to upvote my answer :)
Comment: It is kind of strange. I have a view where I setup the program. Where the user can input the name, add exercises and for every exercise you can add sets. So for instance if I add an exercises and add sets to that exercise and after that change the name, the sets array will change to not contain any sets. I can add some code. but I might think that's better to do that in an answer so the formatting is alright I guess?


Removing rusted screw and wingnuts from toilet tank

Question: My toilet tank is held in place by two screws, which have rusted so much that the shape in their head is almost completely disappeared.
On the opposite side, they are held in place by two wingnuts made from plastic. I tried to losen one of them with pliers, but that only ended up in one wing breaking off.
Main question is: what is the best way to get it off, given the wingnuts?
I'm aware of this other question, and this is the answer I like most, which suggest using a mechnaic's nut cracker, but I have a few follow-up questions to that:

Is there a way to remove the bolts without cutting/drilling/breaking them? (Not that I need them, I'm just afraid of damaging the tank or the bowl in the process.) E.g., I read somewhere else that WD-40 might be enough, but did anyone actually try this with success? Also, where would I put it: between the wingnuts and the toilet bowl? Or below the head of the bolt? (It would be quite difficult to get into both places...) Or maybe with some rust-solvent?
Can the wingnuts also be broken by the mechanic's nut cracker? (Obviously, plastic would be easier to break than metal, but the shape might not make it easy to access.)
Also, as far as I see, this is a tool mostly for car shops (as the name suggests), so I guess a plumber would use some other tool. Which one would it be?

The two rusty bolts inside the tank:

A wingnut:

EDIT: Proper name for wingnuts.
UPDATE: Thanks everyone for the input. Yesterday I was able to remove one wingnut by gripping it really hard with pliers adjustable sized wrench. However, the screw itself is stuck, together with one gasket on the top, and one on the bottom.
The other one moved too a few turns, but it came to the point that now it is rotating together with the screw (and I could not find a way to stop the screw, because the head is so rusted).
Comment: Also that tool is quite expensive (for $350 I could buy a new tank...) Do you think a soldering iron would work too?
Comment: Heat, Heat, Heat... Using penetrating oil could take hours and come with multiple failed attempts, cutting, grinding, breaking the bolt or nut completely obliterates the reuse of the item and risks damaging the toilet, when removing a corroded nut or bolt, always use heat, whether that heat be a torch with kapton tape to protect the toilet from heat or one of these https://www.amazon.com/Removal-Induction-Heating-Flameless-Corrosive/dp/B07L77SZPY It saves you a world of headaches
Comment: @hellomoto : yeah, I read about the possibility of heating too, but I'm a bit concerned: won't the heat damage the tanks as well (after all it is made of porcelain...). Even if I manage to touch only the bolt with the tip of the tool, won't the heated up bolt transfer the heat to the tank?
Answer: When I had the same problem, I took a 4 1/2 inch angle grinder to the bolt heads. Just be careful and try not to touch the grinder to the porcelain. Also dont grind so long that you heat up the bolts to much and be careful not to melt any plastic bits in the toilet with the grinder spray. When you are done grinding, make sure you clean out all the slag and dirt that you generate. If you only grind inside the tank, you dont have to worry if you slip a little, any marks you make will be hidden when you close the tank lid!
Comment: Not a bad idea at all. _If_ you have a small enough angle grinder and you're _really_ careful to not gouge the porcelain.
Answer: It's called a wingnut. I see the rust on the bolt heads in the tank. Are they also rusted under the wingnuts? Those wingnuts should be replaceable at your local home center. Have you checked? If so, try some WD40 or other penetrating oil under the wingnut and let it sit for a few minutes and then try turning them with large pliers or vise grips putting equal pressure on both wings. If they break off just replace them.
The bolts and gaskets under them should also be available for purchase.
Comment: Thanks (I'll edit the question to say `wingnut`.) For the records: I don't care at all about the bolts and wingnuts, (I just don't want to damage the bowl of the tank accidentally, that's why I'd prefer not to start breaking them). And yes, the bolts are rusty all the way down, and the wingnuts won't move even a bit.
Comment: When you replace the bolts, you may want to opt for all plastic, which won't corrode. You may need to tighten the wingnuts twice, to allow for several days worth of creep between tightenings.
Comment: Once the wingnuts are off you should be able to replace the bolts. If you can't unscrew them you can probably break them off.
Comment: Clarification on my comment above. If you can't unscrew the wingnuts you might be able to break them off, freeing up the bolt.
Answer: The plastic nuts put you in a better position than you might otherwise be, I think.
While a nut cracker would be difficult to apply to a wingnut, much less under a toilet tank, a pair of locking pliers or similar "high force" tool should be able to break (crush) the plastic nut so you can get the rusted bolts out.
Example, not endorsement:
Answer: Based on the updated info about the screws and bolts being tightly rusted together, I'd suggest 2 things:

A heavy dose of a rust remover

I've had good success with PB Blaster™ in the past, but any similar product should work.
Give it a good several hours (or even over night) to soak in and do its job.
Put a disposable bowl under each nut to catch drips - you don't want it ruining the flooring.
See if you can loosen it by grasping the screw head with one pair of locking pliers and the nut with another pair.

If that doesn't loosen things up, I'd suggest the use of a hacksaw on the nut under the bottom of the tank/bowl.

Cut as close to the top of the nut as you possibly can. You should be able to get most, if not all, of the nut cut off the bolt. If you can't get it all cut off, once you're down to a thin layer of nut remaining, you should be able to break the rest of the rusty bits off.
A hand-tool is less likely to cause damage to the porcelain coating because you're moving much slower than a power tool would and you'll notice very quickly if you are starting to cause damage. You'll have the opportunity to stop and adjust at the lightest of scratches whereas a power tool will do notable damage before you have a chance to react.

Instead of sawing, use the nut cracker from the question linked in the OP.

If there is still concern about breaking the bowl/tank, hack sawing through part of the bolt (option 2) will leave much less material to be broken by the nut cracker, making its job easier.
Comment: @Attilio 1) I don't know what your floor is made of - mine is carpeted, so I'd definitely want to protect it. If yours is tile, it won't damage it, but it could soak into incompletely sealed (or older) grout. It never hurts to catch drips so you don't have to clean up. 2) it depends on how close to the top of the nut you can get in your cut. If you're within a mm or two, you'll probably be able to break the rusty bits off the remains of the bolts & you're good. Otherwise, see the just added 3rd point.
Comment: Thanks for the tips. A couple of questions:

1. if the rust remover is capable of damaging the floor, won't it damage the tank too? (e.g. by making the hole a little bit larger, and hence causing a leak?)

2. if I cut off the sticking part, won't the bit which is stuck together with the above and lower gasket still be so strong, that I can't separate the tank (without breaking it)? (I'm afraid that I would even be worse off, because I don't have the lower bit to grip.)
Answer: Thanks for all the suggestions.
It turned out that under the wingnuts there were also hex-nuts holding the bolts in place. I added some WD40 on the top of the bolts, and after one day, the right bolt came off quite easily (with a wrench and a screw driver).
          _____           <--- bolt head
      <===========>       <--- hard plastic gasket
      -------------       <--- rubber gasket
        ========          <--- hole in the tank
       <=========>        <--- hard plastic gasket
          ===             <--- hexnut (stuck)
           |
           |
           |
         <--->            <--- wingnut (stuck)
           |

However, the left bolt was stuck and corroded together with the hex-nut (even the wingnut got stuck) and even the slot on the top of the bolt was almost totally eroded (so I could not use a screw driver, I was trying to hold it with pliers).
So in the end I cut the top solid plastic gasket with a knife and pulled off the rubber gasket below it. My original plan was to have a better grip on the head, with the pliers in this way, but suddenly the bolt just fell through the hole (which was much bigger than its head).
TL;DR: I cut off the top plastic gasket and removed the rubber gasket on top, and at that point the bolt was free.


T method that can get nullable and notnullable variable

Question: I looking to create a method that can do the following thing:
string? s = xelement.GetValue < string > ( "elementname" );
Guid? g = xelement.GetValue < Guid > ( "elementname" );
int? i = xelement.GetValue < int > ( "elementname" );
DateTime? d = xelement.GetValue < DateTime > ( "elementname" );

is it possible?
Comment: String is a reference type and so it can have a null value already. Therefore, `Nullable` wouldn't make sense as `Nullable<>` is designed to make `value types` nullable.
Comment: You can alter it so you call `.GetValue`, `GetValue` etc. Or have two different methods: one for structs and one for reference classes.
Comment: No, you cannot have a `string?`.
Comment: why we have string.IsNullOrEmpty ?
Answer: I'm afraid you will have to create 2 separate methods. In order to return Nullable<T>, you need the struct constraint, which prevents reference types from being used.
Comment: Isn't Nullable in itself a type? So you could just create GetValue where sometimes T is in fact sometimes Nullable?
Answer: Try this extension method will work with string, int and DateTime, because all these types are supported by IConvertable interface. Thus you can convert string to bool, byte, char, decimal, etc (except Guid):
public static T GetValue<T>(this XElement element, string name)
{
    string value = (string)element.Element(name);
    return (T)Convert.ChangeType(value, typeof(T));
}

BTW there is no Nullable<string> in C#, because nullable can accept only value types. So you should use simple string.

Usage:
<rooot>
  <string>hello</string>
  <int>42</int>
  <guid>0FFF30ED-0C4B-41ED-9CDA-D9E084FAD6F2</guid>
  <date>06/27/2013</date>
</rooot>

Parsing:
XDocument xdoc = XDocument.Load(path_to_xml);
XElement root = xdoc.Root;
string s = root.GetValue<string>("string");
int? i = root.GetValue<int>("int");
DateTime? d = root.GetValue<DateTime>("date");

If you want guids to be supported also, then you can manually parse them:
public static T GetValue<T>(this XElement element, string name)
{
    string value = (string)element.Element(name);

    Type targetType =  typeof(T);
    if (targetType == typeof(Guid))
        return (T)(object)Guid.Parse(value);

    var typeConverter = TypeDescriptor.GetConverter(targetType);

    if (typeConverter == null || !typeConverter.CanConvertFrom(typeof(string)))
        return default(T); // or throw exception

    return (T)typeConverter.ConvertFrom(value);
}

UPDATE OK, if you want to return nullable value from method, then (remember, strings are not value types, so you can't parametrize method with string):
public static Nullable<T> GetValue<T>(this XElement element, string name)
    where T : struct
{
    string value = (string)element.Element(name);
    if (value == null)
        return null;

    Type targetType =  typeof(T);
    if (targetType == typeof(Guid))
        return (T)(object)Guid.Parse(value);

    var typeConverter = TypeDescriptor.GetConverter(targetType);

    if (typeConverter == null || !typeConverter.CanConvertFrom(typeof(string)))
        return null; // or throw exception

    return (T)typeConverter.ConvertFrom(value);
}

Comment: I must be missing something. Won't calling `GetValue` _never_ return a `null` value? That is, isn't the usage that you have there simply returning an `int` and converting it to `int?` when assigned with `int? i = `?
Comment: @ChrisSinclair null value is not required. You can assign `int` to `int?` See method generic parameters - they are not nullable in question. Or maybe I'm missing something
Comment: My _impression_ was that Salvatore Di Fazio wanted to specify an `int` type and have it return `null` if the element wasn't found or some other exceptional case. That is, specify the underlying type `int` for `T` and have it return `T?`. EDIT: Of course, the actual _intent_ of what he's trying to do is not clear at all; it'd be nice to have better context as to what he's _wanting_ to do.
Comment: @ChrisSinclair OK, I understand your point. Updated answer with returning nullable types
Answer: You can use the "Null object" pattern. Here
Answer: I tested this in LinqPad (my go-to quick C# sandbox) and it works:
    void Main()
{
    string s = GetValue<string>("elementname");
    Guid? g = GetValue<Guid?>("elementname");
    Guid h = GetValue<Guid>("elementname");
    int? i = GetValue<int?>("elementname");
    int j = GetValue<int>("elementname");
    DateTime? d = GetValue<DateTime?>("elementname");
    DateTime e = GetValue<DateTime>("elementname");

    Console.WriteLine(s);
    Console.WriteLine(g);
    Console.WriteLine(h);
    Console.WriteLine(i);
    Console.WriteLine(j);
    Console.WriteLine(d);
    Console.WriteLine(e);
}

T GetValue<T>(string elementName)
{
    return default(T);
}

Output:
null
null
00000000-0000-0000-0000-000000000000
null
0
null
1-1-0001 00:00:00


Python/Selenium. List is not filling up with IMDb hrefs

Question: Hi I'm trying to piece together something that scrapes the hrefs from these 4 IMDb links but my list = [] won't seek to fill up even though when I return or print instead of append I get the list. It worked before but maybe I moved something now it won't work.
first_page = 'https://www.imdb.com/title/'+movie+'/episodes?season=1'
second_page = 'https://www.imdb.com/title/'+movie+'/episodes?season=2'
third_page = 'https://www.imdb.com/title/'+movie+'/episodes?season=3'
fourth_page = 'https://www.imdb.com/title/'+movie+'/episodes?season=4'
driver.get(first_page)
driver.execute_script("window.open('" + second_page +"');")
driver.execute_script("window.open('" + third_page +"');")
driver.execute_script("window.open('" + fourth_page +"');")
time.sleep(3)

# Handles is a variable which handles the
handles = driver.window_handles
# Loops through each tab and performs a function
for handle in handles:
    driver.switch_to.window(handle)
    # Scrapes all hrefs(including episode links) builds a list
    links = []
    elements = driver.find_elements_by_tag_name('a')
    for elem in elements:
        href = elem.get_attribute("href")
        links.append(href)

time.sleep(5)

driver.quit()

This is the error NameError: name 'links' is not defined
Comment: It seems you are trying to define links for each iteration. Try bringing links out of the for loops
Comment: I really can't believe Im that stupid and it was that simple I've been banging my head against a wall trying to indent things and thought I had tried that. Thanks for clearing that up!
Answer: As Robert Kovacs stated this is the answer.
links = []
# Handles is a variable which handles the
handles = driver.window_handles
# Loops through each tab and performs a function
for handle in handles:
    driver.switch_to.window(handle)
    # Scrapes all hrefs(including episode links) builds a list

    elements = driver.find_elements_by_tag_name('a')
    for elem in elements:
       href = elem.get_attribute("href")
       if href is not None:
        links.append(href)

time.sleep(5)

driver.quit()

Comment: Worth pointing out that I had to time.sleep(2) or delay the handle switch to grab the links