What do these apt commands do?

Question: What do these commands do?

Acquire::http::No-Cache=True -o
  Acquire::BrokenProxy=true update
  Acquire::http::Max-Age "0"
Answer:
The following command, Acquire::http::No-Cache=True -o It adds an No-Cache header to APT http requests.
This command Acquire::BrokenProxy=true update Used for fixing your local proxy i guess.
This command Acquire::http::Max-Age "0" Maximum time to keep packages around for.
Comment: Thank you very much. Btw, does the first command disable cache forever? What if I install some package through apt after running that command?
Comment: -1 The Acquire::http::No-Cache=True does not disable apt caching features, it adds an No-Cache header to APT http requests, meaning it will not allow webservers to reply with cached contents (to make sure you don't get a server side cached index file).
Comment: @JoãoPinto are you sure??
Comment: Yes, I wouldn't penalize your answer based on a guess. Check "man apt.conf", search for "http" .
Comment: Alright Thank you @JoãoPinto i have updated my answer.
Comment: The first command solved my BADSIG error. Why?
Answer: I can't speak for the other options.
But, as of today, Acquire::BrokenProxy does nothing. It has done nothing since 2011 at the very latest. It did nothing in the version of Ubuntu that was current when this question was posted. If you look it up in the apt.conf man page, it is not there. If you look for it in the apt source code, it is not there. It's not quite using a regular expression to parse HTML, but it most definitely will not solve your problem and should never be used by anyone.
For one brief, shining moment, between 10:59 PM UTC on Friday, April 1st, 2005, when it sprang fully formed from the head of Michael Vogt, and 8:38 PM UTC on Monday, February 20th, 2006, when he reluctantly had to put it down, setting Acquire::BrokenProxy would force APT to always re-download the signature file for a package repository, instead of just asking to be sent it if it had been modified. Presumably this is because some "broken" proxies were just sending the old version of the file even when it has changed.
This is all it has ever done, as far as I can tell. You can git clone https://salsa.debian.org/apt-team/apt.git and git log -S "BrokenProxy" in there to find commits that add and remove this string to/from the APT source code; I only count the two.
This feature first came out in APT version 0.6.35ubuntu1 and would have last been available around APT version 0.6.43.3, going by the state of the changelog file at those commits. Digging through the Packages.gz files on http://old-releases.ubuntu.com, it looks like it should have had an effect on Ubuntu 5.04 (Hoary Hedgehog), Ubuntu 5.10 (Breezy Badger), and Ubuntu 6.06 LTS (Dapper Drake) (which has 0.6.40.1ubuntu9). Version 6.06 was an LTS release that went out of support in 2011. After 2011, or on any Ubuntu that is 6.10 (Edgy Eft), with apt 0.6.45ubuntu14, or later, nobody has had any business whatsoever using this option.
However, Acquire::BrokenProxy remains a popular apt.conf option to this day. It got its humble start in December 2005, when its author suggested it as a troubleshooting approach in an Ubuntu bug report about BADSIG errors. Over the next few years, many lost souls found their way to this bug report, and a few tried passing -o Acquire::BrokenProxy=true to their package managers, following an encouraging 2006 report by a user that it had worked for them. Despite a couple of subsequent reports that the option did not (and, depending on Ubuntu version, most likely could no longer) help, in 2009-2010 the option made the rounds on blogs and forums, and by 2012 it had been posted back on the BADSIG bug as part of "the fix" for a misbehaving proxy.
In 2013, two major technologies arrived on the scene that changed computing forever: the Docker container management system, and the 99fixbadproxy APT config file:
Acquire::http::Pipeline-Depth "0";
Acquire::http::No-Cache=True;
Acquire::BrokenProxy=true;

Soon, people began combining the power of these two technologies, presumably because Docker image building is an apt stress test and the other two options actually do something useful. Today, the 99fixbadproxy file, with this option that has never had any effect in any Ubuntu version that has ever been available as a Docker image, can be found in Dockerfiles all over Github. It has even ascended to become part of Github itself: if you use Github Actions to run tasks on Ubuntu, your Ubuntu machine will be configured with Acquire::BrokenProxy by a 99fixbadproxy-descendant.
Truly, it is impossible to underestimate the power of the Acquire::BrokenProxy option. It's completely inert, it comes attached to other code that may or may not help resolve an intermittent failure, and it looks plausible enough that hardly anyone, present company excepted, has ever thought to question its presence.

What do these apt commands do?


End of Week - Needs to be Monday

Question: I have a SQL Query, where I need the week ending date to appear as Monday. I tested the following code, but received responses on Saturday, Sunday, Monday, etc. Please help?
SELECT DATEADD(DD, 7-(DATEPART(DW, MIN([Date])))
  , MIN([Date])) AS EndOfWeek, COUNT(*) AS TermsPerWeek

FROM Table

WHERE [Date] NOT LIKE 'null'
 AND ([Date] LIKE '%2016%' OR [Date] LIKE '%2017%')

GROUP BY DATEPART(WEEK,[Date]);

Comment: [Bad Habits to Kick : Using shorthand with date/time operations - Aaron Bertrand](https://sqlblog.org/2011/09/20/bad-habits-to-kick-using-shorthand-with-date-time-operations)
Answer: Using set datefirst:
set datefirst = 2

This will treat the start of the week as Tuesday, and the end as Monday.

End of Week - Needs to be Monday


How to customize the console colors of GlassFish's errors in Eclipse IDE

Question: I've came to a point where the console log's colors of GlassFish in Eclipse are annoying me.
Unlike Tomcat that prints errors in red and stacktraces in blue with the possibility to click on a stacktrace element, GlassFish prints everything in black (very ugly formatting).
This of course makes it difficult to quickly debug, it's actually a headache.
So I'm wondering whether there's a way to make the output of GlassFish errors in the Eclipse console look more "beautiful" or at least look like Tomcat's errors.
p.s: I'm using Eclipse Java EE Juno and GlassFish 3.1.2 (server adapter tools installed)
Comment: Window > Preferences > GlassFish Preferences : Enable Colored Rendering in the GlassFish Log viewer.  I have it checked though i see no colors.
Answer: The following should work to 'colorize' any Console log in eclipse.
There is a plugin called Grep Console which highlights or colors Console log based on string patterns in the output.
Update Sites
Grep Console 2
http://eclipse.musgit.com
(requires Eclipse 3.4 (Ganymede) or higher and Java 5.0 or higher)
Grep Console 3
http://eclipse.schedenig.name
(requires Eclipse 3.7 (Indigo) or higher and Java 6.0 or higher)
Usage
Once you have installed the plugin using the Update Site, you should see an icon in the console view which should allow you to add Expressions (regular expressions) against which output in the Console is matched and formatting that you choose (backgroud color, foreground color etc.) is applied.
Screencast
Please see this screencast which shows the whole process.
New version (3.x) released.
I received a comment from the creator of the Grep Console plugin. He mentioned that Grep console 3 is has been released. I have added the link to the update site above (take a look at the requirements; if you are on an Eclipse version < 3.7 then you'll need to used v2.x of the Grep Console)
Comment: Just checked the screencast, it's indeed simple and useful. However i'm looking forward more screencasts and tips on how to use it, please send me a link where i can follow more screencasts about this plugin.
I'll leave the door opened till tomorrow for more answers and suggestions, before i check your answer as accepted.


How to pass reactive props from a SvelteKit __layout file to a page hosted in one of its slots?

Question: The example below has two files: index.svelte is hosted in the slot provided in __layout.svelte. When you click the button it should change the color of the box in the hosted page. The code below works fine if index.svelte is a child component, but does not work if index.svelte is a page hosted in the slot. I am sure this is because props work differently with hosted pages.
I have tried using setContext/getContext and a writable store to pass the information across, but I have not found a way to make this reactive so that the box color change takes effect immediately - everything I have tried requires reloading index.svelte to apply the color change.
Is there a reactive way to update elements on the hosted page immediately?
__layout.svelte:

<button on:click={onClick}>Red</button>

<slot color={color}></slot>

index.svelte:

Code above can be found here:
Example
Answer: You can create a store in the load function and pass this on one side to the layout and on the other side place in stuff.

<button on:click={onClick}>Red</button>

<slot />

Then in the load function of the page itself, you grab this store from stuff and pass it on with the props.

Now you have reactivity!
a note on shared state and global stores
This works fine as described above, if you have a store that 'lives' outside of the load function this is considered shared state and will be common among all users, so be carefull with this.


How many times should the dice be rolled to maximise chance of winning? 0

Question: A friend bets you $100 on a game involving two six-sided dice, one red and one green. You choose the number of times the pair of dice will be rolled. You win if the number of times a red 6 is rolled is at most 2 and the number of times a green 6 is rolled is at least 2.
a) How many times should the dice be rolled to maximise your chance of winning?
b) With that number of rolls, what are your expected winnings?
Comment: If you have $n$ rolls of a single die, what is the probability of observing exactly $2$ sixes? $1$ six? $0$ sixes?
Comment: Rather tough question.  Empirically the maximum occurs at $n=12$.  Further experiment lead to the conclusion that for given $p$ the maximum occurs in the near of $2/p$; it's approximatly $0.4$.
Comment: @MichaelHoppe thanks so much, the answer is actually 12. If it's not too much trouble could you please explain how you got that? I've been struggling with it for days.
Answer: Let $R$ and $G$ let the number of $6$ in $n$ rolls on the red and green dice, resp.  Both are binomial r.v. with $p=1/6$.
We want to find $n$ which maximises
$$P(R\leq2\text{ and }G\geq2).$$
As the events are independent that probability is equal to
$$P(R\leq2)\cdot P(G\geq2)=P(R\leq2)\cdot\bigl(1-P(G\leq1)\bigr).$$
Assumably there's no analytic way to solve that problem, so simply try out some values of $n$; here $n=12$ gives the maximum $0.4191$.
It seems that in general the maximum is near $n=2/p$ (that is, the expected value is $2$); it's value is approximately $0.4$, independent of $p$.


Integer operators in bash

Question: How can I use ++, +=, *=, etc operators in bash script. Examples please.
Example in C++:
int a = 7;
a = ++a + ++a;
printf("%d", a);

Comment: I'm sorry, but your C++ example is flawed, because the + operator is not a [sequence point](http://en.wikipedia.org/wiki/Sequence_point).
Answer: In Bash you can do things like:
a=1
echo $((++a + ++a))
# result: 5, but don't write code like that

echo $((a+=4))
echo $((a*=4))
echo $((a/=2))
echo $((a-=1))

a=1; b=1
echo $((++a + ++b)) # Result: 4
echo $((--a + --b)) # Result: 2

a=1; b=1
echo $((a++ + b++)) # Result: 2
echo $((a-- + b--)) # Result: 4

The largest number that bash can handle is
echo $((2**63 - 1))
# Result: 9,223,372,036,854,775,807

Comment: I really hope for bash that the first result isn't 7. :P
Comment: @htorque, good point, in bash a=1; ++a + ++a is 5.
Comment: Actually, like in C, the result of `++a + ++a` is undefined. Also, there's not really any reason to do two increments on the same variable on the same line.
Answer: a=7; echo $a
#  7
((a+=a)); echo $a
# 14
((a*=-1)); echo $a
# -14
((++a)); echo $a
# -13

Answer: It is a wide argument, you should definitely go through bash man page, and through some good bash guide, as this BashGuide
In this page you will find some examples.

Integer operators in bash


RxJava - Use flowables async way

Question: Re-edit : I will use the result of this method to initialize the visibility of some buttons in my view
   The accepted answer seems good in theory but the return value of first method is Flowable> instead of Flowable. Hence I cannot pass it as a parameter to subscription since it requires Flowable but it is Flowable>
Question Before Edit
I am using RxJava to observe a method I am required to call from SDK. Using this method I am trying to make an assertion about the existence of something but I do not know how long the call will take so it is hard for me to say terminate the subscription after x seconds.
override fun doesExist(): Boolean {
        var doesExist = false
        var subscription : Subscription
        val flowable = Flowable.just(SDK.searchContact("contact"))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : FlowableSubscriber<Flowable<List<Contact>>> {

                    override fun onSubscribe(s: Subscription) {
                        subscription = s
                    }

                    override fun onNext(t: Flowable<List<Contact>>?) {
                        doesExist = true
                    }

                    override fun onComplete() {
                        Log.d("tagtagcomplete", "tagtagcomplete")

                    }

                    override fun onError(e: Throwable?) {
                        Log.d("tagtagerror", "tagtagerror")
                    }

        return doesExist
    }

So what I want to do is return true if I won't get any result from searchContract method and return false if I get a result. While using observables, I can create a subscription object and call it's methods but I could not figure out how to do it right way with flowables.
My confusion is the following: Method to sdk returns a Flowable<List<Contact>>> but in my opinion I need to check if a contact exists only once and stop
Right now my method does not go inside onError, onNext or onComplete. It just returns doesExist
Answer: I reedit my answer,following return type is you need.
fun doesExist(): Flowable<Single<Boolean>> {
    return Flowable.just(Single.just(SDK.searchContact("contact")).map{ it.isEmpty()})
}

Comment: Couple of questions - 1) Does this wait for searchContact to search one time. 2)When should I cancel the subscription, or does it cancel itself after some point? I can't cancel the subscription at onComplete as it warns me about the initilization of subscription
Comment: you can cancel it in other place,no in doesExist method
Comment: So how can I make it wait? I was using blockingSubscribe for observables in the previous construct. By the way this one liner seems much nicer and more understandable. I will accept it as the correct answer
Comment: do other operation after search
Comment: you can post more code ,I don't know what you want to do after searched result.
Comment: I have posted the code I want to do after this but I do not know if it will help much
Comment: yes,I've see that and I reedit my answer,please check it.I'm going to bed,any question will be answered at tomorrow.
Comment: Thanks, I have accepted your answer. My concern is that doesExist do not return Flowable, it returns Flowable>. So inside the subscription I cannot pass it as a parameter since it is of type Flowable> instead of Flowable. I am very new to RxJava and could not find a way to convert it. I will update here if I can find it
Comment: Hi, I have already fixed that and accepted your answer. My problem is out of my question's scope so you don't have to answer it. I am trying to assign this value to a MutableLiveData but method returns  Single so I can't assign it. I can change my variable to MutableLiveData> but then I want to assign false to that single value. With non-single boolean I can achieve it with myLiveData.value = false but I could not with single data
Comment: Okay,maybe you should ask a new question in this site.

