php json decode ,how to get this value?

Question: Below is json data, I want to get the value 'average'. How can I do?
{
items: [
{

city: "北京",
tel: "85306308-1004",
name: "巴西之家",
mayor_id: 877861620, //当前地主的用户id
venue_info:
{
//地点的评分信息
rating: 7.6, //地点平均分,10分为满分
**average: 116** //地点人均消费(单位:人民币)

},
lon: 116.437031906407,
checkin_users_num: 133, //地点总签到用户数
lat: 39.9131007742324,
checkin_num: 161, //地点总签到数
addr: "朝阳区光华路44号(巴西大使馆对面)",
dist: "200 m", //地点距离传入坐标相对距离
guid: "774E9ED4B79AF2A9904ECDA2F8D70565", //地点的id
description: "地道巴西美食,从芝士夹心面包就征服食客", //推荐潮地的推荐语
img: "http://img.jiepang.com/get/photo/182a6154e2dedbdf111bf29347ad6aa7?size=120" //推荐潮地配图

},
{
},
{
},
],
num_items: 44 //附近共有多少个推荐潮地

}

I use the function json_decode to parse below json data.
How to get the value 'average'?
$jsonObj = json_decode($contentStr);
$items = $jsonObj->items;

Comment: `print_r($items)`. It will be obvious.
Answer: Had to reformat some stuff, not sure if it was invalid JSON or just the foreign characters, but this should work:
<?
          $js = '{ "items" : [{"city": "a",
             "tel": "85306308-1004",
             "name": "b",
             "mayor_id": 877861620,
             "venue_info": {"rating": 7.6,
                          "average": 116
                         },
             "lon": 116.437031906407,
             "checkin_users_num": 133,
             "lat": 39.9131007742324,
             "checkin_num": 161,
             "addr": "b",
             "dist": "200 m",
             "guid": "774E9ED4B79AF2A9904ECDA2F8D70565",
             "description": "c",
             "img": "http://img.jiepang.com/get/photo/182a6154e2dedbdf111bf29347ad6aa7?size=120"
            },
            {},
            {}],
    "num_items": 44}';

    $o = json_decode($js);

    $average = $o->items[0]->venue_info->average;

?>

php json decode ,how to get this value?


Implemtation of += operator oveloaded for the Class Vector. C++