RxJava - Use flowables async way


What is the maximum number of AVP points you can get?

Question: I started the game a while back, played for 60h or so then took a break (to finish other games :) ).
Anyway... at launch there were a ton of posts saying AVP is limited to 20. After I started again (last week, so there were a few patches) I hit 20... then 21... then 22. And it all worked well. So I just guessed they raised the cap.
Now I did the Meridian mission and got 2 more levels (24). But... immediately after I checked screen they went back to 22 (press esc, see 24, then press esc see 22 again). So... I did what any other normal person would do and loaded back the game, ran to AVP console and allocated all pods. Then pressed esc and seen 22 points again, but the pods were already allocated (and they remained like that). This is obviously a bug.
My question is... did they raise the cap (and the bug is that the points disappeared), or they didn't raise the cap and the bug is that I got those points in the first place?
All threads I find saying the cap is 20 are old. Does anyone know any new post regarding that? Or any change log?
Answer: They raised the cap to 29 in a patch a few weeks ago. Patch notes
Personally (though I'm not quite sure, I finished the game a month ago), I reached Level 25 (in theory, it was still capped at 20 back then, but judged by the amount of extra AVP I had back then) with 98% game completion


Why does pushing my locally created MEAN-Application to OpenShift not work?

Question: I'm trying to push my MEAN-Application, which I created locally using express, to OpenShift. For that, I create a new application from the dashboard and add NodeJS as a cartridge. When I then add my Git-Repository-URL (Hosted on BitBucket) and create the application, I get the following error:

When I create a new application without entering the repository URL and then pull from Openshift, copy in my Project and Push again, I get a similar error:

It seems to be some problem with port 8080 being unavailable but I cant resolve this myself as I'm new to this and couldn't find a solution on the web, so any help & advice is appreciated.
EDIT: when I say MEAN I actually mean EAN; I don't use MongoDB at the moment.
EDIT 2: after several hours I decided to try Heroku. It also didn't work on the first try but the Log contained far more useful information so I got everything up and running in about an hour (compared to like 4 hours of trying with OpenShift). After that I tried to push the exact same Project I pushed to Heroku to Openshift and got the following, new error:

Again, if somebody happens to know a quick fix for this please tell me as I would still like to use OpenShift.
Comment: The error message says port 8080 is not available. Do you have port 8080 hard-coded in your configuration, or are you using the value of `OPENSHIFT_NODEJS_PORT` like you are supposed to?
Comment: Where do I find the configuration? Will it still work locally when I change that and, if not, how can I achieve that without changing it every time I want to deploy?
Answer: Your NodeJS code should look something like this:
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
http.createServer().listen(port);

That will use the value of OPENSHIFT_NODEJS_PORT if it is available, and still use 8080 when you run the application outside of OpenShift. Or you could even set the environment variable OPENSHIFT_NODEJS_PORT=8080 on your local machine to more closely simulate the OpenShift environment.
Note that you should also check the environment variables to get the correct server IP address. See this documentation for more information.
Comment: the www File was created by Express, which set the port to `normalizePort(process.env.PORT || '3000');`. I changed that to `app.set('port', process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || 3000);
app.set('ip', process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1");`
But the Error didn't change.
Comment: It sounds like you may already have a version of your app running that isn't getting shut down for some reason. You could try restarting your app to see if that clears the issue up. Restart instructions are here: https://help.openshift.com/hc/en-us/articles/202399040-How-to-restart-an-application-
Comment: I tried that but that wasn't the reason. please see my updated question
Comment: I think you need to SSH into your server and view the logs in `app-root/logs/nodejs.log` to see what is really going on.
Answer: What worked for me was the following:

Create App on OpenSHift, leave Repo Url empty for now.
Use git remote add openshift -f <openshift-git-repo-url
(ssh://...something)> to add the Openshift-Repo as a remote Repo to your Project.
Use git merge openshift/master -s recursive -X ours to merge the Openshift-Repo into your local Repo and keep your files if conflicts appear.
(And this is the important step) Your main File (bin/www for me) has to look something like this (I tried everything to format this but it just didn't format properly):
var app = require('../app');
var debug = require('debug')('CTW:server');
var http = require('http');
/**

Get port from environment and store in Express.
*/
app.set('port', process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || 3002);
app.set('ip', process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1");

/**

Create HTTP server.
*/

var server = http.createServer(app);
/**

Listen on provided port, on all network interfaces.
*/

server.listen(app.get('port') ,app.get('ip'));
git push openshift HEAD to push it to your Application Repo

As it turns out, I had to set the IP.
All credit goes to this and this questions answers.


How do i create json array of object usingthe php code?

Question: for($i=0;$i<count($storetag);$i++){
    $user=mysqli_query($con,"select user_id,profile_image_url from Wheel_User where user_id='$storetag[$i]'");

    if(mysqli_num_rows($user)==0){
        //For failure status if session id is wrong.
        //http_response_code(404);
        echo json_encode(array("status"=>"404","error"=>"Sorry, post id does not exists.".die()));
    }
    else{
        $json_responce1=array();
        while ($row = $user->fetch_array()){
            $row_array['user_id'][$i]=explode(',',$row['user_id']);
            $row_array['profile_image_url'[$i]=$row['profile_image_url'];
        }
    }
}

array_push($json_responce1,$row_array);
echo str_replace('\/','/', json_encode(array($json_responce1)));

It returns the following JSON
{
user_id: [3]

  "1234",
  "31332",
  "12412"

profile_image_url: [3]

      "localhost/1234.com",
      "localhost/2345.com",
      "localhost/3456.com"

}

but i want the json format like this
"user_id":[
    {
        "id":"1234",
        "url":"localhost/1234.com"
    },
    {
        "id":"1234",
        "url":"localhost/1234.com"
    },
    {
        "id":"1234",
        "url":"localhost/1234.com"
    }
]

Answer: You want to organise your array slightly different.
Try this
$row_array['user_id'][$i]['id']=explode(',',$row['user_id']);
$row_array['user_id'][$i]['url']=$row['profile_image_url'];

Everything should be within user_id and then by putting the $i before $id and $url, you will be grouping them as required.


Convert pipe wrench to crescent wrench

Question: Has anyone seen any sort of jaw covers for a pipe wrench to be able to convert it to a crescent wrench (would also need to adjust the angle of the bottom jaw of course)?  It'd be nice to have able to use that for large heads without having to buy a larger crescent wrench or without marking up the head from the teeth by using it without covers.
Comment: Have not seen(or looked), but could probably make some with square tubing, cut in half.  Imagine this is for a once or twice a year job/s.
Comment: Yeah @crip659 for very occasional usage. Good idea on the square tubing as a starting point
Comment: It seams to me it would be more cost effective to just rent one!
Comment: What is this large bolt used on?
Comment: It was more of a just-in-case question @SteveWellens as I know in the past I've wished I had a larger crescent wrench. However, I have since ordered RIDGID 31400 which seemed like a better way to go and can open quite wide and have been happy with it. The largest nut of something I'm actively working on right now goes on a 1-1/4 bolt, and without measuring I'd guess it's around 1-3/4 which I've used that RIDGID wrench on.
Answer: A pipe wrench will never really act like a crescent wrench (or monkey wrench for that matter) because the jaw moves.  That's what makes it for pipes, the moveable jaw creates a lever that tightens on a pipe.  If you are solely looking to have something to put over the teeth to not mark up a piece then steel tubing would work.  But the moveable jaw means it will always be a poor tool for nuts/bolts, subject to more nut-rounding than the right tool, and having a second piece of metal between the jaw and the piece will only make this worse.
Comment: Ah good point about the moving. I guess you'd have to ensure it was in the moved state which would likely be annoying
Answer: Building off the idea @crip659 had in the comment on the question, could cut square metal tubing in half and then line each with a decently thick layer of something like JB Weld's SteelStik epoxy putty. Then them onto the corresponding jaw to mold it to the teeth and remove to let harden.
This would also allow for compensating for the jaw angle and it would keep it from slipping when in use.  Can't speak to the safety aspect of this approach so use with caution.
Comment: this seems like just ruining a good pipe wrench
Comment: @TigerGuy the key piece is removing promptly before gardening so that it fits the teeth but nothing is on there permanently

Convert pipe wrench to crescent wrench


Simplifying $\frac{x^2y + xy^2}{y^2 + \frac{2}{5}xy}$

Question: A bit confused on how to simplify the fraction below:
$$\dfrac{x^2y + xy^2}{y^2 + \frac{2}{5}xy}$$
Initially, I cancelled the numerator and denominator of $y^2$, where in the numerator there is only $x^2y + x$. However, for the denominator should the 5, in 2/5 be multiplied with the numerator to help simplify?
Comment: Yes, that's correct.
Comment: I recommend you think of simplifying fractions like this in terms of multiplying by $1$. For example, $1 = \frac{5/2}{5/2}$: Multiply through by this and what do you get? Another fancy $1$ you might consider is $1 = \frac{1/(xy)}{1/(xy)}$. Multiply through and what do you get? Just choose the special $1$ which makes the result as simple as possible. With experience, the choice becomes obvious
Comment: I think your formatting of the fraction is incorrect: you are missing some parentheses.
Comment: strictly speaking $2/5xy$ means $\frac{2}{5}xy$. Is that what you mean? Just making sure you're not going for $2/(5 xy)$
Comment: If you intend to "cancel $y^2$" you really mean dividing the numerator and denominator by $y^2$.  As two of the terms only have $y$ in them you will have a $y$ in a new denominator.  That is not progress.  You can cancel $y$ usefully, but not $y^2$.
Answer: Hint: You can write$$\frac{5x^2y+5xy^2}{5y^2+2xy}=\frac{5x^2+5xy}{5y+2x}$$ for $$y\neq 0$$
Answer: Assuming $y\ne0$, this is
$$5\frac{x^2+xy}{5y+2x}.$$
Answer: Maybe a bit of confusion about what is meant by the word "canceling".
In general, if a factor [not an addend (which is a number that is added), but a factor (which is a number that is multiplied)] is present in the numerator as well as the denominator, it can be canceled.
$$\frac{ac}{bc} = \frac{a}{b}\cdot\frac{c}{c} = \frac{a}{b}\cdot 1 = \frac{a}{b}$$
An elementary school example of this idea would be
$$\frac{15}{24} = \frac{5\times 3 }{8\times 3} = \frac{5}{8}\times \frac{3}{3} = \frac{5}{8}\times 1 = \frac{5}{8}$$
Moving into higher grades, we did the same thing, but it took this form instead
$$\frac{15x^2y}{24xy^3} = \frac{3\cdot5\cdot xy\cdot x}{3\cdot8\cdot xy\cdot y^2}=\frac{(3xy)(5x)}{(3xy)(8y^2)}=\frac{3xy}{3xy}\cdot\frac{5x}{8y^2}=1\cdot\frac{5x}{8y^2}=\frac{5x}{8y^2}$$
Although we canceled $3xy$ as a single number, we could have canceled each of it's components separately
$$\frac{3xy}{3xy}=\frac{3\cdot xy}{3\cdot xy}=\frac{3}{3}\cdot\frac{xy}{xy}=1\cdot\frac{xy}{xy}=\frac{xy}{xy}= \text{etc.}$$
The difficulty with the expression that you provided is that we have a ratio of two sums, not two products, so we need to factor the numerator and denominator by using the "distributive property" [e.g. $ab+ac=a(b+c)$].
$$\frac{x^2y+xy^2}{y^2+\frac{2}{5}xy} = \frac{y(x^2+xy)}{y(y+\frac{2}{5}x)} = \frac{y}{y}\cdot\frac{x^2+xy}{y+\frac{2}{5}x} = 1\cdot\frac{x^2+xy}{y+\frac{2}{5}x} = \frac{x^2+xy}{y+\frac{2}{5}x}$$
We just "canceled" out a $y$, but it's just as easy to cancel out $\frac{1}{5}$ from the resultant expression.
$$\begin{align}
\frac{x^2+xy}{y+\frac{2}{5}x}&=\frac{\frac{5}{5}x^2+\frac{5}{5}xy}{\frac{5}{5}y+\frac{2}{5}x} = \frac{\frac{5}{5}\cdot\frac{x^2}{1}+\frac{5}{5}\cdot\frac{xy}{1}}{\frac{5}{5}\cdot\frac{y}{1}+\frac{2}{5}\cdot\frac{x}{1}}= \frac{\frac{5x^2}{5\cdot 1}+\frac{5xy}{5\cdot 1}}{\frac{5y}{5\cdot 1}+\frac{2x}{5\cdot 1}} = \frac{\frac{1\cdot 5x^2}{5\cdot 1}+\frac{1\cdot 5xy}{5\cdot 1}}{\frac{1\cdot 5y}{5\cdot 1}+\frac{1\cdot 2x}{5\cdot 1}}= \frac{\frac{1}{5}\cdot \frac{5x^2}{1}+\frac{1}{5}\cdot\frac{5xy}{1}}{\frac{1}{5}\cdot\frac{5y}{1}+\frac{1}{5}\cdot\frac{2x}{1}}\\
&=  \frac{\frac{1}{5}\cdot 5x^2+\frac{1}{5}\cdot5xy}{\frac{1}{5}\cdot5y+\frac{1}{5}\cdot2x} = \frac{\frac{1}{5}(5x^2+5xy)}{\frac{1}{5}(5y+2x)} = \frac{\frac{1}{5}}{\frac{1}{5}}\cdot\frac{5x^2+5xy}{5y+2x} = 1\cdot\frac{5x^2+5xy}{5y+2x}\\
&=\frac{5x^2+5xy}{5y+2x} = \frac{5(x^2+xy)}{5y+2x}
\end{align}$$
Okay, well maybe "easy" wasn't exactly the right word to use. Typically though, the short version would look more like this
$$\frac{x^2+xy}{y+\frac{2}{5}x}=\frac{\frac{5}{5}x^2+\frac{5}{5}xy}{\frac{5}{5}y+\frac{2}{5}x}=\frac{\frac{1}{5}(5x^2+5xy)}{\frac{1}{5}(5y+2x)} = \frac{5x^2+5xy}{5y+2x} = \frac{5(x^2+xy)}{5y+2x}$$
And lastly, another way that you could have canceled out the $\frac{1}{5}$ is just by multiplying the entire expression by  $\frac{5}{5}$
$$\frac{x^2+xy}{y+\frac{2}{5}x} = 1\cdot \frac{x^2+xy}{y+\frac{2}{5}x} = \frac{5}{5}\cdot \frac{x^2+xy}{y+\frac{2}{5}x}= \dots$$
which, I'll leave up to you as an exercise to complete.
And, remember that it's okay to use "tricks" to speed things along, but you need to understand how the tricks work before using them.


PyOpenGL not drawing big VAO

Question: I want to render a large scene made up of many cubes. My first take on this was to create a single cube VBO, and then draw it multiple times using a uniform model matrix to translate it. This was slow, as I was calling glDrawArrays many times per frame.
So I decided to instead use a single, giant VBO with every single cube vertex and an additional translation vector. Basically, I took my old generic cube VBO plus the translation vector, and appended that list to my VBO's list for every cube that I want to draw. I then bind a VAO and draw it. I also changed my vertex shader so that it accepts that translation vector as a vertex attribute, and I generate a model matrix inside the shader.
Now, this doesn't return any errors, which is great, but it doesn't actually draw anything, which is not great, even though the process is fairly similar to what I was doing before.
Here's some code:

Whopper VBO creator:
class render:
    def __init__(self, coords_list):

        self.render_list = []
        for i in coords_list:
            self.render_list.append([
                # Cube model       Texture     Translation
                0.0,  0.0,  0.0,  1.0, 1.0, i[0], i[1], i[2],
                1.0,  0.0,  0.0,  0.0, 1.0, i[0], i[1], i[2],
                1.0,  1.0,  0.0,  0.0, 0.0, i[0], i[1], i[2],
                1.0,  1.0,  0.0,  0.0, 0.0, i[0], i[1], i[2],
                0.0,  1.0,  0.0,  1.0, 0.0, i[0], i[1], i[2],
                0.0,  0.0,  0.0,  1.0, 1.0, i[0], i[1], i[2],

                0.0,  0.0,  1.0,  1.0, 1.0, i[0], i[1], i[2],
                1.0,  0.0,  1.0,  0.0, 1.0, i[0], i[1], i[2],
                1.0,  1.0,  1.0,  0.0, 0.0, i[0], i[1], i[2],
                1.0,  1.0,  1.0,  0.0, 0.0, i[0], i[1], i[2],
                0.0,  1.0,  1.0,  1.0, 0.0, i[0], i[1], i[2],
                0.0,  0.0,  1.0,  1.0, 1.0, i[0], i[1], i[2],

                0.0,  1.0,  1.0,  1.0, 0.0, i[0], i[1], i[2],
                0.0,  1.0,  0.0,  0.0, 0.0, i[0], i[1], i[2],
                0.0,  0.0,  0.0,  0.0, 1.0, i[0], i[1], i[2],
                0.0,  0.0,  0.0,  0.0, 1.0, i[0], i[1], i[2],
                0.0,  0.0,  1.0,  1.0, 1.0, i[0], i[1], i[2],
                0.0,  1.0,  1.0,  1.0, 0.0, i[0], i[1], i[2],

                1.0,  1.0,  1.0,  1.0, 0.0, i[0], i[1], i[2],
                1.0,  1.0,  0.0,  0.0, 0.0, i[0], i[1], i[2],
                1.0,  0.0,  0.0,  0.0, 1.0, i[0], i[1], i[2],
                1.0,  0.0,  0.0,  0.0, 1.0, i[0], i[1], i[2],
                1.0,  0.0,  1.0,  1.0, 1.0, i[0], i[1], i[2],
                1.0,  1.0,  1.0,  1.0, 0.0, i[0], i[1], i[2],

                0.0,  0.0,  0.0,  0.0, 1.0, i[0], i[1], i[2],
                1.0,  0.0,  0.0,  1.0, 1.0, i[0], i[1], i[2],
                1.0,  0.0,  1.0,  1.0, 0.0, i[0], i[1], i[2],
                1.0,  0.0,  1.0,  1.0, 0.0, i[0], i[1], i[2],
                0.0,  0.0,  1.0,  0.0, 0.0, i[0], i[1], i[2],
                0.0,  0.0,  0.0,  0.0, 1.0, i[0], i[1], i[2],

                0.0,  1.0,  0.0,  0.0, 1.0, i[0], i[1], i[2],
                1.0,  1.0,  0.0,  1.0, 1.0, i[0], i[1], i[2],
                1.0,  1.0,  1.0,  1.0, 0.0, i[0], i[1], i[2],
                1.0,  1.0,  1.0,  1.0, 0.0, i[0], i[1], i[2],
                0.0,  1.0,  1.0,  0.0, 0.0, i[0], i[1], i[2],
                0.0,  1.0,  0.0,  0.0, 1.0, i[0], i[1], i[2],
            ])
            print('Cube added!')

    def create_buffers(self):
        render_vbo, self.render_vao = glGenBuffers(1), glGenVertexArrays(1)
        glBindVertexArray(self.render_vao)
        glBindBuffer(GL_ARRAY_BUFFER, render_vbo)
        glBufferData(GL_ARRAY_BUFFER, np.array(self.render_list), GL_STATIC_DRAW)

        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(0))
        glEnableVertexAttribArray(0)
        glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(12))
        glEnableVertexAttribArray(1)
        glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(20))
        glEnableVertexAttribArray(2)

    def draw_buffer(self, program, texture):
        program.use()
        glBindTexture(GL_TEXTURE_2D, texture)
        glBindVertexArray(self.render_vao)
        glDrawArrays(GL_TRIANGLES, 0, int(len(self.render_list)/8))

Initialization and render loop:
def main():

    global delta_time, last_frame

    test_chunk = chunk.chunk((0,0,0)) #Creates a 16x16x16 cube of cubes
    test_chunk.fill_layers(0, 16, 1)  #Works fine

    window = utilities.window()
    camera.setup_window(window)
    glEnable(GL_DEPTH_TEST)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    shader_program = utilities.shader(vertex_source_3d, fragment_source_3d, '330')
    shader_program.compile()

    #Check which cubes are exposed and should be rendered
    #Works fine
    exposed_list = [i for i, blocktype in np.ndenumerate(test_chunk.data) if test_chunk.return_if_exposed(i) == True and blocktype != 0]

    shader_program.use()
    shader_program.set_int('texture0', 0)

    camera_direction = glm.vec3()
    yaw = -90.0
    second_counter = 0
    frame_counter = 0

    render = cube.render(exposed_list)
    render.create_buffers()

    while not window.check_if_closed():

        current_frame = glfw.get_time()
        delta_time = current_frame - last_frame
        last_frame = current_frame
        second_counter += delta_time
        frame_counter += 1

        window.refresh(0)

        camera.process_input(window, delta_time)
        camera.testing_commands(window)

        glActiveTexture(GL_TEXTURE0)

        shader_program.use()

        pos, looking, up = camera.return_vectors()
        view = glm.lookAt(pos, looking, up)
        projection = glm.perspective(glm.radians(45), window.size[0]/window.size[1], 0.1, 100)
        shader_program.set_mat4('view', glm.value_ptr(view))
        shader_program.set_mat4('projection', glm.value_ptr(projection))

        render.draw_buffer(shader_program, cobble_tex_ID)

        glBindVertexArray(0)

        if second_counter >= 1:
            print(frame_counter)
            second_counter, frame_counter = 0, 0

        window.refresh(1)

    window.close()

if __name__ == '__main__':
    main()

Vertex shader:
#version %s core

layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;
layout (location = 2) in vec3 cube_coord;

out vec2 TexCoord;

uniform mat4 view;
uniform mat4 projection;

mat4 model = mat4(1.0);

void main() {
    model[0].w = cube_coord.x;
    model[1].w = cube_coord.y;
    model[2].w = cube_coord.z;
    gl_Position = projection * view * model * vec4(aPos, 1.0);
    TexCoord = aTexCoord;
}

Fragment shader:
version %s core

out vec4 FragColor;
in vec2 TexCoord;

uniform sampler2D texture0;

void main()
{
    FragColor = texture(texture0, TexCoord);
}

Answer: The assignment of the translation to the model matrix is wrong. A glsl matrix is stored in column major order. The translation is the 4th column. A typical model matrix looks as follows:
mat4 m44 = mat4(
    vec4( Xx, Xy, Xz, 0.0),
    vec4( Yx, Xy, Yz, 0.0),
    vec4( Zx  Zy  Zz, 0.0),
    vec4( Tx, Ty, Tz, 1.0) );

You have to change the model matrix initialization:
mat4 model = mat4(1.0);

void main() {
    model[3] = vec4(cube_coord.xyz, 1.0);

    // [...]
}

Further more, you have to specify the data type for the numpy.array (numpy.float32):
glBufferData(GL_ARRAY_BUFFER, np.array(self.render_list), GL_STATIC_DRAW)
glBufferData(GL_ARRAY_BUFFER, np.array(self.render_list, np.float32), GL_STATIC_DRAW)

The vertex array is 2 dimensional, thus len(self.render_list)/8 is not the number of vertices:
glDrawArrays(GL_TRIANGLES, 0, int(len(self.render_list)/8))
no_of_verices = len(self.render_list) * 36
glDrawArrays(GL_TRIANGLES, 0, no_of_verices)

respectively
no_of_verices = len(self.render_list) * len(self.render_list[0]) // 8
glDrawArrays(GL_TRIANGLES, 0, no_of_verices)

Comment: That does draw something, but the shape is completely broken and the textures don't get applied, instead there are just random stripes of color from the original texture on some triangles. Additionally, things only get drawn starting from some number of cube coordinates.
Comment: @Parashoo I've extended the answer.

PyOpenGL not drawing big VAO


Adding JQuery Datepicker Dynamically to Form Elements

Question: I am working on a form with dynamically added inputs, by using the cloned method.  Each input will need a datepicker.
The name of each input will be distinct for output.
I am using the Jquery UI Datepicker for this.
The problem that occurs (the message in the console) is "$cloned.find(...).attr(...) is undefined"
I went to another post jQuery DatePicker not working on newly added row
and tried removing the hasDatepicker class (included in code below), but the problem persists.
Thanks for any input or resources.
The code is below:

 Class Year*
 <input type="text" id="datepicker" name="ClassYear_1" class="usedatepicker" value="" tabindex="4" />

  <button type="button" id="add-btn" name="add-btn">Add Class Year</button>

JS Code:
 function clone2(){
 var $cloned = $('table tr:last').clone();
 $cloned.removeClass('hasDatepicker').datepicker();
 //console.log($(this));
 //alert($(this).attr('name'));
 var oldIndex = $cloned.find('input').attr('name').match(/\d+/);
 var newIndex = parseInt(oldIndex,10)+1;
 $cloned.find('input').each(function(){
 var newName = $(this).attr('name').replace(oldIndex, newIndex);
 $(this).attr('name', newName);
 });
 $cloned.insertAfter('table tr:last');
 }

 $('#add-btn').click( function() {
 clone2();
 });

 //attach datepicker - begin
 $(document).ready(function() {

 $(".usedatepicker").datepicker(); // or
 $(".usedatepicker").datepicker("refresh");

 });

Answer: After cloning / inserting the new table row, you have new elements with .usedatepicker class that have not yet been initialized with datepicker.
I notice you are trying to initialize the new row with datepicker before adding it to the DOM. Two problems. First, you are trying to init datepicker to the entire (new) row and not just to the input field, and second you must do this after injecting the row into the DOM.
Try something like this:
function clone2(){
    var $cloned = $('table tr:last').clone();
    $cloned.removeClass('hasDatepicker').datepicker();
    //console.log($(this));
    //alert($(this).attr('name'));
    var oldIndex = $cloned.find('input').attr('name').match(/\d+/);
    var newIndex = parseInt(oldIndex,10)+1;
    $cloned.find('input').each(function(){
        var newName = $(this).attr('name').replace(oldIndex, newIndex);
        $(this).attr('name', newName);
    });
    $cloned.insertAfter('table tr:last');

    $(".usedatepicker").datepicker();  //<=== NEW
}

Another note:
You have an ID with value datepicker. When the row is cloned, you will have multiple elements with the same ID. A no-no. Change the ID to a class and all will work fine. Note that the only essential difference between a class and an ID is that you cannot use the same ID for more than one element. Simple solution: switch ID to class.
If that is not good enough, perhaps because you need to address each input field directly via a unique ID, do the same thing to the ID attribute that you are already doing to the name attribute.
Comment: Thanks so much for your post.  I have a question, regarding the distinct ids in Jquery Datepicker.  When used such as this (https://jsfiddle.net/buck1115/gj2ohyf3/50/), Jquery Datepicker generates unique ids.  Although of course I can generate them as you stated, I was wondering why the native id generation seems to not work in this case?
Comment: I've used your suggestions here (https://jsfiddle.net/buck1115/hhzL1kw6/26/), although now, I can generate all of the new (cloned) inputs I want, provided non of the input boxes are clicked in.  The top row input box will only fire the datepicker once the second box has been clicked/fired.  Only the top two boxes will fire.  My new code has distinct IDs.  I tried removing the IDs and the ID code, just leaving the class, but that had the same result.
Comment: To amend my last comment - the error message in the console is: `TypeError: $cloned.find(...).attr(...) is undefined`


Azure Logic Apps - Logging for Business Audit

Question: I have built an integration solution between 2 systems.
Azure  Logic App provides logged capability but it is mainly meant for Azure developers.
I have a requirment to maintain logging of my logic app based on some predefined events as mentioned below :-

Pick up newly added files from FTP folder
Unzip
Process the files and merge
Send merge files to Azure functions
.
.
.

Requirement of this logging is for auditors who are non technical people.
We have Azure SQL database in which I can create customised logging tables as we used to do in traditional applications. For this I am thinking of creating a Web UI for auditors to see the logs details.
I just wanted to check
I just wanted to check, is there any other way to achieve the same by leveraging Azure logs and showing them in WebUI.
Looking for better way.
Answer: Although I didn't get any response. However, I would like to share how and what I have implemented this :-
1) Define stages for the entire process -   It defines stages in the Life Cycle of your process. (I have defined Stages as per the actions/steps in my Logic App work flow)
2) After finalizing all the stages, create a master table in Azure database to stages where I also need to store the audit log for each process in AuditLog table.
3) Now in my Logic App, I have using a variable, which maintains StageId,DateTimeStamp for all stages.   eg: Stage1Id,DateTime1;Stage2Id,DateTime2;Stage3Id,DateTime3;
4) In the end of Logic App is making a call to AuditLogStoredProcedure with this variable as parameter to insert values in the  AuditLog table.
<code>***Please note that: -
1)  I have declared one stage as an "Error" which being called up in a similar way for all exceptions.
2)  I am maintaining StagesId with TimeStamps in a variable to avoid multiple calls to the database. For audit log there will be only single call to database from the LogicApp.
***
</code>


What is the best way to maximize gold find in Diablo 3?

Question: What is the best way to maximize your gold find? Some items have extra gold find and if you socket correctly you can get gold find on that too. What is the highest gold find percentage you can get and which items, spells, gems do you need to get that? Are there any classes that change this too?
Comment: I would vote to reopen this if I could... the answer below is a great checklist of things to look for if you're trying to maximize your gold drops. Perhaps you can edit your question a bit so it asks for a canonical list of how to maximize your gold drops, and doesn't just ask what the highest gold find % is?
Answer: As of patch 1.0.4  the maximum gold find is now capped at 300%.  The only exception is Nephalem Valor which can bring the total Gold Find to 375%.
Pre patch information:
According to datamining sites (example) the relevant item affixes are:

Amulet: Prosperous: Chance to Find Gold Increases by 41-50%
Ring/Armor/Offhand: Prosperous: Chance to Find Gold Increases by 21-25%

So, here is a try at the most possible gold find.

Amulet slot: 50%
All other slots except weapon: 11 * 25% = 275% (head, shoulders, torso, wrists, hands, waist, legs, feet, 2x rings, offhand)
Helmet gem slot: 31% (Radiant Star Emerald)
Follower amulet slot: 50% * 20% follower bonus ratio = 10%
Follower ring and offhand slots: 3 * 25% * 20% follower bonus ratio = 15%
Nephalem Valor: 75%
Shrine of Fortune: 25%
Demon Hunter Ferret Companion: 10%