Question: I need to implement the overloading of the += operator in c++. I have a Vector class and my implentation of += needs to add an integer from the back of my Vector.
For example: if my vector V1 contains of {1, 2, 3} and I write V1 += 4, it needs to give me {1, 2, 3, 4}.
I have almost the same functionality with the overload of the + operator which receives a Vector and an int and adds the given integer to the back of the array.
Fields for my class
    class Vector
    {
        unsigned int _size;
        int * _list;

HERE IS MY NON-WORKING SOLUTION FOR += OPERATOR
    Vector& operator+=(const int val)
    {
        Vector temp;
        temp._list = new int[_size + 1];
        temp._size = this->_size + 1;

        for (unsigned int i = 0; i < temp._size; i++)
        {
            if (i < temp._size - 1)
            {
                temp._list[i] = this->_list[i];
            }
            else if (i == temp._size - 1)
            {
                temp._list[i] = val;
            }
        }
        return temp;
    }

AND ALMOST IDENTICAL WORKING SOLUTION FOR + OPERATOR
    friend Vector operator+(Vector lhs, const int val)
        {
            Vector temp;
            temp._list = new int[lhs._size + 1];
            temp._size = lhs._size + 1;

            for (unsigned int i = 0; i < temp._size; i++)
            {
                if (i < temp._size - 1)
                {
                    temp._list[i] = lhs._list[i];
                }
                else if (i == temp._size - 1)
                {
                    temp._list[i] = val;
                }
            }
            return temp;
        }

I can't understand where is the key difference, however I am guessing it is somewhere in & or friend concepts, cuz I dont'really understand how they are working in this case.
And one more thing I MUST NOT CHANGE THE DESCRIPTION OF MY METHODS. (just the implementation)
Comment: You can't return a reference to a local variable.
Comment: @pptaszni Generally, the binary operators should be implemented from the compound assignment operators, not the other way around. So `+` should be implemented using `+=`.
Comment: *"HERE IS MY NON-WORKING SOLUTION..."* What does nonworking mean? Do you get any error. Or something else.
Comment: your `operator+=` is broken due to returning a reference to a local.
Comment: I also suggest you spend some time to read [this canonical implementation reference](https://en.cppreference.com/w/cpp/language/operators#Canonical_implementations) for overloading operators. From it you should learn that all assignment operators should return a reference to `*this` (and modify `this`, not create a new object).
Comment: Unnecessarily duplicated code. `Vector& operator+=(const int val) { *this = *this + val; return *this; }` would also work.
Comment: Suggest thinking about using another operator for this (e.g. `<<=`). For `+=`, one might expect to add rhs to each element of lhs.
Comment: `operator+=` should modify and return `this` not a temporary value
Comment: A note about the code: if you change the upper limit of the loop so it runs up to `temp._size - 1` instead of `temp._size` you can make the code much simpler: `for (unsigned i = 0; i < temp._size - 1; ++i) { temp._list[i] = lhs._list[i]; } temp._list[temp._size - 1] = val;`.
Comment: Wouldn't it be idiomatic to implement this as `push_back`?
Comment: In the expression `a += b`, the effect is modifying `a` and the result is (typically a reference to) the modified `a`.  In the expression `a + b`, it is pretty typical that the effect does not involve modifying either `a` or `b`, and the result is another (temporary) object containing the result of summation.
Answer: In the += operator, you should set the new value to the vecor to be added itself.
Also note that returning a reference to a non-static local variable temp is a bad idea.
Try this:
Vector& operator+=(const int val)
{
    Vector temp;
    temp._list = new int[_size + 1];
    temp._size = this->_size + 1;

    for (unsigned int i = 0; i < temp._size; i++)
    {
        if (i < temp._size - 1)
        {
            temp._list[i] = this->_list[i];
        }
        else if (i == temp._size - 1)
        {
            temp._list[i] = val;
        }
    }
    // move the data in temp to this object
    this->_size = temp._size;
    delete[] this->_list;
    this->_list = temp._list;
    // assign new array to temp for being destructed
    temp._list = new int[1];
    temp._size = 1;
    // return a reference to this object
    return *this;
}


lodash functions are not recognizing in angular6 and jasmine test cases

Question: I am using lodash library in my angular application for trimming text box value.
The code am using like this
This is working fine when i run the app.
import _ from 'lodash';
validateForm() {
 if(_.trim(this.addusermodel.firstname) == "") {
   ////
 }
}

in spec file am using this code
describe('validateForm', () => {
    it('Form should validate', () => {
      component.addusermodel.firstname = "wrwer";
      component.validateForm();
    });
  });

But when i executing the function from spec file am getting this error TypeError: Cannot read property 'trim' of undefined
Answer: Import lodash like this
import * as _ from "lodash"; instead of import _ from 'lodash';


Convergence of $u_{n+1} =\sqrt{\sum_{k=0}^{n} u_k}$

Question: I am trying to study the convergence of the sequence defined by:
$$u_0 = a>0, u_{n+1} = \sqrt{\sum_{k = 0} ^{n} u_k}$$
I have shown that $$u_{n+1} - {u_n} = \frac{u_n}{u_{n+1}+{u_n}} \tag{$*$}$$ since
$$u_{n+1} - {u_n} = \sqrt{\sum_{k=0}^{n}u_k} - \sqrt{\sum_{k=0}^{n-1}u_k}$$
then rationalize to get to $(*)$.
And since it can be easily shown that (induction) that $u_n>0$ for all $n$ we have that $$u_{n+1}-u_n>0 \Rightarrow u_{n+1}>u_n$$
S0 $(u_n)$ is an increasing sequence. Suppose $(u_n)$ was bounded above, then $u_n \rightarrow u$ for some $u\in\mathbb{R}$. Passing to the limit in $(*)$ we have the $u = 0$, but this is impossible since $u_0>0$ and $(u_n)$ increasing so then $(u_n)$ does not converge.
Is this argument correct?
Comment: Cesaro tells if it converges, it's to $0$.
Comment: @AbdallahHammam I have not learnt that yet unfortunately, is my argument above correct?
Comment: @Dman: How did you show $$u_{n+1}-u_n=\frac{u_n}{u_{n+1}+u_n}?$$ Furthermore, I'll agree that $u_n>0$ for all $n$, how are you deducing that $u_{n+1}-u_n>0$?
Comment: @Clayton, write out the term for $u_{n+1}$ explicitly on the LHS and then rationalize. Since all the terms on the RHS are positive, the LHS must be positive as well.
Comment: @Clayton see the updated answer
Comment: @Dman: Your proof seems fine to me now.
Comment: @Clayton, great! Thanks for the confirmation. Much Appreciated.
Comment: If you would like, you can confirm the correctness in an answer and I will accept it.
Comment: is it ok now with an without.
Answer: Another way of seeing this is to note that $(u_n)$ also verifies the recurrence formula
$$u_{n+1}=\sqrt{u_n+u_n^2}$$
and study the function $f:x\mapsto \sqrt{x+x^2}$. This function stabilizes the interval $[0,+\infty[$, is strictly increasing and it is easy to prove that $x>0$ implies $f(x)>x$.
So the sequence $(u_n)$ is strictly increasing, and cannot be bounded because, as you said, the only fixed point by $f$ is $0$.
It would be funny then to find an equivalent of $u_n$ :-)
This is what I found : from $u_{n+1}=\sqrt{u_n+u_n^2}$, you can first derive, as you pointed,
$$u_{n+1}-u_n=\frac{u_n}{u_n+u_{n+1}}< \frac{1}{2}$$
because $(u_n)$ is strictly increasing. This leads to
$$u_n=u_1+\sum_{k=1}^{n-1} u_{k+1}-u_k\le 1+\frac{n-1}{2}=\frac{n+1}{2}$$
But you can also derive
$$u_{n+1}=u_n\sqrt{1+\frac{1}{u_n}}$$
and because we proved $\lim u_n=+\infty$, we can use the development :
$$u_{n+1}=u_n(1+\frac{1}{2u_n}+o(\frac{1}{u_n})) = u_n+\frac12 +o(1)$$
so
$$u_{n+1}-u_n=\frac{1}{2}+o(1)\sim \frac12$$
and by Cesaro theorem (or by summations of equivalents) :
$$u_n = u_1+\sum_{k=1}^{n-1} u_{k+1}-u_k \sim \frac n2$$
So now you have the limit, an upper bound and an equivalent :-)
Answer: Since every $u_n$ is positive, we have $u_n \ge \sqrt {u_0}$ for $n \ge 1$, and then $u_n \ge \sqrt {(n-1)\sqrt {u_0}}$ for $n \ge 2$, which shows that $(u_n)$ diverges.
Answer: let
$$v_n=\frac{\sum_{k=0}^n u_k}{n+1}$$.
we have
$$\frac{u_{n+1}^2}{n+1}=v_n$$.
if $lim_{n\to +\infty}u_n=L$ then
$0=\lim_{n\to+\infty} v_n=L$
using Cesaro average.
Now, if $(u_n)$ is increasing and
$u_0=a>0$, the limit can't be $0$.
thus $(u_n)$ diverges.
OR WITHOUT CESARO
we have
$$u_{n+1}-u_n=\frac{u_n}{u_n+u_{n+1}}$$
and  when $n\to +\infty$
$$L-L=\frac{L}{2L}$$
which proves that
$(u_n)$ diverges.


SIP over double nat

Question: I'm developing a SIP parser in C (client only) and i have doubt about, do i need to bind a socket with a specific port (5060) on double nat?. What i'm sure about it's that is really important in the server side but i'm not really sure about the client side
Answer: You don't have to use port 5060 on the client side regardless of the NAT type. There is no any disadvantage if you just pickup a random port. The only recommendation is that once you pickup a port, keep that across sessions to help NAT bypassing a bit in some circumstances and to not overflow NAT's with various binding.
Even on the server side you can use any port, but there is a big disadvantage: users need to type also the port part as the server address (yourdomain:port) if you are not using the standard 5060 port.
Think about it like in case of http. On the web server the standard port is 80. However none of the clients (web browsers) are using port 80 on the client side.
Comment: Thank you very much for your reply, I was forcing the app to bind on port 5060 and crashes a lot. I'll do it that way then ;)

SIP over double nat


Which is the easiest game in Prince of Persia series?

Question: At present, I am playing Prince of Persia: Sands of Time. After 69% completion, I find that it is way too difficult, even though I use cheats(meaning infinite sand, infinite power, and infinite walking on walls). It seems impossible for me to go ahead.
Please suggest to me the easiest game in the POP series.
Comment: Heh, I suggest you *don't* try the original game [link](http://en.wikipedia.org/wiki/Prince_of_Persia_(1989_video_game) ) if you find the modern remakes too hard! (kids today, grumble grumble grumble...)
Comment: This question seems completely subjective to me.  What is "easy" for one person is hard for another.
Comment: [Fixed link](http://en.wikipedia.org/wiki/Prince_of_Persia_(1989_video_game%29)
Comment: @therefromhere: ihave played original one and complete tht :D
Comment: @sjohnston: easiest not easy. lolz :D
Comment: @sjohnston I don't agree that this question is completely subjective, but I do think it's too subjective for this site.
Answer: I am currently enjoying playing the 2008 Prince of Persia game on the Xbox 360 (but its also available on PS3 and PC).
It is relatively easy so far and quite a few reviews for the game suggest this too
Comment: Just to add to the anwser: What makes 2008 Prince of Persia so easy is that you quite literally can not die in the game, as Elika, your companion, will always save you, no matter if you jumped into a bottomless pit or are fighting against an evil foe. I consider Sands of Time to be a better and more interesting game, but the 2008 PoP is certainly a very relaxing and enjoyable game on its own.
Comment: While the platforming for 2008 Prince is easy, the fights get kind of crazy about halfway through (boss fights, that is).
Answer: If this is about Ubisoft's Prince of Persia Game Series, Sands of Time is the easiest of all. Honestly, I also found it to be hard when I'm playing it for the first time. The following will be hard

Finding the way
Solving the puzzles
Very tiring and long fights

Finding the way
Unlike other games, the game doesn't suggest any directions, we have to find on our own. This makes the game hard as well as challenging. It's hard in the beginning, but you'll love it once cracked.
Solving the Puzzles
I wasted days to solve a few puzzles, especially the one with mirrors and the other one with many doors. The mirrors puzzle, when I solved it first, I didn't even know how I did it. While doing it the second time, I observed clearly how I did it.
Very tiring and long fights
The first one of this kind is when the Prince has to kill his own father. Prince is surrounded by many enemies at once. I planned to quit playing this game to avoid facing this. The key to win this is not to stay at one place for longer time. Just jump over enemies, hit them; roll over the floor to escape, etc. But, never stay on the same ground until you get killed. Also, learn how to block the enemies swords. This is more useful.
Don't give up on this game. For me, this is the best of the games I've played. The story and the game play are so gripping. Believe me, you'll enjoy the story more in the next parts.
Happy Gaming!
Answer: The Two Thrones is the easiest of all POP series games. I ve completed it 18 times totally. (including PS2, PC, and laptop) :)


ionic 3 html button linked to a funtion in .ts but says its undefined

Question: I have this line of code which I have at the end of a sign-up type form:
<button ion-button full color="secondary" onclick="save()"></button>`

However when I click on it I get an error saying save is undefined but I have this in my .ts file
save() {
  this.submitAttempt= true;
  console.log("success!");
  console.log(this.slideOneForm.value);
  console.log(this.slideTwoForm.value);
  console.log(this.slideThreeForm.value);
}

Is my mistake in the definition or in the button itself and how can I fix this?
Comment: Can you provide us more of your code so that we can debug? https://stackoverflow.com/help/mcve
Comment: Sonicd300 already answered it
Answer: Your error is in the button's html, you bind it like (click)="save()" not onclick="save()"
Answer: This is an issue of the Ionic live reloader (debug server). So you have 2 options here.
Option 1: Change something on .ts file and allow to server reload again
Option 2: Kill the server and restart it again using ionic serve


how show/list snaphosts by "description" in GoogleCloud?

Question: Any idea how to show "snapshots descriptions" in Google Cloud ?
When I am creating a snapshot, there is option to make description about this snapshot, however I just realized that after that I don't see this "snapshots description" in the list, also not found how to list via gcloud command
Answer: You can view the snapshot description via console by clicking on the name of your snapshot from the Snapshots page (Compute Engine > Snapshots) and going to the details of that snapshot.
You can also view the description of your snapshot through the gcloud compute snapshots describe command.
<code>gcloud compute snapshots describe [SNAPSHOT_NAME]
</code>
Comment: OK this is some workaround, but my complain was that u don't see descriptions about snapshots in "main view" so u are missing some quick overview about all snaps.
ok seems that this is not a bug, this is a feature :)


Get Android CurrentActivity in .Net MAUI

Question: I'm porting a Xamarin.Android project to .Net 6.
Because of dependencies, it's not possible to include Xamarin.Essentials in the .Net 6 project.
So I'm switching everything to use the Microsoft.* namespaces. This was easy enough, except for Xamarin.Essentials.Platform.CurrentActivity.
Is there a .Net MAUI equivalent of this class? If not, any other good options other than copying/pasting the code from Essentials into the app?
Comment: I think [Microsoft.Maui.Essentials.Platform.CurrentActivity](https://github.com/dotnet/maui/blob/main/src/Essentials/src/Platform/Platform.shared.cs) exists
Answer: All of Essentials got rearranged to go under more logical namespaces. The one you are looking for is now under Microsoft.Maui.ApplicationModel.Platform.CurrentActivity
A full overview, where somehow this one is missing, can be found here: https://github.com/dotnet/maui/pull/5562
Comment: This is very useful for simple android conditionals. Thank you!


Implementing secure, unique "single-use" activation URLs in ASP.NET (C#)

Question: I have a scenario inwhich users of a site I am building need the ability to enter some basic information into a webform without having to logon.  The site is being developed with ASP.NET/C# and is using MSSQL 2005 for its relational data.
The users will be sent an email from the site, providing them a unique link to enter the specific information they are required.  The email will be very similar to the style of email we all get when registering for sites such as forums, containing a randomly generated, unique URL paramter specifically pertaining to a single purpose (such as verifying an email address for a forum).
My queries are regarding the secure implementation of this problem.  I was considering using a GUID as the unique identifier, but am unsure of its implications in the security world.

Is a GUID sufficiently long enough such that values cannot be easily guessed (or brute-forced over time)?
Is .NET's GUID implmentation sufficiently random in the sense that there is an equal chance of generation of all possible values in the "key space"?
If using a GUID is an acceptable approach, should the site then redirect to the information via URL rewriting or by associating the information in a datatable with the GUID as a reference?
Will using a URL rewriting hide the true source of the data?
Should I consider using TSQL's SELECT NEWID() as the GUID generator over the .NET implementation?
Am I completely wrong with my approach to this problem?

Many thanks,
Carl
Answer:
No, GUIDs are not fully random, and most of the bits are either static or easily guessable.
No, they're not random, see 1. There is actually a very small number of bits that are actually random, and not cryptographically strong random at that.
It's not, see 1 and 2.
you can, but dont need to... see my solution at the end.
No, see 1 and 2
Yes.

What you should be using instead of a GUID, is a cryptographically strong random number generator - use System.Security.Cryptography.RNGCryptoServiceProvider, to generate long (say, 32 bytes) string of data, then base64 encode that.
Also, assuming this is some kind of registration with sensitive data, you'd want to time limit the validity of the link, say 60 minutes, or 24 hours - depends on your site.
You'll need to keep a mapping of these values to the specific users. Then you can automatically present him with the proper form as needed. Dont need to do url rewriting, just use that as the user's identifier (on this page).
Of course, dont forget this URL should be HTTPS...
Btw, just a note - its good practice to put some form of text in the email, explaining that users shouldnt click on links in anonymous emails, and typically your site wont send, and they should never enter their password after clicking blablabla....
Oh, almost forgot - another issue you should consider is what happens if the user wants several emails sent to him, e.g. hits register several times. Can he do this over and over again, and get many valid URLs? Is only the last one valid? Or maybe the same value gets resent over and over again? Of course, if an anonymous user can put in a request for this email, then DoS may become an issue... not to mention that if he puts in his own email, he can put in any random address too, flooding some poor shmuck's inbox and possibly causing your mail server to get blacklisted...
No one right answer, but needs to be considered in context of your application.
Answer:
Yes, 2128 is long enough.
No, GUID implementations are designed to generate unique GUIDs rather than random ones. You should use a cryptographically secure random number generator (e.g. RNGCryptoServiceProvider) to generate 16 random bytes and initialize a Guid structure with that.
Yes, it's an acceptable approach overall. Both will work.
Yes, if you don't give out any other clues
No, goto 2
No, it's pretty OK. You just need to use a cryptographically secure random number generator to generate the GUID.
Comment: @AviD: I never said you'd generate a GUID by calling `Guid.NewGuid`. All I care about is the GUID format. You generate 16 arbitrary bytes with a random number generator and pack it in a GUID format. Yes, it may not serve as a Globally Unique Identifier but that doesn't matter. GUID *format* is just a convenient format.
Comment: Sorry, but this is really wrong, and misleading - GUIDs are not good for this sort of thing, see my answer below.
Comment: GUID, in sense of *unique identifier* is not really suited (as I mentioned in #2). But there's nothing to prevent you from using them as a 128 bit number.
Comment: But the thing is they're *not* really 128 bit numbers (even though it does take 128 bits to store them). Again, too much of it is either static, or easily guessable. GUIDs have no use in secure identifiers. What the OP needs is something secure, and long enough in the sense of "128 bits of randomness", which GUIDs are not, not even close.
Comment: The thing is, you don't use Guid.NewGuid() and NEWID() as I said *explicitly*. You use a CSRNG to generate 16 random bytes and get a GUID representation from it.
Comment: Ah, see - CRNG's do *not* generate GUIDs. A GUID has a very specific structure, *which is not random*, only a small part of it is.
Comment: Oh, and as long as we're mentioning it - 16 bytes of random data will NOT translate to 16 characters - since there will be a lot bytes that would be represented by non-printable characters, you need to base64-encode it. Thus you'll get a longer output string, more like 24 characters... but again, thats not 24 bytes worth of randomness, only 16.
Comment: GUID is not 16 ASCII chars. It's 32 hex digits = 16 bytes which you fill with 16 bytes of random data. I don't see a relation here.
Comment: @Mehrdad, GUID is *not* 16 bytes of random data, it has a very specific structure, out of which the first few (most) bytes are NOT random. The random element is only in the last few bytes.
Answer: I would recommend just using a plain random number, e.g. bytes from RNGCryptoServiceProvider.GetBytes .  GUIDs are not meant to be completely random.  They have fixed bits, and some versions use your MAC address.  GetBytes also gives you the option to use more than 128 bits (though that should be plenty).
I think it is better not to put the user's data in a url.  Though HTTPS can protect it in transit, it may still be in the user's browser history or such.  It is better to use POST and associate the random number with a row of your database.
Answer: It might be overkill, but you could hash their email address with SHA1 using your guid (NewGuid is fine) as a hash salt and place that in the URL.  Then, when they arrive at your page, you could ask them their email address, retrieve the guid and recompute the hash to validate.  Even if somebody were to know what email addresses to try, they would never be able to generate a hash collision without knowing the guid you salted with (or it would take them a hell of a long time :).  Of course, you would have to save their email and the hash salt guid in the database.
Comment: Glad to help.  One note about your solution, you open yourself to a new use case since you cannot recreate the email.  That is, the user requests and email, does nothing with it, requests another one and then clicks the link in the first email (as I'm sure you know, users do stuff like that :)  So, you will have to expire each ServerHash by keeping the date you sent the email out in the DB and giving the user a reasonable time to respond.
Comment: Although the above technically answered my questions directly, I love your implementation idea.  After some thought I have expaneded on it some:

URL = SHA1(email + randomPass + salt)
serverHash = SHA1(email + randomPass)

Table Columns:
serverHash (primary key)
salt

The randompass would also be sent out with the url in the email and used in the original URL calculation then discarded.

I believe in this implementation no sensitive information would be stored in the database.  Meaning even if the the raw datatable were exposed you could not generate the URL to brute-force the email address
Comment: Yup, thanks.  I realise this.  The emails and URLs generated are very case-specific and generated to allow the users to generally save themselves some money, so they should probably use them, but I'll implement some handling also.
Comment: Most salting suggestions I've read recommend adding the salt to the beginning as opposed to the end.
Answer: First, if possible you should limit brute force, by limiting the throughput of the query (e.g. limited tries per IP per second, and limited total tries per second).
Depending on the GUID generation algorithm, this might not be a good idea. While recent implementations should be "good enough usually", there can be a lot of predictability to the values. Recent implementations as the one used in .NET apply a hash, otherwise you have clearly identifiable fields for MAC address, and time since boot. However, the possible values are limited, so you don't have true 128 random bits.
If security is the top priority, I'd pick a cryptographically strong random number generator, and build a string of random characters. This also makes oyu independent of an easily guessable algorithm (as a guid.ToString() is easily identified as such) for which an attack might be discovered in the near future.
If these criteria are met, I see no problem in having the key in the query string.
Answer: create a table in the database with a linkID and a Datesent column, on generation of the link send insert DateTime.Now into the table and return linkId, set the linkID as a querystring parameter on the activationLink. On load of the activation page retrive the linkId and use it to evoke a stored procedure that will return the date when passed the correspondin linkId as a parameter, when you get the date back you can add how long you want the link to stay active by using the .AddDays()/.AddMonths this are C# methods for datetime. then compare the date you got back with today's date. if it has passed its length of days or months give an error message or else continue and display the page content. I sugest you keep the contents of the page in a panel and and set it vissible = "false" then only make the panel visible="true" if the date is still within range.


Routing pages using flask and deploying on cPanel

Question: Hy I'm new to flask and trying to get my first site up, I have been trying this for a couple of days now with little to no progress, Here is some code:
from flask import Flask, render_template, url_for, redirect, request, session

app = Flask(__name__)

@app.route('/', methods=["POST", "GET"])
def purchase():
    try:

        if request.method == "POST":
            email = request.form["email"]
            # Query the data base to find the exact amount and name of buyer

            session["user"] = email
            return redirect(url_for("proceed"))

        else:
            return render_template("index.html",logged_in=True)

    except Exception as e:
        return(str(e))

@app.route("/confirm")
def proceed():
    # Get information and create another form
    if "user" in session:
        return f"""
{session["user"]}
"""
    else:
        return f"""
No email found
"""
if __name__ == "__main__":

    app.run()

The first purchase function works just fine, the problem appears when the user get redirected to proceed. The '/confirm' tag is added to the url of the site and the site goes to a **404 Not Found ** page. I have had problems changing pages with cPanel. What would be the best way to send the user of my site to a totally different page where i can add an HTML file of my choosing.
Answer: Firstly, you need to change the redirect(url_for('proceed')) to redirect(url_for('confirm'))
And the code should look like this:
from flask import Flask, render_template, url_for, redirect, request, session

app = Flask(__name__)

@app.route('/', methods=["POST", "GET"])
def purchase():
    try:

        if request.method == "POST":
            email = request.form["email"]
            # Query the data base to find the exact amount and name of buyer

            session["user"] = email
            return redirect(url_for("cofirm"))

        else:
            return render_template("index.html",logged_in=True)

    except Exception as e:
        return(str(e))

@app.route("/confirm")
def proceed():
    # Get information and create another form
    if "user" in session:
        return f"""
{session["user"]}
"""
    else:
        return f"""
No email found
"""
if __name__ == "__main__":

    app.run()

And since you are hosting on Cpanel, change your .htaccess file to add the following so apache redirect all the not-found URL to your application
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . / [L]

Answer: Add the following rules to your .htaccess in the directory of your application URL
RewriteEngine on
RewriteRule ^http://%{HTTP_HOST}%{REQUEST_URI} [END,NE]


Operator norm of matrices of a change of basis

Question: Let $X = (x_1, \dots, x_d)$ and $Y = (y_1, \dots, y_d)$ be two basis of $\mathbb{C}^d$ such that $|x_n| = |y_n| = 1$ for all $n = 1, \dots, d$.
Then, there exists unique matrix of a change of basis $A(X,Y) = (a_{i,j})_{1\leq i,j \leq d} \in M_{d\times d}(\mathbb{C})$, that is, the following holds:
$$
(x_1, \dots, y_d) = (y_1, \dots, y_d) A(X,Y).
$$
Can we know something $\|A(X,Y)\|$, that is, the operator norm of $A(X,Y)$, or equivalently, $\|A(X,Y)\|_p:= (\sum_{i,j=1}^d |a_{i,j}|^p)^{1/p}$ ?
I hope $\|A(X,Y)\|$ is bounded with respect to $X, Y$, that is,
$$
C := \sup \{\| A(X,Y)\| : X \; \text{and} \; Y \text{are the basis of} \; \mathbb{C}^d\} < \infty.
$$
Furthermore, I really hope that $C$ is independent of $d$.
Comment: You need some additional normalization assumptions. Otherwise $C$ is infinite. For example $A$ can be diagonal with any nonzero numbers on the diagonal.
Comment: Can please confirm that the $\sup$ is taken over all bases $X,Y$? If so, $||A||$ is clearly not bounded. Take the basis $X=(1,1)$ and $Y=(\alpha,1)$ with $|\alpha|>1$. Since $\alpha$ is free, $C$ is not finite.
Comment: I'm really sorry, I edited. I forgot to write that normalization assumption. @RyszardSzwarc
Comment: By $|u|$ do you mean the euclidean norm ? Also the operator norm although is equivalent with the one you defined, but the equivalence constant depends on $d.$
Answer: The answer is no, even for $d=2.$ Indeed, for $0<a<1$
let $$x_1=e_1,\ x_2=ae_1+(1-a^2)^{1/2}e_2,\quad y_1=e_1,\ y_2=e_2$$ where $e_1=(1,0)$ and $e_2=(0,1).$ Then for
$$A=\begin{pmatrix} 1 & -a(1-a^2)^{-1/2}\\
0 & (1-a^2)^{-1/2}
\end{pmatrix}
$$
we get  $Ax_1=y_1, \ Ax_2=y_2.$ The operator norm of $A$ is greater than $(1-a^2)^{-1/2}.$
Remark The main reason that we cannot expect boundedness are the angles between the elements of the basis. The elements $y_1$ and $y_2$ are orthogonal, while $x_1$ and $x_2$ are nearly parallel, when $a\to 1^-.$


One sided trig identity with conjugates $\frac{(\cos x\cot x)}{\cot x-\cos x}=\frac{\cot x+\cos x}{(\cos x\cot x)}$

Question: I've been given a trigonometric identity worksheet. We need to use conjugates to solve these identities. One sided proofs. I've spent some time on it but just can't crack it. Here it is, help appreciated. Any tips (such as which side to start on etc) is appreciated.
$$\frac{(\cos x\cot x)}{\cot x-\cos x}=\frac{\cot x+\cos x}{(\cos x\cot x)}$$
Comment: Hint: use conjugation on either side. Notice symmetry.
Comment: I tried applying (cotx+cosx) to the left side and got a few steps in, though I wasn't able to finish it up.
Answer: As $\cos x=\cot x\cdot\sin x$ for $\sin x\ne0,$
$$(\cot x+\cos x)(\cot x-\cos x)=\cot^2x\left(1-\sin^2x\right)=?$$
Answer: For $\sin x\neq0$,
$\dfrac{(\cos x\cot x)}{\cot x-\cos x}=\dfrac{(\cos x\cot x)}{\cos x(\csc x-1)}=\dfrac{\cot x}{\csc x-1}\cdot\dfrac{\csc x+1}{\csc x+1}=\dfrac{\csc x\cot x+\cot x}{\cot^2x}=\dfrac{\dfrac{\cos x}{\sin^2 x}+\dfrac{\cos x}{\sin x}}{\dfrac{\cos^2x}{\sin^2 x}}=\dfrac{\dfrac{\cos x+\sin x\cos x}{\sin^2 x}}{\dfrac{\cos^2x}{\sin^2 x}}={\dfrac{\cos x+\sin x\cos x}{\sin^2 x}}\cdot{\dfrac{\sin^2 x}{\cos^2 x}}={\dfrac{\cos x+\sin x\cos x}{\sin x}}\cdot{\dfrac{\sin x}{\cos^2 x}}=\left(\cot x+\cos x\right)\dfrac{1}{\cos x\cot x}=\dfrac{\cot x+\cos x}{(\cos x\cot x)}$
Comment: It should be $\sin x\ne0\iff x\ne m\pi$ for any integer $n$
Comment: @labbhattacharjee: Yeah. Thanks.
Comment: Thanks. Could you outline the final step a bit more? Are you using that a/b/c = a*c/b rule?
Comment: Yes but prior to that taking lcm in the numerator. $\dfrac{\frac{a}{b}}{\frac{c}{d}}=\dfrac{a\cdot d}{b\cdot c}$.
Comment: Sorry, I tried working that out but still couldn't figure out how the full transition of the final step. Could you expand the answer itself some more steps, skipping the lcm part?
Answer: $$\dfrac{\cos x\cot x}{\cot x-\cos x}=\cdots=\dfrac{\cos x}{1-\sin x}$$
Similarly simplify the right hand side
Finally use $$\cos^2x=(1-\sin x)(1+\sin x)$$
$$\implies\dfrac{\cos x}{1-\sin x}=?$$
Alternatively, $$\dfrac{\cot x-\cos x}{\cot x\cos x}=\dfrac1{\cos x}-\dfrac1{\cot x}=\sec x-\tan x$$
which is $=\dfrac1{\sec x+\tan x}=?$


Adding multiple buttons on the fly

Question: I want to add multiple buttons dynamically through the code on button click, I searched many previous posts which shows to add single button, but I need multiple ones.
Attached is the sample code.
   public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b1 = (Button)findViewById(R.id.button1);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddAll();
            }
        });
    }
    public void AddAll() {
        final RelativeLayout rl = (RelativeLayout)findViewById(R.id.rel);
        final Button btn = new Button(this);
        for(int i=0;i<4;i++)
        {
            rl.addView(btn);
            btn.setText("hello");
            btn.setWidth(320);
            btn.setHeight(40);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

Please help regarding the same. However adding single button is working fine, but I need to add many buttons one below the other.
Answer: public void AddAll() {
final RelativeLayout rl = (RelativeLayout)findViewById(R.id.rel);

for(int i=0;i<4;i++)
{
    final Button btn = new Button(this);
    rl.addView(btn);
    btn.setText("hello");

    btn.setWidth(320);
    btn.setHeight(40);
}
//////////////////////////////////////////////////////////
}

For more detail :-
How do I programmatically add buttons into layout one by one in several lines?
or
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ScrollView scrollView= new ScrollView(this);
    LinearLayout mainLayout = new LinearLayout(this);
    mainLayout.setOrientation(LinearLayout.VERTICAL);
    for (int i=0; i<10; i++){
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setTag(i);
        TextView tv=new TextView(this);
        tv.setText("Row " + i);
        ll.addView(tv);
        Button b = new Button(this);
        b.setTag(i);
        b.setText("Button " + i);
        ll.addView(b);
        mainLayout.addView(ll);
    }
    scrollView.addView(mainLayout);
    setContentView(scrollView);
}

Comment: Thanks for the help, no errors now, but still i am able to view only one button, may be all the 4 buttons are overlapping?? can i make it one below the other??
Comment: hope so once u have to use linear layout to see u going right way or not. ohk
Comment: checked with linear layout as well, not displaying 4 different buttons which i want! Any other suggestions?
Comment: Ok, making both linear view workk, but is it not possible to do them in relative layout??
Comment: how?? Any major modifications?? Just replacing them with Relative Layout is not working, plz suggest the right way!
Answer: public void AddAll() {
  LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
        layout.setOrientation(LinearLayout.HORIZONTAL);

            for (int j = 0; j < 4; j++ ){
                Button btnTag = new Button(this);
                btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                btnTag.setText("Button " + j);
                layout.addView(btnTag);
            }
        }

Adding multiple buttons on the fly


No sound in Headphone from front panel audio port in Ubuntu 18.04

Question: When I was connecting Headphone in the front panel port of CPU I couldn't hear any sound, actually it couldn't detect the headphone. But when I'm connecting it in the back panel port it can detect. And sound box is also working fine from the back panel, but not from front panel. This problem occurs only when I'm using Ubuntu 18.04, but in Windows 10 Pro it works fine from both of the panels (I use Win 10 & Ubuntu 18.04 in dual boot).
My CPU config is 3.5GHz Intel G-4560, H110M PRO VH Plus MSI motherboard, Intel HD 610 GPU.
Is the problem because of drivers? If so then how fix this (or how to install it) ?
Or any kind of suggestion how to fix it.
Thanks in advance!
Answer: I had the same issue. This answer below helped me
Front panel audio jack is not working in Ubuntu 16.04
When you are running Alsamixer, be sure to do these things:

Unmute Headphones by pressing M
Disable Auto mute
Play around with volume levels of "Front", "PCM", etc till you get the sound coming in your headphones (this is what did the trick for me)

Also note that the Headphones volume will continue to show zero in Alsamixer for some reason, but sound will still be there.
If you want a greater degree of control over the mixer, somebody recommended qashctl ..... check it out. For me, Alsamixer did the job, so I didn't bother
Comment: It worked @gg108. But it could have been documented better. Anyway thanks!
Answer: This worked-out for me. Thought it was better to share it elaborately.
In the 'Terminal' write alsamixer

In 'AlsaMixer' select Headphone using the side-arrows keys in Keyboard.

Now press m in Keyboard (mouse dose not work here) to Unmute the Headphone. ( When the Headphone is mute you can see in the column it shows MM, and after you unmute the Headphone, it will show OO)

Press up-down arrow keys to control sound in your Headphone.
Now to save the configuration run this command:
sudo alsactl store
So the next time you open your pc, it will boot-up with that config.
Answer: First, open
$ sudo gedit /etc/modprobe.d/alsa-base.conf

After the last line, add a new line. This line let the laptop to recognize the audio card. My audio card name is CA0132. You can find the name of audio card by: cat /proc/asound/card0/codec* | grep Codec
$ options snd-hda-intel model=CA0132

Then reload:
$ sudo alsa force-reload

Next, enter command:
$ alsamixer

In the open window: turn on the option "HP/Speaker Auto Detect"
Note: after the above steps, you can also try to reboot your computer. Sometime it does the trick.
Comment: How can I get a list of available options for snd-hda-XXX model=XXX?
Answer: Today I faced the same problem that unable to hear any sound if headphone connected even unable to test it out from settings > sounds but able hear properly if headphone not connected using laptop inbuilt speaker.
I referred all available solutions and even after changing it from mm to 00, it was not allowing me to hear sound using headphone.
I was using Lenovo ideapad and checked other options that available and it was showing F6 for sound cards so I tried to press it but didn't show me any available cards.
Then I pressed Function key + F6 and was able to see USB2.0 which was my headphone. So select it and then press m and increase it from 00 by pressing upper arrow key and after that was able to hear sound properly.
I hope it helps.
Thank you.


Lighting fireplace pilot

Question: I was trying to light my pilot and was having difficulty. The steps I followed.

Turn on gas
Turned pilot button from "off" to "pilot"
Pushed in pilot button
Pushed ignitor every second
Nothing happened

I tried it again - same steps as above - Again nothing happened.
I then moved the pilot button from "pilot" to "on" and the fireplace started up.
Now my questions

I believe the fireplace should have started when the pilot switch was on "pilot" and pilot button pushed in - is that correct?
Should I have a professional look at my system?

Thanks
Comment: You expected the fireplace burner to ignite when you lit the pilot? Why? The pilot is a little candle flame adjacent to the main burner. Sounds like everything worked as it should.
Comment: Great Point - I was not thinking about it right - thanks
Comment: John, you might [take the tour](https://diy.stackexchange.com/tour) to learn what's expected of you when you post. If the question turned out to be invalid, please delete the post.
Answer: There are two types of systems (I'll call them old and new) that I have seen when it comes to pilot lights.   In newer systems (sounds like what you have) you must press the valve knob or a separate pilot button to bypass a safety valve and allow enough gas to come out to light the pilot.  Once the pilot is lit, the flame heats up a thermocouple that allows the main gas valve to open.  Once all that happens, you can turn the valve fully on and light the main burner.  The idea is if the flame goes out (thermocouple isn't heated), the gas is completely cut off to avoid leaks.
On older style valves, you just turn the gas all the way on and light the burner.  When you are done, you can turn it all the way down to pilot and only the pilot remains lit so you can easily light it next time.  If the pilot blows out, you're leaking a small amount of gas (not good).
So, based on those two descriptions, do you still think that something is wrong?  Your description doesn't seem to really match either of those exactly, so something could be wrong with your valve.  At the very least, the safety valve that cuts off gas flow if the flame blows out could be faulty.  Today that's considered a problem, but years ago it was normal - again depends on the valve design.  I would have someone look at it just to make sure nothing else is wrong.  Gas is pretty deadly.
Try to light it again with the above description in mind, and if it still doesn't seem right, have it looked at.
Comment: Really appreciate the background you provided - I have a much better understanding

Lighting fireplace pilot


Audio on onloadeddata event not working in knockout

Question: Audio on onloadeddata event  not working in knockout
<audio id="audio"
       data-bind="attr {type: activity().mediaType, src: getAttachmentURL()},
                  event: {onloadeddata: function(data,event) {test(event);}}"controls>
</audio>

Comment: play event is working fine but onloadeddata is not working.
Comment: `data-bind="attr { ...`  lacks ':'.  Perhaps is a typo.  It should be `data-bind="attr: {...`.  And at the end there is `..}controls`, perhaps it lacks a space:  `..} controls`.
Answer: I changed onloadeddata to loadeddata:
    <audio id="audio"
           data-bind="attr: {type: activity().mediaType, src: getAttachmentURL},
                      event: {loadeddata: function(data,event) {test(event);}}"  controls>
    </audio>

Here is a fiddle.  I changed getAttachmentURL() to getAttachmentURL, without parenthesis, because I have not a function but an observable in my model.


Trying to find correct bolt for ceiling fan electrical box

Question: I'm really struggling trying to find the correct bolt for this electrical box for a ceiling fan. After taking the old ceiling fan out, I found 2 mismatched bolts that the previous person had used. One looked like a 10-32 that had been stripped at the end and was bent and the other was some type of sheet metal screw. I wanted to replace both of them with the correct bolts but after multiple trips to the hardware store I'm out of luck and out of ideas, as are the people at the stores I've asked (well one person told me to replace the whole box but that seems drastic).
So far I've tried 8-32, 10-32, 10-24 and M5.80. The 10-24 seemed the closest but won't turn once I thread it into the 2nd hole. I've circled in red below the 2 holes the bolt has to pass through. They are aligned, just the angle I took the picture makes them look bent. House is in the USA and was built in 1999 if this information is of any help. Much appreciation if anyone can tell me what the type of bolt it is please.
Thanks.
Comment: Most metal box covers are 8-32 but a box that is listed for a fan may be a 10-32 it should never be a sheet metal screw. Many boxes have self forming screws these are different than self tapping that may have been used if a screw was lost. Self forming will clear the damaged threads but each time threads are reformed some metal is removed so caution is needed usually going up a size will be safer if the threads are heavily damaged.
Answer: That box is a side mount 8B, 54151NL made by Steel City. It is not fan rated. The screw that it came with was an 8/32 and some one has messed up the threads and took out the clamps.

It needs to be replaced with a fan rated box, you will also need a joist support.

When you buy one you will see the additional double screw support for the 10/32 screws it comes with. Your in for a challenge getting the old box out. I would buy a medallion while your at your favorite gettin place.
Good luck. No hill for a high stepper!
Comment: Great answer, keep 'em coming! If you're going to stick around, please take the [tour] to become familiar with Home Improvement's guidelines, though you're off to a great start already.
Answer: As Ed said, it's almost certainly an 8-32, with a slim chance of a 10-32. My guess is the screws aren't working because the threads got damaged by the old incorrect screws. This is most likely why it was suggested you replace the box. If the threads are damaged I would probably replace the box. It's a chore but is the best option.
The alternative (which may violate the UL listing and/or NEC which are there for your safety) would be to re-tap the holes at a larger size than the damage. This could be done with self forming screws or with a drill and tap set. However, this will almost certainly result in a weaker connection and given this is an overhead box holding something up above people's heads and someone could come along and do something later like install a ceiling fan I would not recommend it.


An analytic function satisfies $f(1/z)=f(z) $, if $f$ is real on $\{|z|=1\}$, then the coefficients of expansion are real.

Question: An analytic function satisfies $f(1/z)=f(z),\forall z \in \mathbb{C}\backslash\{0\} $, if $f$ has real values on $\{|z|=1\}$, then the coefficients of the Laurent expansion are all real and.
Here is my try, $f(z)=\sum_{n=-\infty}^{n=\infty} \alpha_n z^n=f(\frac{1}{z})=\sum_{n=-\infty}^{n=\infty} \alpha_nz^{-n}$, so $\alpha_n=\alpha_{-n},\forall n\geq 1.$
On $|z|=1, f(z)$ is real, so $\alpha_0=\frac{1}{2\pi i}\int_{|\zeta|=1}\frac{f(\zeta)}{\zeta}d\zeta=\frac{1}{2\pi}\int_0^{2\pi}\frac{f(e^{i\theta})}{e^{i\theta}} \cdot e^{i\theta}d\theta\in \mathbb{R}$.
When $n\geq 1$,
$\alpha_n=\frac{1}{2\pi i}\int_{|\zeta|=1}\frac{f(\zeta)}{\zeta^{n+1}}d\zeta=\frac{1}{2\pi}\int_0^{2\pi}\frac{f(e^{i\theta})}{e^{i\theta {(n+1)}}} \cdot e^{i\theta}d\theta=\frac{1}{2\pi}\int_0^{2\pi}\frac{f(e^{i\theta})}{e^{i\theta n}}d\theta$
$\bar{\alpha_n}=\overline{\frac{1}{2\pi}\int_0^{2\pi}\frac{f(e^{i\theta})}{e^{i\theta n}}d\theta}=\frac{1}{2\pi}\int_0^{2\pi}\overline{(\frac{f(e^{i\theta})}{e^{i\theta n}})}d\theta=\frac{1}{2\pi}\int_0^{2\pi}\frac{f(e^{i\theta})}{e^{-i\theta n}}d\theta=\alpha_{-n-1}$
Actually the answer said that $\bar{\alpha_n}=\alpha_{-n}$. I don't know what is wrong in the calculation.
Answer: The expression you compute for $\overline{a_n}$ looks much more like the expression you computed for $a_{-n}$ thanlike the one you computed for $a_{-n-1}$.
Comment: Yes, i mixed up the $\int_{|\zeta|=1} \frac{f(\zeta)}{\zeta^{(n+1)}} d\zeta$ and $\int_0^{2\pi} \frac{f( e^{i\theta})}{ e^{i\theta n}} d\theta$
Answer: An approach which is quite similar, but not completely identical, to that of Adam Hughes:  consider $z$ such that $\vert z \vert = 1$; we may write $z = e^{i \theta}$ for such $z$.  Then we have $\bar z = z^{-1} = e^{-i \theta}$.  Expanding $f(z) = f(z^{-1})$ in terms of $e^{i \theta}$ on the circle $\vert z \vert = 1$ yields
$f(z) = f(e^{i \theta}) = \sum_{n = -\infty}^{n = \infty} a_n e^{in\theta} \tag{1}$
and
$f(z^{-1}) = f(e^{-i \theta}) = \sum_{n = -\infty}^{n = \infty} a_n e^{-in\theta}; \tag{2}$
using $f(z) = f(z^{-1})$ we obtain
$\sum_{n = -\infty}^{n = \infty} a_n e^{in\theta} = \sum_{n = -\infty}^{n = \infty} a_n e^{-in\theta}, \tag{3}$
from which it follows that $a_m = a_{-m}$ for all $m \in \Bbb Z$, as has been observed by our OP user159895.  Or, to make a somewhat more formal argument, we note that, since $f(z)$ is analytic on $\Bbb C \setminus \{0\}$, it is continuous on $T = \{z \in \Bbb C \mid \vert z \vert = 1 \}$, hence $f(e^{i\theta}) \in L^2(T)$, and since the functions $e^{in\theta}$, $-\infty < n < \infty$, constitute an orthonormal basis for $L^2(T)$ with respect to the usual inner product
$\langle \omega, \sigma \rangle = \dfrac{1}{2\pi}\int_0^{2\pi} \bar \omega(\theta) \sigma(\theta) d\theta, \tag{4}$
we may simply compute, from (3)
$a_m = \langle e^{im\theta}, \sum_{n = -\infty}^{n = \infty} a_n e^{in\theta}\rangle = \langle e^{im\theta}, \sum_{n = -\infty}^{n = \infty} a_n e^{-in\theta} \rangle = a_{-m}; \tag{5}$
likewise, exploiting the hypothesis that $f(z)$ is real on $T$, so that $f(z) = \overline {f(z)}$ there, we find that
$\sum_{n = -\infty}^{n = \infty} a_n e^{in\theta} = \overline{\sum_{n = -\infty}^{n = \infty} a_n e^{in\theta}} = \sum_{n = -\infty}^{n = \infty} \bar a_n e^{-in\theta}; \tag{6}$
if we now take the $L^2$ inner product of (6) with $e^{-im\theta}$ we see that
$\bar a_m = a_{-m}, \tag{7}$
which combined with our previous result
$a_m = a_{-m} \tag{8}$
yields
$\bar a_m = a_m, \tag{9}$
the desired conclusion.  QED
Note:  The preceding answer assumes my readers are familiar with the basic facts of Fourier analysis on the unit circle $T$, such as $\langle e^{im\theta}, e^{in\theta} \rangle = \delta_{mn}$ and $c_m = \langle e^{im\theta}, \sum_{n = -\infty}^{n = \infty} c_n e^{in\theta} \rangle$ for $\sum_{n = -\infty}^{n = \infty} c_n e^{in\theta} \in L^2(T)$.  The former is easy to see by direct integration:
$\langle e^{im\theta}, e^{in\theta} \rangle = (1/2\pi)\int_0^{2\pi} e^{-im\theta}e^{in\theta}d\theta = (1/2\pi)\int_0^{2\pi} e^{i(n - m)\theta}d\theta$
$= (1/2\pi)(i(n - m))^{-1}(e^{i(n - m)2\pi} - e^{i(n - m)(0)}) = 0 \tag{10}$
if $m \ne n$ and
$\langle e^{n\theta}, e^{in\theta} \rangle = (1/2\pi)\int_0^{2\pi} e^{i(n - n)\theta}d\theta = (1/2\pi)\int_0^{2\pi}1 d\theta = (2\pi/2\pi) = 1. \tag{11}$
The formula
$c_m = \langle e^{im\theta}, \sum_{n = -\infty}^{n = \infty} c_n e^{in\theta} \rangle \tag{12}$
follows from (10) and (11) via term-by-term integration.  But these are commonly known tricks of the trade, and most likely anyone reading this post has seen them already.  End of Note.
Hope this helps.  Cheers,
and as always,
Fiat Lux!!!


New List Items Added Via Javascript need separate IDs

Question: fairly new to html, css, and javascript- also compeltely new to stackoverflow.
I am making an html list, which users can add to by typing in an text input, but I want to add buttons to each new li that will cause that specific li to change to a strikethrough text-decoration.
My javascript code for the function is:
function addListItem() {
      var input = document.getElementById('listAdd').value;
      var ul = document.getElementById("list");
      var li = document.createElement("li");
      var buttonId = document.getElementById('button1').id;
      var button = document.createElement('input');
            button.type = "button";
            button.name = "name";
            button.value = "Done";
            button.id = buttonId +"1";
      li.appendChild(button);
      li.appendChild(document.createTextNode(" "+input));

      ul.appendChild(li);
 }

I'm assuming I need to create a separate function that would apply to each added item to the ul, but the issue I'm running into is the id of each new li.
As it currently stands, all new li will have an id of "button11", where as I would need them to each have a unique identifier.
Should I use an if statement to achieve this?
Thanks to any and all who have suggestions, citicism, etc.
Comment: Don't use IDs - that kind of defeats the purpose. Use a class instead, if necessary
Comment: If you add the event listener in your function then you already have references to all the other elements within the `` and the `` itself. Dynamically incrementing ID's is more work than it's worth. note you wold always end up incrementing `button1` and therefore all added items would have same ID
Answer: button.id = buttonId +"1" is string concatenation, not any form of arithmetic or incrementation.  You would need a number for both operands for arithmetic (and "1" is a string, not a number).
I agree with CertainPerformance that an id is likely unnecessary but if you did want a unique identifier for each button, you could use the count of existing buttons (as long as you are only adding and not removing buttons):
button.id = 'button' + li.getElementsByTagName("button").length + 1;

li.getElementsByTagName("button") will get an array of existing buttons under that
.
Comment: Problem with that approach will show up if items start getting removed
Comment: Thanks everyone!  I wanted to see if it was possible to do this. Devon's answer gave me the clue I needed, and I used getElementsByTagName("li").length to solve this issue. I do not need to remove items from the list, but that is a great thought for future projects!  Thanks again!


value already exist using bootstrapvalidation on codeigniter if value already exist

Question: I Tried using bootstrap validation for a project with CodeIgniter framework , but when I insert the current value ' ID ' validation does not work when there is value already exist in the database.

ITS SOLVED

this my controllers
public function check_user()
{
    $id= $this->input->post('id');
    $result= $this->mcrud->check_user_exist($id);
    if($result)
    {
        echo "false";

    }
    else{

        echo "true";
    }
}

this my models
public function check_user_exist($id)
{
    $this->db->where('id',$id);
    $query= $this->db->get('tbdetail');
    if($query->num_rows()>0)
    {
        return $query->result();
    }
    else
    {
        return false;
    }
}

and this my javascipt for validation
$(document).ready(function() {
    $('#defaultForm').bootstrapValidator({
        message: 'This value is not valid',
        icon: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },

        fields: {
            id: {
                    row: '.col-md-3',
                        message: 'ID Tidak Valid',
                        validators: {
                            notEmpty: {
                                message: 'ID tidak boleh kosong'
                                },
                            remote: {
                                url: '<?php echo base_url(); ?>index.php/instrument/detailalat/check_user',
                                type:'POST',
                                message: 'ID sudah ada'
                                }
                        }
                },

Answer: As i notice, you are not passing any value through post using data,
So try this,
    id: {
          row: '.col-md-3',
          message: 'ID Tidak Valid',
          validators: {
                notEmpty: {
                     message: 'ID tidak boleh kosong'
                },
                remote: {
                     url: '<?php echo base_url(); ?>index.php/instrument/detailalat/check_user',
                     type:'POST',
                     message: 'ID sudah ada',
                     data: function(validator) {
                          return {
                               id: $('[name="name of the id in your form"]').val(),
                          };
                     },
               }
         }
    },

For more information see here
Comment: thanks @Niranjan N Raju,  I tried but it was not working . what wrong with the controller and the model ??
Comment: check the console, is the `id` passed to controller?? echo the id in controller and see what you are getting there.
Comment: Also instead of `return $query->result();` try with, `return $query->num_rows();`
Comment: did u check with that??
Comment: is the value going to controller??
Comment: whats wrong with my controllers? result validation false
Comment: are you able to pass the value?? echo the id in controller see in console.
Comment: it solved thanks @Niranju, there are script less complete i change controllers with ,
`$id= $this->input->post('id');
$result= $this->mcrud->check_user_exist($id);
if($result==0)
        {
    $isAvailable = true;

        }
        else{

   $isAvailable = False;
       }

  echo json_encode(array(
   'valid' => $isAvailable,
   ));`


"Slow" and "fast" rates of convergence

Question: I have recently read about convergence and divergence. However, I am having trouble understanding how something can converge/diverge "slowly" or "fast". If you sum up two series (that converge to the same number) infinitely, they will converge, not at any particular rate, but just to the number- this is how I see it.
So what does it mean for a series to converge (or diverge) slowly?
Answer: Suppose $\sum x_n$ converges. Given a positive $\varepsilon$; let $S:(0,\infty)\to \Bbb N$, $S(\varepsilon)$ give the smallest $N$ such that $|x-\sum^N x_n|<\varepsilon$. This measures convergence, in some sense.
Suppose $\sum x_n$ diverges to positive infinity. Given a positive $M$, let $S:(0,\infty)\to \Bbb N$, $S(M)$ give the smallest $N$ such that $|\sum^N x_n|>M$. This measures divergence, in some sense.
As an example, if $x_n=1/n$, then $S(N)\sim e^N$, this says that the divergence is very slow. That is, the larger $S(N)$ is, the slower the series diverges.
For convergence, we're worried at what happens with $S(\varepsilon)$ as $\varepsilon\to 0$. For $S(M)$; we're interested at what happens as $M\to\infty$.
Answer: We define the sum of an infinite sequence $a_1,a_2,\dots$ to be the limit of its partial sums:
$$
\sum_{k=1}^\infty a_k = \lim_{N\to\infty}\sum_{k=1}^N a_k.
$$
The series converges quickly if the limit of partial sums converges quickly; the series converges slowly if the limit converges slowly. Similarly, the series diverges quickly if the limit goes to infinity very quickly and diverges slowly if the limit goes to infinity very slowly.
In the interest of being more concrete -- I never said what I meant by "slowly" or "quickly", did I? -- let me give you a few examples.

The divergent series $\sum_{k=1}^\infty 1$ has partial sum $n$; it diverges as quickly as $n$ grows.
The divergent series $\sum_{k=1}^\infty 1/k$ has partial sum very close to $\log n$, meaning that it diverges very slowly. To reach a sum greater than $100$, for example, you would need to add up something like the first $3\times10^{43}$ terms.
The convergent series $\sum_{k=0}^\infty (-1)^k/k!$, which sums to $e^{-1}$, converges quickly: the difference between the $n$th partial sum and the sum of the series is no more than $1/(n+1)!$. This follows from basic properties of alternating series. To calculate $e^{-1}$ to $5$ decimal places you would have to add the first $8$ terms of the series.
The convergent series $\sum_{k=1}^\infty (-1)^k/k$, which sums to $\ln 2$, converges much more slowly: to calculate $\ln 2$ to $5$ decimal places you would need to add the first $500000$ terms of the series.
Answer: Think about those two series (we'll call them S1 and S2) you mentioned that converge to the same number. Let say that both series get to that number after at least 50 terms in each series. So, at 50 terms, the sum you have at that point in S1 will be different than the sum of S2 at 50 terms. The series with the sum at 50 terms that is closer to the convergence point is the series that is approaching it faster at 50 terms.
Comment: Welcome to this site! The question you just answered is more than a year old and already has perfectly good answers, to which your post does not seem to add much.  What would add more value to the site would be to answer unanswered questions, or provide new answers that contain substantially more or different information than the existing ones.

"Slow" and "fast" rates of convergence


How should I respond with different status codes to a GET request in Spray?

Question: For POST and PUT requests I use the following syntax:
put {
  entity(as[CaseClass]) { entity =>
     returnsOption(entity).map(result => complete{(Created, result)})
       .getOrElse(complete{(NotFound, "I couldn't find the parent resource you're modifying")})
  }
}

Now for GET requests I'm trying to do the same, but I can't get it to work analogously to my PUT solution. What is a good way to do this with GET requests?
Update:
I've got this working with the following hack:
(get & parameters('ignored.?)) {
  //TODO find a way to do this without ignored parameters
  (ingored:Option[String]) => {
     returnsOption().map(result => complete(result))
       .getOrElse(complete{(NotFound, "")})
  }
 }

I'd expect something similar to be possible with () => or ctx => , but that doesn't fly,  because it gives trouble with marshalling:
... could not find implicit value for evidence parameter of type spray.httpx.marshalling.Marshaller[(spray.http.StatusCodes.ClientError, String)]
    }).getOrElse(ctx.complete{(NotFound, "")})
                             ^

Could it be that this somehow relates to the fact that I'm using spray-json?
Answer: Use HttpResponse like this for example
complete{
  HttpResponse(StatusCodes.OK, HttpBody(ContentType(`text/html`), "test test: " + System.currentTimeMillis.toString))
}

Update: I've been using Spray for a while now. Turned out there is better way:
complete {
  StatusCodes.BandwidthLimitExceeded -> MyCustomObject("blah blah")
}

Comment: @Phil Thank you for reminding me about this question. Yes, there is better way. I updated the answer.
Comment: Is there a more concise way to write this?
Answer: This code should work:
get {
  ctx =>
     ctx.complete(returnsOption())
 }

If don't use ctx => at the start, your code might only be executed at route build time.
Here you can find some explanations: Understanding the DSL Structure
Comment: That works, but I want to return a different StatusCode based on wether the Option is defined. If you map the option to complete it gets executed once only on startup, which is not my intent.
Comment: That's exactly why you should read the above documentation on the topic. The important thing is to understand that only the code inside of the block started with `ctx =>` is guranteed to be executed on each request and other code may be executed only (which sometimes may be at request handling time but not necessarily) during route _building_ time.
Comment: @jrudolph I understand that, I'll edit the question to reflect that part. Now if the code would return a different status code based on the content of the option, it would totally answer the question.
Comment: get {
  ctx =>
     returnsOption().map(result => ctx.complete(result))
       .getOrElse(ctx.complete{(NotFound, "")})
 }
Comment: your last example works fine. In my case it wasn't working because of a marshaller problem, unrelated to the question.


Problem with installation of DB2

Question: I have a problem with installation of IBM DB2, it tells me it didn't find libpam.so. Is there a package I have to install to correct the problem?
I used to find a solution on the web but I found nothing that managed to correct my problem.
Answer: My worries is, that Ubuntu is not a supported system for DB2. if you look into this document: (http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=%2Fcom.ibm.db2.udb.apdv.gs.doc%2Fdoc%2Fr0023433.htm) you will see, that Ubuntu is not listed there, but all red-hat-like systems are.
U can try to discover unsupported install of DB2 (I will not recommend it), or you can choose the proper way with different Linux distribution.
For development purposes you can stay on Ubuntu and run DB2 in a Virtual machine (VirtualBox, http://www.howopensource.com/2013/04/install-virtualbox-ubuntu-ppa/) and virtualize the supported server. For production server purpose better to choose proper OS, it will run on server, anyway, does not matter that this is not Ubuntu.
Comment: So should I install OpenSUSE instead of Ubuntu in order to install DB2 on my system? I look for a free system like Ubuntu is.
Comment: @Steve: If you like Ubuntu desktop, you can try the virtualisation way... You will need DB2 on the server anyway... and server environment does not differ so much on Suse or Fedora or Ubuntu. Your desktop is one thing, DB2 installation on the server is another. So you can try following: Ubuntu 13.04 desktop, Virtualbox, Virtualised FedoraCore4 and DB2 on it. I would choose Fedora as it is the most similar to RHEL, which is widely used in production systems.
Answer: Find out where libpam.so.0 exists on your machine under /lib.
Copy this libpam.so.0 to /lib (don't create a soft link)
Answer: Using Ubuntu Server I had the same issue. Just do the following steps:
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt install libpam0g:i386

Problem with installation of DB2


How to get the THX helicopter mod without needing minecraft.jar in finder?

Question: I might have accidentally deleted minecraft.jar in ~/Library/Application Support/minecraft and I need it to download thx helicopter mod. How can I still download THX helicopter mod without minecraft.jar?
Comment: That's not how mods are installed anymore. What version of Minecraft are you using, and what version does the mod say it is for?
Answer: You don't need that file anymore – it's a leftover from version 1.5.x, and since then the equivalent file (which contains most of the actual game) is stored in the versions folders, one for each version of the game you've installed with the new launcher. You don't need minecraft.jar anymore, and can't install mods using it anymore anyway since the game doesn't even use it anymore.
So some digging turns up this THX Helicopter mod. It's not available for the current version of Minecraft – the latest it supports is 1.6.1 – and requires Forge (or ModLoader, but who uses that anymore).
Fortunately, the normal Forge install instructions will get you 99% of the way to having this mod installed. Then just drop the mod's zipfile (make sure it's the 1.6.1 version) into the folder the Forge instructions tell you to put mods in, then play (again, using the launcher profile the Forge install instructions tell you to use).


Proving integer inequality

Question: I am having trouble proving this inequality:
For positive integers $p$, $q$, $c$, $k$ such that $2 \le p < q$:
$$
\frac{(p-1) \, p^{k-1} / \, (c p^k - 1)}{(q-1) \, q^{k-1} / \, (c q^k - 1)} \le 1
$$
Note that I have verified it empirically in code for thousands of small values.
Answer: Your statement is equivalent to saying the function
$$f_{c,k}(x)= \frac{(x-1) \, x^{k-1} }{ c x^k - 1} $$
is increasing on the set of integers $x \ge 2$.
Now, extend this function to the real interval $(1, \infty)$.
You have
$$ f'(x)=\frac{x^{k-2} }{ (c x^k - 1)^2} (cx^k-kx+k-1)$$
we clearly have
$$\frac{x^{k-2} }{ (c x^k - 1)^2}  >0$$
and by Bernoulli's inequality
$$x^k \geq 1+k(x-1)=1+kx-k$$
thus
$$cx^k-kx+k-1 \geq x^k-kx+k-1 \geq 1+kx-k-kx+k-1=0$$
This shows that $f(x)$ is increasing on $(1, \infty)$, which proves your statement.
Comment: Thank you for the quick answer! I will incorporate it into my proof and verify each line before accepting. It looks reasonable and understandable to me at a glance.
Comment: If there happens to be an alternative simpler/shorter answer (such as one that involves manipulating integer inequalities without calculus), I would appreciate it. I want to fully understand and internalize this part of the proof before proceeding with work that builds on it.
Comment: How does the Bernoulli step work?
Comment: @Nayuki Bernoulli inequality says: If $n$ is a positive integer and $y$ is a real number with $y \geq -1$ then $$(1+y)^n \geq 1+ny$$ Now replace $y=x-1$...
Comment: Thanks! I was able to find more information based on the full name (which wasn't clear to me before). [Bernoulli's inequality at Wikipedia](https://en.wikipedia.org/wiki/Bernoulli's_inequality)
Comment: A slight correction: The interval should be $(1, \infty)$ because $f(1)$ is a division by zero when $c=1$.
Comment: @Nayuki Yes, you are right.
Comment: Awesome. Because in my world, buggy theorems can crash computer programs. =)

Proving integer inequality


Meaning of open (and closed) subgroup

Question: In Cassels and Froehlich's ANT, I met with the following statement:

p. 5: The additive group of $K$ is the union of open (and hence closed) subgroups $\mathfrak p^n$ ($n\in \Bbb Z$), whose intersection is zero.

Here $\mathfrak p$ is the prime ideal associated to a valuation on $K$. Since C&F didn't talk about topology up to this moment, I am not sure what the adjectives open and closed could mean. And even if they have a topological meaning, why does openness imply closedness? And why is the additive group of $K$ a union of only these subgroups? If we pick $\Bbb Q$ with the 5-adic valuation, for example, we still have many elements which do not lie in $(5)^n$.
Answer: The valution associated with $\mathfrak p$ defines a metric and hence a topology on $K$. And, yes, in this sense the subgroups considered are both open and closed. Saying "and hence" is indeed a bit strange though if the topological notions have not been investigated a bit before ...
For your last question: Note that $\mathfrak p^n$ is considered with $n\in\mathbb Z$, not merely $\mathbb n\in \mathbb N_0$.
Answer: In a topological group, an open subgroup is also necessarily closed.
(Each coset is open, hence the union of all the non-identity cosets is open, and hence the subgroup itself, being their complement, is closed.)

Meaning of open (and closed) subgroup


Does Crashlytics Manage Offline Crashes.

Question: Fabric Crashlytics is a very good facility to handle the crashes in Android and iOs. But I want to know does it handle Offline crashes. If yes then please give me an example in android so that I can apply it in my projects.
Comment: Hello, guys !

 I am searching alternate which can catch crashes when the Internet is not available in Mobile. please answer me ..
Answer: Crashlytics autosave crashing report into a cache If Network and Wi-Fi connectivity are not available. **There is no need to add additional code to get offline crashes **. Crashing error are sent them into crashlytics dashboard when mobile get again network connectivity at app restart.
Please check following answer link and this one also which are posted on StackOverflow by ex-employee of crashlytics companies


Log4j2: How can I get Class Name and Line Number without using Throwable?

Question: I have developed a wrapper class on Log4j2. Using declarative services of OSGi I have published a custom logger service using my own logger interface with the wrapper class being the implementation. The wrapper class is only used to configure the logger programmatically, message formatting & add a few more methods, at last it is calling the logging methods of Log4j2.
I want to print source class/file name and line number of each logs requested in the log file. The options %C/%F and %L only print information about the location inside my wrapper class where I actually call the log method.
So as a workout I am passing new Throwable as an argument each time so that I can use the layout %throwable{short.lineNumber}. But this is an expensive process for embedded applications.
My main problem is in getting the line number because for the file name I could at least request a new logger from Log4j2 with the name of each service requesting for logger service and keep it in a map.
Is there a solution to trace back the caller? I hope there is a similar solution for applications where you don't want to have the LOG4j2 jars on each consumer of the logger service. Just for info, I don't want to use any XML files, all configurations are made programmatically.
Comment: Log4j also used stack trace to identify those information.
Comment: Interesting question.  Perhaps look at the source of log4j and see how they do it.
Answer: You can use
StackTraceElement[] stes = Thread.currentThread().getStackTrace();

however I am not sure this is much cheaper.
What I do is make each message unique (for the class) and avoid including the line number. You can search for the unique message in your IDE to find the line number.  The class should be in the name of the logger.
Comment: Hi Peter, thank you for the answer. I have not seen other alternatives so I think calling the stack trace from my  wrapper class on each log might be the current solution(if I understand your answer correctly). And because of project requirement, I'll need the line number. But Log4j2 only takes one message argument, do you have any suggestion on how to pass the extracted information other than concatenating the string in the message to be logged?
Answer: Log4j2 internally walks the stacktrace to extract location information. It knows where to stop in the stack trace by specifying the correct FQCN (fully qualified class name) to the org.apache.logging.log4j.spi.ExtendedLogger#logMessage method.
Log4j2 contains a tool that generates code for logger wrappers. The documentation is here (in the Custom Log Levels manual page):
http://logging.apache.org/log4j/2.x/manual/customloglevels.html#CustomLoggers
Try generating a logger wrapper with this tool and base your custom wrapper on the generated code. This generated code will use the correct FQCN and will be able to produce the correct location information.
Answer: as @Remko Popma said, here is a simple implementation:

First create your ExtendedLogger class:
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.spi.AbstractLogger;
import org.apache.logging.log4j.spi.ExtendedLoggerWrapper;

public class ExtLogWithLine extends ExtendedLoggerWrapper {
    private static final long serialVersionUID = 8239280349129059055L;

    // define your wrapper class here
    private static final String FQCN = WrapperLog.class.getName();

    private final ExtendedLoggerWrapper logger;

    private ExtLogWithLine(final Logger logger) {
        super((AbstractLogger) logger, logger.getName(), logger.getMessageFactory());
        this.logger = this;
    }

    public static ExtLogWithLine create(final String name) {
        final Logger wrapped = LogManager.getLogger(name);
        return new ExtLogWithLine(wrapped);
    }

    @Override
    public void debug(String info) {
        if (isDebugEnabled()) {
            logger.logIfEnabled(FQCN, Level.DEBUG, null, info, (Throwable) null);
        }
    }

    @Override
    public void info(String info) {
        if (isInfoEnabled()) {
            logger.logIfEnabled(FQCN, Level.INFO, null, info, (Throwable) null);
        }
    }

    @Override
    public void warn(String info) {
        if (isWarnEnabled()) {
            logger.logIfEnabled(FQCN, Level.WARN, null, info, (Throwable) null);
        }
    }

    @Override
    public void error(String info) {
        if (isErrorEnabled()) {
            logger.logIfEnabled(FQCN, Level.ERROR, null, info, (Throwable) null);
        }
    }
}

Then user the exetended logger to print log:
public class WrapperLog {

    public void testLog() {
       ExtLogWithLine logger = ExtLogWithLine.create("xxx");

       // log will print out with correct line number
       logger.info("see the line number");
    }
}


Failed to execute SP with error PLS-00201

Question: I've stored procedure called CAL_TAX which create by schema EMP_DBA, right now I want to grant execute right on this SP to user USER1. I've execute below statement:
CREATE USER USER1 IDENTIFIED BY USER1234;
GRANT CONNECT TO USER1;
GRANT RESOURCE TO USER1;
GRANT CREATE SESSION TO USER1;
GRANT EXECUTE ON EMP_DBA.CAL_TAX TO USER1;

DECLARE
CURSOR C1 IS SELECT TABLE_NAME FROM USER_TABLES;
CMD VARCHAR2(200);
BEGIN
FOR C IN C1 LOOP
CMD:='GRANT SELECT ON ' || C.TABLE_NAME || ' TO USER1';
EXECUTE IMMEDIATE CMD;
END LOOP;
END;

When I connect as USER1 and execute SP CAL_TAX, I received below error messages. Can anyone help me on this ? I've no problem to execute SP if connect as EMP_DBA
BEGIN CAL_TAX; END;

         *
ERROR AT LINE 1:
ORA-06550: LINE 1, COLUMN 7:
PLS-00201: IDENTIFIER 'CAL_TAX' MUST BE DECLARED
ORA-06550:LINE 1, COLUMN 7:
PL/SQL: STATEMENT IGNORED

This is the part of the SP CAL_TAX.
CREATE OR REPLACE PROCEDURE CAL_TAX
AUTHID CURRENT_USER
IS
.
.
.

Answer: You need to either specify the owner of the SP:
BEGIN emp_dba.cal_tax; END;

or, you can create a public synonym:
CREATE PUBLIC SYNONYM cal_tax FOR emp_dba.cal_tax;

or you can create a private synonym for each user:
CONNECT user1/pw
CREATE SYNONYM cal_tax FOR emp_dba.cal_tax;

Once the synonym is created, your original BEGIN..END block should work.
Comment: BEGIN CAL_TAX; END;

*
ERROR at line 1:
ORA-00942: table or view does not exist
ORA-06512: at "EMP_DBA.CAL_TAX", line 111
ORA-06512: at line 1
Comment: I can run the SP with USER1 once specified EMP_DBA schema in SP
Comment: Need to see the source for your SP to know for sure, but it seems as if you're referencing a table you don't have appropriate permissions on.  Are you perchance updating a table at line 111?


In CPLEX, How can I use variables in forall loop syntax?

Question: I wanna use variables in cplex forall syntax like as below..
forall(j in {1,2,3,4,5,6,7})
{
  x[1][j] + x[1][(j+3)%7] + x[1][(j+4)%7] + x[1][(j+5)%7] +
  x[1][(j+6)%7] + x[2][j] + x[2][(j+3)%7] + x[2][(j+4)%7] +
  x[2][(j+5)%7] + x[2][(j+6)%7] >= 5;
}

But after I ran this script, there was a syntax eror because of (j+3)...
How should I make a script to use this algorithm?
Comment: What is the declaration of the array x[][]?
What error do you get?
Comment: I got syntax error because of j+4 in forall,
Comment: can't i use j+4 or j+3 in forall(j in) syntax?
Comment: could you paste the definition of x please?
Answer: There are different ways to solve this, basically you need a function which takes the j index and the offset as parameter and return the corresponding result.
This could be done with a constant matrix that you set at the beginning for each of the 7 j and offsets.
Then inside the loop you refer to
x[1][ f[j][3] ]


WinMerge select "Tools" -> "Generate Report" missing

Question: I used to have nice HTML reporting in WinMerge by selecting "Tools" -> "Generate Report".  Now that feature is missing.  Does anyone have a link to that plugin?  I've been scouring the prior versions in 7zip format to no avail.
Answer: It turns out that the "Generate Report" feature was there all along.  My mistake was in assuming that the menu item would be visible when the application first opened.  Once I did a file compare, the  "Tools" -> "Generate Report" option appeared.  Sorry for the confusion.  (Great feature for archiving code reviews BTW.)


Breadcrumbs with action menu - what are the best practices?

Question: I am curious about best practices for visualizing additional actions in breadrumbs.
Details: the user should be able to copy the IDs of the elements from the breadcrumbs.
Is it a good way to add such a solution as in the screenshot? Or is it better to avoid this?
Comment: Do you still have the navigation function as well? I feel like users would be confused if they are trying to use breadcrumbs in the standard way (navigation) and end up only having the option to copy
Answer: Breadcrumb Dropdowns
There are many examples on the internet like the one in the this page menu. The difference with the example in the question is that they are used for navigation, the primary function of a breadcrumb, not for an action like copying an element (At least I haven't seen it, Google: breadcrumb dropdown).

Image source processwire.com
However, I think the action can be implemented within the breadcrumb item, I would try making it clear that it is something separate from the navigation >


How can I get a single tile of natural gas out of my greenhouse?

Question: In Oxygen Not Included my greenhouse has a single tile of natural gas that has settled on the bottom. Whenever it moves over a plant, the plant stops growing.
I have a strong force of oxygen coming in from one end of the room, but it is just not blowing the natural gas out for some reason. The pressure inside the room is 1700 and outside is 1400, so there should be good circulation, but for some reason the natural gas does not move.
Answer: To remove it you would need to construct a Gas Pump in the room, which pumps into a Gas Filter. Then you could set the Gas Filter to filter Natural Gas, venting that outside the room and sending the Oxygen back into the room.
The second solution is to create a single tile empty space, in the same row as your farm tiles. This single space will eventually capture the Natural Gas as it sinks below Oxygen. As shown in this video.
Comment: I did try the low tile, but for some reason the natural gas never goes in there, it just floats around on top of the plants.
Comment: You might need to increase the Oxygen pressure.
Comment: I had a deoxydizer right under this room blowing into it. It was 1700g of oxygen per tile.


Halting problem on 2 registers

Question: How can we show that the halting problem on register machines equipped with only two registers
is unsolvable.
My intuition stems from assuming it is unsolvable on $n$ registers, but if we take a finite tuple of $n$ entries/registers, how do we get it to simplify to the two registers?
Comment: I don't have a concrete proof handy, but couldn't you save the data of n registers in the first register by using some tuple encoding, and use the second register for decoding?
Comment: Can you please elaborate on how the Turing machine encodes and decodes? I thought of incorporating a counter somewhere
Comment: Aaah, now I remember how to do this. You use the first register as "tape to the left of the head position" and the second as "tape to the right of the head position", and the symbol at the head position is stored in the state. Building the operations should then be straightforward.
Comment: How do you build the operations? Can you also please describe the setting which you started with? I don't quite understand that. Thanks
Answer: There is a proof sketch of this on the Wikipedia article Counter Machine with a reference to Minsky's 1967 textbook on computability.
The interesting thing is that a two-register machine is only Turing complete if the correct input/output encoding is used. There is no two-register machine that computes $f(n) = 2^n$ when the input is given by placing $n$ in one register and $0$ in the other. But if the input is encoded as $2^n$ in one register and $0$ in the other, there is a two-register machine program that will compute $2^{(2^n)}$ in the first register. So the input has to be encoded in a special way (place $2^n$ in the register), and the output has to be decoded in the corresponding way (the register will end up with the value $2^{f(n)}$).
A three register machine is able to compute $2^n$ given $n$ in a register, so it does not require this unconventional input encoding.

Halting problem on 2 registers


Why is AbortController not defined?

Question: I want to be able to cancel requests with fetch API and use new AbortController() Unfortunately I get an error in the console: AbortController is not defined
//  this.aborter = new XMLHttpRequest()  no error
    this.aborter = new AbortController() error

What might be the reason?
I'm using just vanilla JS without any dependencies.
Comment: On which browser and which version?
Comment: @karolis2017: Which version of Chrome
Comment: Based on MDN, AbortController is an experimental technology. You should be sure that you are running a browser with the correct version. See: https://developer.mozilla.org/en-US/docs/Web/API/AbortController
Comment: I tried to create AborterController in a browser and same error. Chrome. Why it doesn't support new AbortController() ?
Comment: updated browser and no problem. Thanks
Answer: try
this.aborter = new window.AbortController();

I found that on Chrome (v77) it didn't recognise AbortController with specifying it as a window property.
Also, after you call
this.aborter.abort()

you may need to re-initialise
this.aborter = new window.AbortController();

or future fetch statements won't work (the status will be aborted and it will throw an error!).
Answer: The MDN documentation on AbortController includes an up-to-date table of supported browsers.
The API is still marked as experimental, although it should be well supported in current browsers. Firefox has it since November 2017 (FF 57), and Chrome followed on April 2018 (Chrome 66).

Why is AbortController not defined?