Total: 491%
There may be some legendaries with increased gold find, so more than this may be possible. However this is not at all realistic, because 1) it would take ages to find perfect "Prosperous" items for all these slots, and 2) your gear would likely be decidedly suboptimal for your class if all you sought was Prosperous items.
Overall, to maximize profit, I think you would do better optimizing for your class's DPS stats, and adding in as much gold find and magic find as you can without hurting your kill rate or survivability.
Comment: @MichelAyres Added in the DH skill. Together we will ferret out the truth to this answer.
Comment: Do you know if most of those same values would apply to Magic Find as well? And if not, would you be willing to post a similar answer to the question about [maximizing your Magic Find](http://gaming.stackexchange.com/q/66216/8462)? It's a very nice checklist of things to look for when building a Magic/Gold finding set :)
Comment: Don't forget jewel slots
Comment: @ChrisRasys Thanks, added in the helm gem slot (the only one to add gold find I believe).
Comment: Also, DH has an skill+rune that increase his gold find. If you take that in count.
Comment: Also, don't forget the Valor buff. I think that's 75% assuming you have a full stack of 5.
Comment: @Mr.November Valor buff == [Nephalem Valor buff](http://gaming.stackexchange.com/questions/66122/how-does-the-nephalem-valor-buff-work)?
Comment: @Mr.November Added that in. Checking class skills now.
Comment: @MichelAyres yes
Comment: @Wikwocket \o/ To the best answer and beyond!
Comment: @Rachel The calculations for MF would be similar. I'll work on a list for the other question.
Comment: Shouldn't the follower's ring/offhand bonuses be 3 * 25% * 20% = 15%? Also, the Nephalem Valor post says nothing about gold find being affected, so if your 100% NV bonus is correct, you should also give an answer or comment there. (Only thing stated there is that it gives +75% magic find and +5 boss drops when maxed.)
Comment: @TheodoreMurdock Thanks, I noticed too that as I wrote the MF post, and fixed it. As for NV, [everything](http://us.battle.net/d3/en/forum/topic/4241234476#1) I've [read](http://eu.battle.net/d3/en/forum/topic/4309851977) says it affects gold find as well, including the post I link to.
Comment: @Wikwocket The Nephalem Valor post was finally updated to the correct value of 75%
Comment: Just wanted to make a note about "Overall, to maximize profit, I think you would do better optimizing for your class's DPS stats". There are some spots (The Royal Crypts for example) where on a typical run you will encounter 3 skeletons and find 6-7k gold (on hell with 154% GF. that would be nearly 20k with max GF). So DPS doesn't matter here.
Comment: Actually there is one more way to improve your gold find. There are two rings that together form a set. The rings are called "Screaming chain" and "Band of fallen heroes" and if you have them both they provide a set bonus of +15 gold find and +15 magic find. The rings themselves can have 18 gold find (as they are level 61 rings). So in total you could get +51 gold find on the two rings instead off +40 on two +20 rings which is +11 more in gold find.
Comment: Can we get updated values added to this answer with info from patch 1.0.5, specifically regarding Monster Power.  People will probably ask regarding how MP +MF/GF affects the 300/375 (+25) cap.
Comment: With patch 2.0.1, some of the major sources of gold find have been reworked.  The tooltip still says there is a max of 300%, but Torment difficulties offer a bonus beyond that (I assume they're exempt from the cap, but cannot confirm - but it's silly to give a +550% bonus and then cap you at 300%).  Paragon bonuses have also been reworked and there's a category just for increasing gold find.  Is the Paragon bonus exempt from the cap too?
Answer: I hate to make another answer, but the previous answer is wrong.
Maximum value gold find per slot is presently:
Amulet: 40%
Ring: 20%
2H Sword: 25% (Sultan of the Burning Sands legendary)
Quiver: 20%
Shield: 25%
Other Armor: 25%
So, the 8 'common' armor slots cap at 200%.
With a legendary 2H sword, you can get another 25%.
With any 1H and a cap shield, you can get 25%.
With any ranged and a cap quiver, you can get 20%.
Breakdown
Due to quivers having slightly less, the ferrets available bring it up 10%, which makes a demon hunter with quiver and ferrets cap at 30%; or demon hunter with 1h xbow, ferrets, and shield cap at 35%.
The helmet socket is the only socket that can provide additional find.
A radiant star emerald can provide 31% additional gold find, though most will only use a 25% as it's the highest you can make without getting a dropped recipe.
The most effective follower is either the templar (with cap gold find shield) or the enchantress (with a cap Sultan of the Burning Sands), two rings, and an amulet.. all at cap. The bonus you get is 20% of theirs, with their cap being (25+20+20+40)/5=21%.
For a demon hunter with 2H ranged equipped, the equipment bonus caps at:
200% (armor) + 10% ferrets + 20% quiver + 31% radiant star emerald + 21% follower + 80% jewelery = 362%.
For a demon hunter with 1H xbow and shield equipped, the equipment bonus caps at:
200% (armor) + 10% ferrets + 25% shield + 31% radiant star emerald + 21% follower + 80% jewelery = 367%.
For all other classes, if they have a shield equipped, the bonus caps at:
200% (armor) + 25% shield + 31% radiant star emerald + 21% follower + 80% jewelery = 357%.
For classes who can use a 2H sword and ignore shield, the Sultan build caps at:
200% (armor) + 25% sultan + 31% radiant star emerald + 21% follower + 80% jewelery = 357%.
If you have 5 stacks of NV, it provides 75% more. A fortune shrine adds 25%.
Summary
So maximum possible gold find is a 1h xbow wielding demon hunter with ferrets and a shield, a capped follower, with 5 NV stacks and a fortune shrine, which can net 467%.
If they use a quiver, and thereby allowing a 2H ranged to clear faster, they are limited to 462%
All other classes, if using a shield, or that particular 2H sword, are limited to 457%.
Without a shield or that particular legendary sword, then all other classes cap at 432%.


Datatype Mismatch criteria while comparing two dates from database

Question: In the below comparing two dates and fetching data.But from the form am getting two date correctly and it was showing an error datatype mismatch any one please help me how to resolve this issuse.
Form.vb:
 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        provider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source="
        dataFile = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        connString = provider & dataFile
        myConnection.ConnectionString = connString
        myConnection.Open()
        Dim dt As New DataTable
        Dim ds As New DataSet
        ds.Tables.Add(dt)
        Dim da As New OleDbDataAdapter
        da = New OleDbDataAdapter("Select * from Add_Student Where Fee_Date between '" + DateTimePicker1.Value.ToString() + "' and '" + DateTimePicker2.Value.ToString() + "'", myConnection)
        da.Fill(dt)
        Add_StudentDataGridView.DataSource = dt.DefaultView
        myConnection.Close()
    End Sub

Comment: Use a parametrized query (`"Select * from Add_Student Where Fee_Date between ? and ?"` with two parameters for start and end dates).  Once you have learnt how to do this, you will be protected from SQL injection attacks.
Comment: Try changing `DateTimePicker1.Value.ToString()` to `DateTimePicker1.Value.ToString("yyyy-MM-dd")` and doing the same for the next one. It should provide a format that is more .. interchangeable. Hope it helps
Comment: On a side note - after you sort this out, make sure you parametrize the query - this is very SQL-injection vulnerable.
Comment: still am getting same error Mihai Ovidiu Drăgoi
Comment: jmcilhinney'a answer seems robust.
Answer: If you're using Access then the proper way to format date literals is the same way it's done in VB, i.e.
da = New OleDbDataAdapter("Select * from Add_Student Where Fee_Date between #" + DateTimePicker1.Value.ToString("d/MM/yyyy h:mm:ss tt") + "# and #" + DateTimePicker2.Value.ToString("d/MM/yyyy h:mm:ss tt") + "#", myConnection)

You should remove the time portion if you only want to compare the date.
Using & operators in expressions like that is hard to read though.  Instead, you should use String.Format:
da = New OleDbDataAdapter(String.Format("Select * from Add_Student Where Fee_Date between #{0:d/MM/yyyy h:mm:ss tt}# and #{1:d/MM/yyyy h:mm:ss tt}#",
                                        DateTimePicker1.Value,
                                        DateTimePicker2.Value),
                          myConnection)

or, in recent versions of VB, string interpolation:
da = New OleDbDataAdapter($"Select * from Add_Student Where Fee_Date between #{DateTimePicker1.Value:d/MM/yyyy h:mm:ss tt}# and #{1:d/MM/yyyy h:mm:ss tt}#",
                          myConnection)

Of course, the best option is to not use any type of string concatenation and use parameters instead:
da = New OleDbDataAdapter($"Select * from Add_Student Where Fee_Date between @StartDate and @EndDate",
                          myConnection)

With da.SelectCommand.Parameters
    .AddWithValue("@StartDate", DateTimePicker1.Value)
    .AddWithValue("@EndDate", DateTimePicker2.Value)
End With

Click here for more information on using ADO.NET parameters.
Note: I think that Access supports "h:mm:ss tt" for time but, if not, try "HH:mm:ss".
Comment: If your database column contains only dates and no times then you need to trim the time off your filter values. If you use one of the first three examples then simply omit the time portion of the format string. If you're using parameters then use `DateTimePicker1.Value.Date` to zero the time of the parameter value. If that doesn't fix it then you're going to have to be more specific about what the database contains and what exact code and parameter values you're using. That's probably something for a new question.
Comment: small doubt while comparing two dates are same then nothing displaying
Comment: Thank again got it


Wiring A Switch For A 240v Power Outlet

Question: I want to add power outlets to a side of my garage that currently has none but am struggling to find wiring diagrams for a 240v switch that will be connected to an outlet. Is it as easy as 2 hots connected to the bottom two screws of a double pole switch and then 2 hots out of the top two screws with a ground wire attached? I just haven't had any luck finding anything to confirm this.
My garage functions as both a hobby space and where my kids store their bikes, scooters, etc. I want to wire switches upstream of the outlets so I can keep my tools plugged in and not be concerned about a child messing around and accidentally turning a tool on.
Comment: I take it the circuit breakers for your garage circuits are nowhere near the garage?
Comment: It is that simple, but don't underestimate yours kids willingness to activate more than one switch when they have a case of curiosity. I highly recommend a long and boring explanation of the dangers of each tool. Talk at least 2 minutes past their eyes glazing over.
Comment: Both are required in / for all receptacles, the GFCI protection can be from the panel or a GFCI receptacle that the load terminals feed the rest of the string.
Comment: The circuit breakers are in the same garage. I need outlets on the opposite side of the garage than the power panel. As for kids, my concern is with smaller children that could pull out the  switch on a table saw but not be tall enough to operate switches.
Comment: @Remy -- does the panel in the garage serve the whole house, or just the garage?
Comment: The panel serves the whole house including the garage. @ThreePhaseEel
Comment: Remy Another code mention that we regularly forget here. Tamper resistant receptacles are also required. 2020 NEC 406.12 all 15 & 20 amp 125- and 250v non locking-type receptacles ,,, in following ares shall be listed tamper-resistant. 406.12.1. Dwelling units including detached garages and accessory buildings. Washing state has adopted the 2020 code and unless the receptacle is a twist lock it requires a a tamper-resistant GFCI protected receptacle. Still requires GFCI for twist lock.
Comment: @EdBeal Does every outlet in a 125v string need to be tamper resistance & GFCI or can all be tamper resistant and just one be GFCI?
Answer: A single receptacle has to be full circuit amperage [NEC 210.21(B)(2)], so the 15A (NEMA 6-15) receptacle would be connected to 15A breaker or you need a NEMA 6-20 or a duplex 6-15. Normally a 6-20R is a T-slot and will accept a 6-15P.
Also the 2020 NEC specifies 240v receptacles in garages now require GFCI protection too [210.8(A)(2)].
Comment: I don't believe Washington State requires the GFCI, am I reading this correctly?
008(B) Other than dwelling units – GFCI requirements.
(3) GFCI requirements. GFCI protection for personnel will not be required for:
(a) Three-phase receptacles unless specifically required elsewhere in the NEC; or
(b) Receptacles other than 125-volt, single phase, 15- or 20-ampere used for: recreational vehicle supply
equipment or for attachment of a mobile home supply cord.
Comment: I don't think you are. "008(B) Other Than Dwelling Units" correlates with "NEC 210.8(B) Other Than Dwelling Units".  008(A) modifications for 210.8(A)Dwelling Units only gives modifications to the NEC, if it were a complete replacement for that section then no GFCI's would be required at all.  And even then I think, due to the colon, the modification for non-dwelling unit only applies if used for RV or mobile home connection.
Comment: Remy if you are in Washington state they are on the 2020 code. The 2017 code req all 120v receptacles in garages to provide GFCI protection.  The 2020 code requires all 125v through 250v receptacles to have GFCI protection 210.8.A. And 210.8.A.2. I am a licensed electrician in Oregon and we have a reciprocal license agreement because our states have similar enforcement of the code. You may have a local exception i an not currently working on your side of the Columbia so I haven't checked the exceptions but the 2020 code has been approved and is In use by Washington state. We are trying to help
Comment: @EdBeal Thanks for the help! I really do appreciate it. So a 240v GFCI breaker would be something like this for a Homeline panel: https://www.homedepot.com/p/Square-D-Homeline-20-Amp-2-Pole-GFCI-Circuit-Breaker-Clear-Packaging-HOM220GFIC/204355351
Comment: Yes that breaker would meet code requirements for the 240v GFCI. Thanks on the site are up votes and or accepting an answer the check mark it shows the information was useful or you used it. You can upvote multiple items or answers but only accept 1.
Answer: To switch 240v there are 2 methods.
Cheap method single pole switch break 1 hot that's it. the circuit is still live 120v could be measured to ground but a 240v device will be turned off.
I have seen this used extensively on heating circuits.
I have also found this in older tools like radial arm saws, and table saws that were multi voltage. The down side the tool has 120v potential to ground when off.
Advantage it's cheaper.
Today The more common way is to use a double pole switch and break both hot legs.
This kills all power going to the tool
It cost a bit more.
Is considered safer because no power to the tool but a 240v device doesn't care.
Which method is used.
If you want to use standard snap switches on motors if not motor rated a switch with 2x the current requirement is needed.
For general loads ( other than motors) the switch only needs to be rated for the load.
Comment: I plan on running a 3HP table saw using a 6-15 outlet downstream of the switch. Would a double pole switch rated at 20amps not be correct for this application? I was considering a switch like this one:

https://www.platt.com/platt-electric-supply/Industrial-Switches-20-Amp-Toggle-Switches/Leviton/1222-2W/product.aspx?zpid=34331
Comment: No, it is only 2 hp rated. Try a ms303-ds https://amzn.to/38aMAex 5 hp@ 240v
Comment: Do I have to have a motor rated switch if I am not using it to control the motor? My intent is not to turn the power on and off through the switch but to provide power to the outlet and then turn the table saw on.
Comment: Well by code a 3 Hp motor 240v is 17 amps so it should be at least a 30A unless motor rated for 3hp. The switch you have is only rated for 2 Hp. If you are only using it for a safety not opening and closing under load it might hold up. For circuit ampacity motors require 125% of the fla so you need a 20 amp circuit and receptacle also.
Comment: From the manual: "The Professional Cabinet Saw model number PCS31230 comes with an AC motor that is rated at 3 hp and operates at 60 Hz. It can be used with single phase 208-240V power. The motor draws 13 amps at 208-240V power." The saw uses as 6-15 plug so that means I have to use a 15amp circuit breaker to match it, correct? And I should be able to use this switch in case it was used unintentionally to start the saw:  https://www.platt.com/platt-electric-supply/Manual-Starters-Switches-Toggle-Type/Leviton/MS302-DS/product.aspx?zpid=214415
Comment: @NoSparksPlease The MS303-DS you referred to is non-grounded. Is it legal to use them when running new circuits (not replacing an existing component).
Comment: It needs to be mounted in a metal junction box to comply with grounding requirements in 404.9(B)(1).
Comment: Rely code requires the book value to be used 430.6.A1. The nameplate is only used for separate overloads. The disconnect if motor rated can be 115%430.110.A exception 1 the wiring 125% the overcurrent protection device up to 250% for an inverse time breaker (home panels) per table 430.52 . The 2x for a snap switch and 20 amps is still not enough with the nameplate 430.109.C.1. Code value for a 3 Hp at 208=18.7, 240=17 (table 430.248)  even the 80% rule a 20 amp switch it two small motor circuits require 125% of there book value. We are not messing with you but providing code req to do it right
Comment: @nosparksplease, I had never known of a metal box requirement so I checked your reference. You missed the OR to a non metallic box with integral means for connecting to a equipment grounding conductor. Most all snap switches have a ground screw and metal strap that the cover attaches to to fulfill this requirement, plastic boxes are allowed. No change in the 2020 code for 404.9.B.1
Comment: @Remy if it's in a metal junction box (and most of the time, an industrial switch like this *would be*), then **the switch grounds through its monting screws**.  (the ground wires are required to be attached to the metal box FIRST *anyway*, so this makes grounding easy).  Receptacles can't do that trick *unless* they're labeled "self-grounding".
Comment: @EdBeal I will be using metal boxes mounted to the surface of the sheetrock along with 3/4" eat conduit. If I did a 6-20 outlet for the table saw and a 20 amp breaker with 10 gauge wire, the Leviton MS302-DS switch should work right? 30 amps and rated for motors. https://www.platt.com/platt-electric-supply/Manual-Starters-Switches-Toggle-Type/Leviton/MS302-DS/product.aspx?zpid=214415
Comment: That switch will hold up, having the #10 wiring will be a good idea if the 20 amp breaker won't hold and you have to increase in size then you would need to upsize to a 30 amp receptacle & breaker to be fully code compliant but for a load of under 16 amps 240v this would be approved.
Comment: @EdBeal Did you miss that the ms303 switches have no ground terminal? I can't see any way to satisfy condition (2), leaving option (1), a metal box the only solution
Comment: @nosparksplease, did you miss the op is using a metal box?
Answer: While your approach with switched receptacles works...
While your approach using an external switch to control the receptacles works, and can be made fairly robust using a key-operated lightswitch like what's shown below:

, it does have the downside that you need to give each circuit its own switch, which doesn't scale as you add circuits.
The alternative: feeder and lockoff
A more scalable alternative to the individual keyed switches is to reroute the shop circuits to a main lug subpanel in the garage, then put a breaker lockoff device and a suitable padlock on the feeder breaker for the shop.  That way, you have only one thing you need to unlock and lock to turn the shop on and off.
Similarly, you could use a main breaker in the subpanel with a locked on the subpanel's door.  You could even implement it using a separate lockable switch or breaker in its own box; this would allow you to use a breaker (such as an ABB/GE S800U or Schneider Electric/Square-D Multi9 C60BP) that can be fitted with both a lockoff and an undervoltage release coil, which allows you to implement a shop-wide E-stop function for a price that's not completely eye-watering.
Comment: I highly recommend your final suggestion.  I did something similar in my recently built workshop.  I have a subpanel with a main breaker and locking cover that feeds all the larger tools.  I can lock them all down by shutting off the main breaker and locking the panel door.

Wiring A Switch For A 240v Power Outlet


Closing a PopupWindow with the back button?

Question: I've got a popupWindow that I'm using to display google maps but once it's open I can't seem to close it, I'm trying to set the back button to close it but can't call the onBackButtonClick override as I'm inside a fragment. Doesn't seem to do anything though
   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_go, container, false);
    mRouteBtn = (Button) rootView.findViewById(R.id.routeBtn);

    mRouteBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            View popupView = getActivity().getLayoutInflater().inflate(R.layout.fragment_map, null);

            mPopupWindow = new PopupWindow(popupView,
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            // If the PopupWindow should be focusable
            mPopupWindow.setFocusable(true);
            mPopupWindow.showAtLocation(getActivity().findViewById(R.id.routeBtn), Gravity.CENTER, 0, 0);
            mPopupWindow.update(0, 0, 800, 800); //don't hardcode

Back button code part:
            mPopupWindow.getContentView().setOnKeyListener( new View.OnKeyListener(){
                @Override
                public boolean onKey( View v, int keyCode, KeyEvent event ){
                    if( keyCode == KeyEvent.KEYCODE_BACK ){
                        mPopupWindow.dismiss();
                        return true;
                    }
                    return false;
                }
            } );
        }
    });

Alright sorted, after following Deepak Singh's advice I got it working although when I reopened it I had issues with crashing due to trying to recreate a view that still exists. here's my working code for future reference:
FIXED VERSION:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_go, container, false);

    mRouteBtn = (Button) rootView.findViewById(R.id.routeBtn);

    mRouteBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (mPopupView != null) {
                ViewGroup parent = (ViewGroup) mPopupView.getParent();
                if (parent != null)
                    parent.removeView(mPopupView);
            }
            try {
                mPopupView = getActivity().getLayoutInflater().inflate(R.layout.fragment_map, null);
            } catch (InflateException e) {
                /* map is already there, just return view as it is */
            }
            mPopupWindow = new PopupWindow(mPopupView,
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.showAtLocation(getActivity().findViewById(R.id.routeBtn), Gravity.CENTER, 0, 0);
            mPopupWindow.update(0, 0, 800, 800); //don't hardcode

            mPopupView.findViewById(R.id.doneBtn).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPopupWindow.dismiss();
                }
            });
        }
    });

Comment: can you post back button code ?
Comment: As you are inside a fragment, I would suggest adding a DialogFragment using getChildFragmentManager() instead.
Comment: have you try to use : setOutsideTouchable(true)
Answer: Add a button on your pop up window layout and find the id of button using popupView.findviewbyid(id),then set clicklisener on this button and call  mPopupWindow.dismiss();.
Also you can try this:
 popupView.setOutsideTouchable(true);
 popupView.setFocusable(true);

Comment: Yeah .This logic is simple
Comment: That's working great however now when I reopen the popup it crashes with Duplicate id.
Answer: add to your code popupWindow.setOutsideTouchable(true);
Comment: Tried that, didn't seem to do anything.
Comment: If the popup is showing, calling this method will take effect only the next time the popup is shown or through a manual call to one of the update() methods.
Answer: According to this answer you need to set a background drawable to the popup window.
I tested it out and you don't even need to handle the OnKeyListener by yourself.
This should be enough to make 'back button' work:
popupWindow.setBackgroundDrawable(new ColorDrawable());
popupWindow.setFocusable(true);


Dynamically change content scraped with PHP

Question: I am developing a website which collates information from several weather/snow information sites for mountain walking in Scotland. I currently have a page which uses an iFrame to fetch and show an avalanche report map for a region and a series of links which call a javascript function to change the map shown for different locations.
I am now adding in a scraping method in php to pull the text report from a seperate page on the original site and add it with the map. I've got that function working ok but what I am struggling with is how to change this text content when the user chooses a location by clicking on the link.
Anyone have any suggestions on how to achieve this? Preferably I want to do it without refreshing the page (should I be using something like Ajax for the whole thing?). Here are the 2 scripts I have at the moment:
PHP Scraping script:
<?php
    $data = file_get_contents('http://www.sais.gov.uk/page_Creag%20Meagaidh.asp');
    $regex = '/Observed Weather Influences........(.+?)\W\Wp\W/';
    $preg_match($regex,$data,$match);
    echo $match[1];
?>

Javascript map change:

Comment: @Daniel Lisik please don't edit the code itself in questions. You may accidentally cause confusion.
Answer: jQuery's not required but will simplify the process for you (doesn't sound like you're that confident) :
Set up a container div in your HTML. And add a script like so:
$('.dropdown-or-whatever').change(function(){
    $.ajax({
        url: 'http://www.domain.com/the_location/_of_your_script.php',
        success: function(result){
            $("#your-container-div").html(result);
        }
    });
});

The change() function on the first line is assuming you're using a dropdown (select) element, which might not be correct.
You'll also (probably) want to pass your PHP script different parameters based on which dropdown choice is selected and scrape a different page depending what that's set to. Parameters can be added at the end of the URL string like so:
?place=scotland

Any questions, just ask.
Edit: got bored and basically did it for you. http://pastebin.com/np7GVh3f Take a look at the code and hopefully you'll learn something :)
Comment: If you dont cast that script from http://www.domain.com/, then it is crossdomain request and it will be not possible.
Comment: It won't be a crossdomain request because it will be on his server.
Comment: Sorry I didn't reply earlier - important phone calls always come at bad times :D Thanks very much for this. I'll look over it and see if I can work it out. You're right I am not confident with this - I've never really done more than basic HTML5/CSS/PHP websites before so this is new for me. I'm always ready to learn new stuff though (kinda the whole point of this web project) so thanks very much!


error while using array of pointers instead of 2 dimensional array

Question: the following code crashes if i give array of pointer here is there any other way to accept value through array of pointers or did i do somethong wrong here
the run this program after compiling you should type
objectname -numberoflines
  //program to print first n lines of string using command  line arguement
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
int less(int x,int y);`enter code here`
int main(int argc,char* argv[])
 {
     int i,j,n,num;
    char *lines[100];/*if I use two dimensional array here the code compiles
    char nu[6];

 // the whole for loop is for checking error in n
    for(i=1,n=strlen(argv[1]);i<n;i++)
    {
            if(argv[1][i]=='.')
            {
                    printf("your input was not correct \n");
                    return 0;
            }
            if(argv[1][i]=='-')
            {
                    printf("your input was not correct \n");
                    return 0;
            }
            if(isalpha(argv[1][i])!=0)
            {
                printf("your input was not correct indeed");
                return 0;
            }
    }
    printf("\t\t application to print number of last n lines \n\n\n");
    printf("enter the number of lines\n");
    scanf("%d",&n);
    printf("enter your lines \n");
    for(j=0;(n<100)&&(j<=n);j++)
    {
            gets(lines[j]);
    }
    strcpy(nu,argv[1]);
    nu[0]=' ';
    num=atoi(nu);
    num=(less(num,n));
    for(i=0;i<=num;i++)
    {
            printf("%s",lines[i]);
    }
    return 0;
}
int less(int x,int y)
{
    int z;
    return (z=(x>y?y,printf("your input lines are less\n"):x));
}

Answer: The main problem is that when you write
char *lines[100];

You create an array of 100 char* pointers. These pointers have no memory allocated for them and they point to a random location. Writing to that location(using gets in your program) invokes Undefined Behavior.
To fix it, allocate memory for each pointer using
for(i=0 ; i<100 ; i++)
    lines[i]=malloc(AMOUNT_OF_BYTES_TO_ALLOCATE);

And later, after the use is over, free the allocated memory using
for(i=0 ; i<100 ; i++)
    free(lines[i]);

The reason that it worked when you used a two dimensional array is that you create an array of array of char for which memory is automatically allocated in the stack.


How can I switch between two background-colors using js setinterval()

Question: How to Set two background-color in the javascript by setInterval()?
    let x = document.body;
    x.style.backgroundColor = x.style.backgroundColor === "yellow" ? "pink": "yellow";

Answer: Try this:

var i = 0;
function change() {
  var doc = document.getElementById("background");
  var color = ["black", "blue", "brown", "green"];
  doc.style.backgroundColor = color[i];
  i = (i + 1) % color.length;
}
setInterval(change, 1000);

&nbsp


How to pass multiple variables in python flask to mysqldb?

Question: I have tried to apply the advice in this question but I still don't seem to get the code to work. I am trying to pass two variables
How to pass variables in python flask to mysqldb?
cur = mysql.connection.cursor()
for row in jdict:
  headline = row['title']
  url = row['url']
  cur.execute("INSERT INTO headlinetitles (Title, Url) VALUES ('%s','%s');",str(headline),str(url))
mysql.connection.commit()

I get the error TypeError: execute() takes from 2 to 3 positional arguments but 4 were given
Answer: I found the solution. Maybe this will help someone.
cur = mysql.connection.cursor()
for row in jdict:
    headline = row['title']
    url = row['url']
    sqldata = ("INSERT INTO headlinetitles (Title, Url) VALUES ('%s','%s');",str(headline),str(url))
    cur.execute = (sqldata)
mysql.connection.commit()


Why do two Ubuntu systems in the same network behave differently in DNS resolution?

Question: EDIT (tl;dr)
I seem to have identified part of the problem here, as at least the differences in /etc/resolv.conf and related files are gone.
But I still cannot connect via WiFi, so other difference probably persist.
I mean to identify these, and act upon them.

I intentionally selected the same title as this OP.
I have two Ubuntu systems, server1 and server2, very similar in all respects.
Both are connected to the same router, via WiFi.
I worked by comparing the two systems to help tracking the problem.
In server2, I just started having DNS name resolution problems. I was connected to a VPN, and the server was rebooted, so I guess this PostScriptum may describe the case.
server2 did not have resolvconf and  I installed it as an outcome.
At that time /etc/resolv.conf started pointing at /run/resolvconf/resolv.conf (note the modification date below), instead of /run/systemd/resolve/stub-resolv.conf.
To do that, I had to manually add nameserver 22.214.171.124 at the top in /etc/resolv.conf, plug a wired internet connection, and I could immediately sudo apt update, etc.
Note:
As of now, the problem with file permissions quoted in the link above is not present. If it shows up next time I connect to/disconnect from a VPN, I will deal with it.
I am listing below: 1) what is different in server1 and server2,
2) what is the same in both (with any replacing the server name),
and 3) what is almost the same (with irrelevant differences, in my understanding).
Why DIFFERENCE #3 below? (nameserver ::1).

How to fix server2, if possible, by leaving it with the same configuration as server1?
I could try modifying /etc/resolvconf/resolv.conf.d/tail in server2, but since that file is empty in server1 this action would possibly mask other problems, even if successful.
I guess if I could only have DIFFERENCES #1-4 below fixed, that will solve the problem.
But all 4 files are quoted as dynamically created.
I could not locate who is/was responsible for "creating" the differences, and how to fix that.
Different
dig:
[server1]$ dig google.com

; <<>> DiG 9.16.1-Ubuntu <<>> google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 64202
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;google.com.            IN  A

;; ANSWER SECTION:
google.com.     94  IN  A   18.104.22.168

;; Query time: 36 msec
;; SERVER: 127.0.0.53#53(127.0.0.53)
;; WHEN: mar ago 10 03:44:51 -03 2021
;; MSG SIZE  rcvd: 55

vs.
[server2]$ dig google.com

; <<>> DiG 9.16.1-Ubuntu <<>> google.com
;; global options: +cmd
;; connection timed out; no servers could be reached

/etc/resolv.conf and related files:
[server1]$ cat /etc/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
# 127.0.0.53 is the systemd-resolved stub resolver.
# run "systemd-resolve --status" to see details about the actual nameservers.

nameserver 127.0.0.53
search fibertel.com.ar                                     <--- DIFFERENCE #1

[server1]$ cat /run/systemd/resolve/stub-resolv.conf
# This file is managed by man:systemd-resolved(8). Do not edit.
#
# This is a dynamic resolv.conf file for connecting local clients to the
# internal DNS stub resolver of systemd-resolved. This file lists all
# configured search domains.
#
# Run "resolvectl status" to see details about the uplink DNS servers
# currently in use.
#
# Third party programs must not access this file directly, but only through the
# symlink at /etc/resolv.conf. To manage man:resolv.conf(5) in a different way,
# replace this symlink by a static file or a different symlink.
#
# See man:systemd-resolved.service(8) for details about the supported modes of
# operation for /etc/resolv.conf.

nameserver 127.0.0.53
options edns0 trust-ad
search fibertel.com.ar                                     <--- DIFFERENCE #2

[server1]$ cat /run/systemd/resolve/resolv.conf
# This file is managed by man:systemd-resolved(8). Do not edit.
#
# This is a dynamic resolv.conf file for connecting local clients directly to
# all known uplink DNS servers. This file lists all configured search domains.
#
# Third party programs must not access this file directly, but only through the
# symlink at /etc/resolv.conf. To manage man:resolv.conf(5) in a different way,
# replace this symlink by a static file or a different symlink.
#
# See man:systemd-resolved.service(8) for details about the supported modes of
# operation for /etc/resolv.conf.

nameserver 192.168.0.1                                     <--- DIFFERENCE #3
search fibertel.com.ar                                     <--- DIFFERENCE #3

[server1]$ cat /run/resolvconf/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
# 127.0.0.53 is the systemd-resolved stub resolver.
# run "systemd-resolve --status" to see details about the actual nameservers.

nameserver 127.0.0.53
search fibertel.com.ar                                     <--- DIFFERENCE #4

[server1]$ ll /etc/resolv.conf
lrwxrwxrwx 1 root root 29 feb  1  2021 /etc/resolv.conf -> ../run/resolvconf/resolv.conf
[server1]$ ll /run/resolvconf/resolv.conf
-rw-r--r-- 1 root root 327 ago  9 20:59 /run/resolvconf/resolv.conf

vs.
[server2]$ cat /etc/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
# 127.0.0.53 is the systemd-resolved stub resolver.
# run "systemd-resolve --status" to see details about the actual nameservers.

nameserver 127.0.0.53

[server2]$ cat /run/systemd/resolve/stub-resolv.conf
# This file is managed by man:systemd-resolved(8). Do not edit.
#
# This is a dynamic resolv.conf file for connecting local clients to the
# internal DNS stub resolver of systemd-resolved. This file lists all
# configured search domains.
#
# Run "resolvectl status" to see details about the uplink DNS servers
# currently in use.
#
# Third party programs must not access this file directly, but only through the
# symlink at /etc/resolv.conf. To manage man:resolv.conf(5) in a different way,
# replace this symlink by a static file or a different symlink.
#
# See man:systemd-resolved.service(8) for details about the supported modes of
# operation for /etc/resolv.conf.

nameserver 127.0.0.53
options edns0 trust-ad

[server2]$ cat /run/systemd/resolve/resolv.conf
# This file is managed by man:systemd-resolved(8). Do not edit.
#
# This is a dynamic resolv.conf file for connecting local clients directly to
# all known uplink DNS servers. This file lists all configured search domains.
#
# Third party programs must not access this file directly, but only through the
# symlink at /etc/resolv.conf. To manage man:resolv.conf(5) in a different way,
# replace this symlink by a static file or a different symlink.
#
# See man:systemd-resolved.service(8) for details about the supported modes of
# operation for /etc/resolv.conf.

nameserver ::1                                     <--- DIFFERENCE #3

[server2]$ cat /run/resolvconf/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
# 127.0.0.53 is the systemd-resolved stub resolver.
# run "systemd-resolve --status" to see details about the actual nameservers.

nameserver 127.0.0.53

[server2]$ ll /etc/resolv.conf
lrwxrwxrwx 1 root root 29 ago  9 22:38 /etc/resolv.conf -> ../run/resolvconf/resolv.conf
[server2]$ ll /run/resolvconf/resolv.conf
-rw-r--r-- 1 root root 304 ago 10 03:13 /run/resolvconf/resolv.conf

Same
[any]$ uname -a
Linux <serverN> 5.11.0-25-generic #27~20.04.1-Ubuntu SMP Tue Jul 13 17:41:23 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

[any]$ dpkg -l | grep resolvconf
ii  resolvconf                                    1.82                                all          name server information handler

[any]$ cat /etc/netplan/01-network-manager-all.yaml
# Let NetworkManager manage all devices on this system
network:
  version: 2
  renderer: NetworkManager

[any]$ cat /etc/NetworkManager/NetworkManager.conf
[main]
plugins=ifupdown,keyfile

[ifupdown]
managed=false

[device]
wifi.scan-rand-mac-address=no

[any]$ cat /etc/hosts
127.0.0.1   localhost
127.0.1.1   <serverN>

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

[any]$ cat /etc/nsswitch.conf
...
[any]$ cat /etc/systemd/networkd.conf
...
[any]$ ss -plnt | grep ':53'
LISTEN   0        4096       127.0.0.53%lo:53            0.0.0.0:*
[any]$ sudo systemctl status resolvconf.service
...
[any]$ /lib/systemd/network/
...

Almost the same
[server1]$ lsb_release -a
LSB Version:    core-11.1.0ubuntu2-noarch:security-11.1.0ubuntu2-noarch
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.2 LTS
Release:    20.04
Codename:   focal

[server2]$ lsb_release -a
LSB Version:    core-11.1.0ubuntu2-noarch:printing-11.1.0ubuntu2-noarch:security-11.1.0ubuntu2-noarch
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.2 LTS
Release:    20.04
Codename:   focal

Related:

DNS set to systemd's 127.0.0.53 - how to change permanently?
Comment: The show very different with regards *patch* level (one still says 20.04.1 meaning it's not received patches from before 4-Feb-2021 at least (https://fridge.ubuntu.com/2021/02/05/ubuntu-20-04-2-lts-released/ though that date is the ISO release date, installed systems upgraded to 20.04.2 before that date).   *Given that difference alone (6 months) no doubt a load of differences exist between them you're ignoring*...
Comment: @guiverc - I agree that may represent significant differences (*overall*) and can try updating. But do you think that has anything to do with the two questions (in boldface)?
Comment: It shows very different systems; either one has been ignored for six months & not updated (so updating it would fix the differences), or more likely - it's been altered in such a way that prevents upgrades from being installed, and is potentially also the cause for the difference and what you're looking for.
Comment: @guiverc - I did the upgrade, but the issue persists. Please see edited OP.
Answer: The file /etc/resolv.conf is intended to be a symbolic link to /run/systemd/resolve/stub-resolv.conf Check:
ls -al /etc/resolv.conf

If it is not, correct it:
sudo rm /etc/resolv.conf
sudo ln -s /run/systemd/resolve/stub-resolv.conf  /etc/resolv.conf

Your netplan yaml file indicates that you are running Network Manager. That is the place to make your changes to DNS nameservers.
Comment: As stated in the OP, I just installed `resolvconf`. "At that time `/etc/resolv.conf` started pointing at `/run/resolvconf/resolv.conf` ..., instead of `/run/systemd/resolve/stub-resolv.conf`." So yes, I have it as a soft link, but different now from what you posted.
As for manually changing DNS nameservers in *Menu* -> *Settings* -> *Wi-Fi* -> ..., why would I need to do that in one system (`server2`), and not in the other (`server1`)?
I will try it anyway.
Comment: I confirm that manually setting the values as you show makes WiFi work. But why would that be needed? How can I avoid that?
It should be possible I guess... `server1` works that way. And `server2` was working that way too up until yesterday.
Comment: Your netplan yaml says, as it should when Network Manager is installed and running, to turn over everything to NM. Therefore, that's where we set the DNS configuration. If that's not what you want, remove NM entirely and amend your netplan yaml accordingly. If that's what you want, please start a new question. I am wondering why NM is installed on a server. If I have given a helpful answer to your question, please accept it: https://askubuntu.com/tour
Comment: So you mean that the *only* place to set DNS configuration when NM is in charge is the config of each WiFi connection? (could you point to which file/s store the modifications introduced via GUI?)
As said, on one hand, that worked for `server2`. OTOH, it does not seem to be "the" place to handle DNS configuration. In `server1` that seems to be set somewhere else, as my WiFi connection has automatic config, which is the easiest to handle, and what I mostly want to have.
So the answer *is* helpful (+1)... I would wait to possibly receive additional answers/info clarifying the point.
Comment: In automatic config, or more properly, DHCP, the access point, usually a wireless router, provides all necessary details; IP address, gateway and DNS nameservers. Find out which with: `systemd-resolve --status | grep 'DNS Servers' -A2` In a manual configuration, that is, you wish to specify either the IP address, DNS nameservers or both, the details will be recorded in: `sudo cat /etc/NetworkManager/system-connections/MYROUTER.nmconnection` where MYROUTER is the name of the access point to which you are connected. Here is a snip from my file: `dns=184.108.40.206;184.108.40.206;`


Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /home/content/30/10933330/html/sales/save_item.php on line 45

Question: I have created a webstore in opencart. I added some extra pages for sellers to register and sell their products in it. When seller add a product it returns :
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /home/content/30/10933330/html/sales/save_item.php on line 45

and the product is not added to the main page.
My code is:
mysql_query("insert into oc_product (model,seller_id,quantity,price,image,status,listing_days) values ('$model','".$_SESSION['seller_id']."','$qnt','$price','data/no_image.jpg','1','$datetime')");
mysql_query("insert into seller_balance (seller_id,amount,remark) values('".$_SESSION['seller_id']."','$amount','$remark')");
$product_id=mysql_query("select product_id from oc_product where seller_id='".$_SESSION['seller_id']."' order by product_id desc");
$product_fetch=mysql_fetch_assoc($product_id);
$product_id_result=$product_fetch['product_id'];
mysql_query("insert into oc_product_description (product_id,language_id,name,description) values ('$product_id_result','1','$name','$description')");
mysql_query("insert into oc_product_to_category (product_id,category_id) values('$product_id_result','$category')");
mysql_query("insert into oc_product_to_store (product_id,store_id) values('$product_id_result','0')");
echo'

Upload Image

<form action="send_hp.php" id="hp_form" method="POST" enctype="multipart/form-data">
    <input type="file" name="h_pic" id="hp_upload" style="color:#000;" required="required" />
    <input type="hidden" name="product_id" id="product_id" value="'.$product_id_result.'"/>
    </form>';

echo'

';

}
?>

pls help
Comment: Which line is "line 45"?
Answer: Firstly check your Query is right
Proper way to do this is
$query = mysql_query('Select * from table_name');

if( $query ) {
while ( $row = mysql_fetch_assoc( $query ) {

  }

} else {
  throw new My_Db_Exception('Database error: ' . mysql_error());
}

Answer: A better idea, is to use mysql_insert_id()
Also might want to look into using prepared statements and MySQLI for your OpenCart, guides exist for this, but beyond the questions scope.
    mysql_query("insert into oc_product (model,seller_id,quantity,price,image,status,listing_days) values ('$model','".$_SESSION['seller_id']."','$qnt','$price','data/no_image.jpg','1','$datetime')");
$product_id_result = mysql_insert_id();
    mysql_query("insert into seller_balance (seller_id,amount,remark) values('".$_SESSION['seller_id']."','$amount','$remark')");

    mysql_query("insert into oc_product_description (product_id,language_id,name,description) values ('$product_id_result','1','$name','$description')");
    mysql_query("insert into oc_product_to_category (product_id,category_id) values('$product_id_result','$category')");
    mysql_query("insert into oc_product_to_store (product_id,store_id) values('$product_id_result','0')");
    echo'

    Upload Image

    <form action="send_hp.php" id="hp_form" method="POST" enctype="multipart/form-data">
        <input type="file" name="h_pic" id="hp_upload" style="color:#000;" required="required" />
        <input type="hidden" name="product_id" id="product_id" value="'.$product_id_result.'"/>
        </form>';

    echo'

';

    }
    ?>