text:
Q: Error 500 after choosing additional payment method (onepage checkout) - magento 1.9.2 I have added additional payment method almost the same as banktransfer, and everything works fine until this payment is checked at checkout. This payment shows up in adminpanel and front end.
Html code in checkout form looks the same for both payment methods.

            <input id="p_method_custom" value="custom" type="radio" name="payment[method]" title="Custom Payment" onclick="payment.switchMethod('custom')" class="radio validation-passed" autocomplete="off">
            Custom Payment

               some text

            <input id="p_method_banktransfer" value="banktransfer" type="radio" name="payment[method]" title="Banktransfer title" onclick="payment.switchMethod('banktransfer')" class="radio validation-passed" autocomplete="off">
            Banktransfer title

some text

Unfortunately after clicking next step, i got 500 error if i choose this custom method. I have found nothing in Apache log. Chrome log looks like this:
headerJSON    :    null
readyState    :    4
request    :    klass
responseJSON    :    null
responseText    :    ""
responseXML    :    null
status    :    500
statusText    :    "Internal Server Error"
transport    :    XMLHttpRequest
__proto__    :    Object
_getHeaderJSON    :    ()
_getResponseJSON    :    ()
constructor    :    klass()
getAllHeaders    :    ()
getAllResponseHeaders    :    ()
getHeader    :    (name)
getResponseHeader    :    (name)
getStatus    :    ()
getStatusText    :    ()
initialize    :    (request)
status    :     0
statusText    :    ""
__proto__    :    Object

Function payment.save() works, but next one makes error.
reloadStep: function(prevStep) {
        var updater = new Ajax.Updater(prevStep + '-progress-opcheckout', this.progressUrl, {
            method:'get',
           onFailure:this.ajaxFailure.bind(this),
            onComplete: function(response){
                this.checkout.resetPreviousSteps();
console.log(response);
            },
            parameters:prevStep ? { prevStep:prevStep } : null
        });
    },

Any idea what could I messed up?
///Bypassed
I've made a custom module for another payment method instead of duplicating method in core files. Now works fine, no problems in JS.
Any way, i'll try to check why the problem occured.


text:
Q: What's the purpose of inverted bombing on this building? Ives and the Protaginist shelter as Red team exchanges fire with the Enemy further up the street.
The Protagonist checks his watch: "5:15, 5:14............"

Protagonist: We're runnin' out of time, let's go!
Ives: If they see us, it's all for nothing.
Protagonist: We need a distraction.

What's the purpose of inverted bombing on this building?

A: The rockets are both fired at the midpoint of the battle (at exactly 5 minutes) - so the undestruction/destruction of the tower is almost certainly a coordinated event between the red and blue teams designed to cause the distraction that was just called for.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Intl.DateTimeFormat 'calendar' and 'numberingSystem' options never work I'm trying to set the calendar and numberingSystem options for an Intl.DateTimeFormat object. When I set them via the locale argument as below it works:

var dateFormat = new Intl.DateTimeFormat('en-US-u-ca-chinese-nu-arab');
var usedOptions = dateFormat.resolvedOptions();

console.log("resolved calendar: " + usedOptions.calendar);
console.log("resolved numbering: " + usedOptions.numberingSystem);

But when I try to set them via options argument as below, it doesn't work. Mozilla MDN specifically mentions that this should work:

But when you try it, it doesn't:

var options = {calendar: 'chinese', numberingSystem: 'arab'};
var dateFormat = new Intl.DateTimeFormat('default', options);
var usedOptions = dateFormat.resolvedOptions();

console.log("resolved calendar: " + usedOptions.calendar);
console.log("resolved numbering: " + usedOptions.numberingSystem);

I have tested this on node.js and Firefox with the same results. Online javascript emulators also give the same result.
I could still set them via the locale string but it's rather ugly. I prefer to use the options argument if possible.

A: I think Mozilla MDN may be wrong about this. If I am reading the ECMA-402 spec for constructing a DateTimeFormat correctly, in step 8 of §13.1.1 the calendar option is considered, but then in step 17 we go to ResolveLocale where in step 9.i.iv of §9.2.7 the calendar option only overrides the default if it is already a possible choice for the calendar in that locale.
That said, I cannot seem to come up with a case where it works as I expect it would from reading the spec, so maybe I am reading it wrong. I would expect that the second line here would return 'japanese', because the Japanese and Gregorian calendars would be valid choices in the Japanese locale:
> new Intl.DateTimeFormat('ja').resolvedOptions().calendar
'gregory'
> new Intl.DateTimeFormat('ja', { calendar: 'japanese' }).resolvedOptions().calendar
'gregory'


text: Q: Compare the effect of centering power series about different points I loosely understand what it means to center a power series about a certain point. If you were to find a sufficiently high degree power series approximation to a function, would that not provide an approximation for all points in the domain? If so, why choose a particular point to center around?


text:
Q: Airflow declare timestamp as a variables but got the different timestamp for each Task Im exporting data from Postgresql to GCS and then GCS to BQ. The DAG looks good. But in the export path Im using the current timestamp like below.
import datetime

date=str(datetime.datetime.now().strftime("%Y-%m-%d-%H-%M"))
year=date.split('-')[0]
month=date.split('-')[1]
day=date.split('-')[2]
hour=date.split('-')[3]
minutes=date.split('-')[4]
export_suffix = year + '/' + month + '/' + day + '/' + hour + '/' + minutes

So the TASK1(export to GCS) exported the data into this path.
gs://bucket/jobs/export_tbl/2020/09/27/07/12/file.csv

But the export process took 2 mins, then the GCS to BQ dag started and its failed. When I checked the log, it is showing GCS URI not found and its looking for the path as
gs://bucket/jobs/export_tbl/2020/09/27/07/14/file.csv

I have declared the variable at the top on my DAG.

A: You shouldn't set the path like this due to multiple reasons:

*

*It sounds like you put this code snippet on top of the python file, meaning it will be executed every time airflow parses through the dag folder (and then it will reassign the variable)

*If you plan to rerun any dag run, the output path will be different. The dag isn't idempotent which makes it harder to debug & reproduce results

I guess you are rather looking for execution_date which is the logical date and time which the DAG Run, and its task instances, are running for. Airflow supports accessing this via macros.


text:
Q: What to name a variable which you want to name after its type? Let's say I have an enum class breed and I want to initialize a variable of type breed and I want to name the variable "breed"
struct dog{
    enum class breed{
        shepherd, husky, terrier
    };
    breed breed; // I don't know what to name this.
};

dog::breed makes sense, but dog.breed also makes sense. I don't know what to name these so they don't clash.

A: A common practice that (I guess) swapped over from Java is to start the class / enum name with a capital letter:
Breed breed


text:
Q: What is meant by the "collar of a disk"? I've seen people use the term "collar of a disk" within the context of algebraic topology.  What is meant by this term?  Is it the "boundary" of a disk?

A: It's the boundary cross an interval open on one side, equivalently a small open neighborhood of the boundary.


text:
Q: How to change color of the elements in the array? I want to change each element in the set to red color. I don't know but my solution doesn't work. Any ideas?
var arr = [1,2,3,4];
for(var i=0; i<arr.length;++i){
arr[i].style.backgroundColor = "rgb(0, 0, 0)"; // I want to set i element in the array to color red

}

A: You'll need to create HTML elements to insert into the DOM. As it is now, it's all JS.
var body = document.querySelector("body");
for (int i = 1; i<=4;i++){
    var node = document.createTextNode(i);
    node.style.color = "red";
    body.appendChild(node);
}


text:
Q: What does Pin type I mean on the ESP32 datasheet On page 3 of the esp32-wroom datasheet (PDF) it shows a series of pins with type "I".
What does pin type I mean? Are these different to the pin type I/O pins? If so, how?

A: Some pins can be input and output: I/O (or sometimes General Purpose I/O: GPIO).
Some pins can be outputs only: O.
Some pins can be inputs only: I.
Some pins can be power: P (note that some datasheets will differentiate between input power and ground).
And some pins can be not connected: NC.


text:
Q: Switching a user using "su" gives me only the $ prompt I'm using Ubuntu 19 and I created a few users already. On the latest user I created and tried to do a:
su userx
I login with only the $ prompt, but when I type "bash" as that user I get: userx@myhost:
My other users all login as user@myhost. Why is that user going directly to $ prompt? Also none of my paths work it seems. When I type ll it doesnt work until I type "bash".

A: It is very likely that you did not set a login shell for the user when you created them, causing su to default to /bin/sh. As noted in man su:

       The invoked shell is chosen from (highest priority first):

           The shell specified with --shell.

           If --preserve-environment is used, the shell specified by the
           $SHELL environment variable.

           The shell indicated in the /etc/passwd entry for the target
           user.

           /bin/sh if a shell could not be found by any above method.

Using adduser instead of useradd makes this process easier.
If there is no login shell listed next to the user in /etc/passwd, that would confirm that this is the issue.
You can fix this by running usermod -s /bin/bash <username>


text:
Q: Two domains server_names but separate SSL certificates in NGINX? My NGINX config has a single server defined, and in server-name I have both my domains listed. However, I'd like to keep their SSL certificates separate if possible. I tried using certbot twice, once for each domain, but it seems certbot changes the server's ssl_certificate path in the NGNIX config to match the second domain and overwrites the first domain. Is there a way around this?
Thanks!


text:
Q: z3 and z3PY giving different results When I tried following  in z3, I got result timeout
(set-option :smt.mbqi true)
(declare-fun R(Int) Int)
(declare-fun Q(Int) Int)
(declare-var X Int)
(declare-var Y Int)
(declare-const k Int)
(assert (>= X 0))
(assert (> Y 0))
(assert (forall ((n Int)) (=> (= n 0) (= (Q n) 0))))
(assert (forall ((n Int)) (=> (= n 0) (= (R n) X))))
(assert (forall ((n Int)) (=> (> n 0) (= (R (+ n 1) ) (+ (R n) (* 2 Y))))))
(assert (forall ((n Int)) (=> (> n 0) (= (Q (+ n 1) ) (- (Q n) 2)))))
(assert (forall ((n Int)) (=> (> n 0) (= X (+ (* (Q n) Y) (R n))))))
(assert (forall ((n Int)) (= X (+ (* (Q n) Y) (R n)))))
(assert (= X (+ (* (Q k) Y) (R k))))
(assert  (not (= (* X 2) (+ (* (Q (+ k 1)) Y) (R (+ k 1))))))
(check-sat)

Same when I tried in z3py using following code, I got result unsat which is wrong
from z3 import *
x=Int('x')
y=Int('y')
k=Int('k')
n1=Int('n1')
r=Function('r',IntSort(),IntSort())
q=Function('q',IntSort(),IntSort())
s=Solver()
s.add(x>=0)
s.add(y>0)
s.add(ForAll(n1,Implies(n1==0,r(0)==x)))
s.add(ForAll(n1,Implies(n1==0,q(0)==0)))
s.add(ForAll(n1,Implies(n1>0,r(n1+1)==r(n1)-(2*y))))
s.add(ForAll(n1,Implies(n1>0,q(n1+1)==q(n1)+(2))))
s.add(x==q(k)*y+r(k))
s.add(not(2*x==q(k+1)*y+r(k+1)))
if sat==s.check():
    print s.check()
    print s.model()
else :
    print s.check()

Looking forward to Suggestions.

A: My suggestion is to use replace the built-in not operator by the Z3 function called Not, e.g.
not(2*x==q(k+1)*y+r(k+1))

is simplified to False by Python before Z3 gets to see it, while
Not(2*x==q(k+1)*y+r(k+1))

has the desired meaning.


text:
Q: Updating mysql using ajax recently I was working on a simple voting system for my movie website and I´m stuck with a simple point counter. I have a button with id="point" and when you click it, it should send an ajax request with id number to PHP file, which should increase a value of score in the database (where id=number).
<button type="button" id="point">Points</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>
$(document).ready(function(){
    $("#point").click(function(){
       $.ajax({
            type: "POST",
            url: 'update.php',
            data: {id: 22}
        });
    });
});
</script>`

update.php
<?php
$num = $_POST['id']

$con = mysqli_connect("localhost", "username", "password", "movies");
$vote = "UPDATE movies SET score=score + 1 WHERE id='$num'";
$run_vote = mysqli_query($con,$vote);
?>

Unfortunately, this isn´t working and I can´t figure out why. If someone knows, please write it in the comments.

A: It might be syntax error from your side,
please try the below code:
<?php
$num = $_POST['id'];

$con = mysqli_connect("localhost", "username", "password", "movies");
$vote = "UPDATE movies SET score=score + 1 WHERE id='$num'";
$run_vote = mysqli_query($con,$vote);
?>


text:
Q: The same password is not working across all Stack Exchange sites I am not sure what happened in the last two days. Every time I log in to Stack Overflow I'm asked to reset my password.
I've been resetting my password in Stack Overflow for the last few days and the same password does not work across all Stack Exchange sites. Is it just for me or for others too?
Note:
I signed into Meta.stackexchange with my email and password. However, the same email and password doesn't work in Stack Overflow. I've reset the password in Stack Overflow. Once I log in to Stack Overflow, my Meta login doesn't work anymore.

A: It was resolved using Gmail sign in instead of using email and password. I'm not really sure why email and password stopped working for the last two days.

A: You have two emails attached to your account. One has a password and the other does not. Attempting to reset your password for the email which is not set up with a password actually redirects the request and resets the password for the other email which is set up with one. This can give the impression that the reset isn't working if you continue trying to login with the wrong email, because you need to be typing in a different email with that password.
If you want to use the other email with a password, you need to make sure it's set up with one. You can do so by heading to My logins and adding a new credential, using the desired email and password to trigger a new verification email for it.


text:
Q: What does it mean for two morphisms with different sources and targets to be isomorphic? The standard definition of a subobject relies on the following definition: we call two morphisms $f : X \rightarrow A, g : Y \rightarrow A$ with the same target isomorphic if there exists an isomorphism $u : X \rightarrow Y$ such that $f = g \circ u$. In my eyes, in most texts, this definition is asserted almost by fiat, without diving into what this actually means and why this is a reasonable definition. It's not obvious to me that this is a reasonable definition, for several reasons.
One issue with this definition is that it's not obvious to me why you need it at all - why we can't just define subobjects as isomorphism classes of objects that have monomorphisms into the target in question.
But my larger problem is this. It's obvious what the corresponding definition of isomorphism is between morphisms that share the same source, but what about morphisms that share neither a source nor a target? I would expect that the natural definition would be to say that $f : X \rightarrow A, g : Y \rightarrow B$ are isomoprhic if there exist two isomorphisms $u : X \rightarrow Y, v : A \rightarrow B$ such that $f = v^{-1} \circ g \circ u$. The benefit of this definition is that I believe it flows naturally from the preorder on morphisms in which we define $f \preceq g$ iff $f$ factors through $g$, as the equivalence. However, this definition of isomorphism of morphisms doesn't actually appear to say the same thing as the above
This definition appears - to me - to the notion of isomorphism in the twisted arrow category, also called the category of factorizations: two morphisms are considered however, when specialized to the case $A = B$, this doesn't actually appear to say the same thing as the previous definition, as we have an extra automorphism tacked on to the end.
So is there a way to generalize isomorphism of morphisms that share the same target to isomorphism of all morphisms? If not, why not?

A: One way to motivate the definition of subobjects is that it works in familiar categories. For instance, in $\mathbf{Set}$, every subobject of a set $S$ has a unique representative which is a subset of $S$. In particular, two distinct subsets of $S$ are never isomorphic, which would fail under either of your other two proposals. In fact, for $\mathbf{Set}$ the notion of "isomorphism classes of objects admitting a mono into $S$" and "isomorphism class of arrows into $S$" are equivalent, since if $T$ and $T'$ are (without loss of generality) subsets of $S$ and there exists a bijection $\varphi: T\to T'$, then we can always extend $\varphi$ to an automorphism of $S$ making the arrows $T\to S$ and $T'\to S$ isomorphic.
It's the notion of subset that we want to generalize in defining subobjects, for several very good reasons. The collection of subsets of a set has a rich algebraic structure: it's a complete Boolean algebra. Furthermore, functions between sets induce three morphisms of Boolean algebras which encode first-order logic. Most of this story generalizes to an arbitrary locally Cartesian closed category such as a topos, and some of it generalizes to a huge range of categories satisfying weaker properties. Your proposals amount to considering the set of mere cardinalities at most that of $S$, which has no such interesting structure.


text:
Q: Android: How to get gps on/off events as they occur I have seen the following question asked many times but none of the answers have been very clear, at least to me....
I want my android app to capture when GPS is enabled/disabled. I am NOT interested in the users current location, or in receiving location updates.
The reason I am confused is people have suggested both a location listener and the gpsstatus listener and I'm not sure how to work with either (I have looked at tutorials such as http://www.vogella.com/tutorials/AndroidLocationAPI/article.html and on androidhive etc.).
1)Do I implement the location listener within a service? If so, how is onProviderEnabled or onProviderDisabled called? Should the listener be created in onCreate(), onStartCommand() or does it matter?
2)Do I need to implement my service in conjunction with a broadcast receiver like you do for screen on/off events? Or can I capture the events with just a service...
3) If I don't care about location updates, do I still have to call locationManager.requestLocationUpdates in order for onProviderEnabled and onProviderDisabled to be called?
Edit: It needs to work on android api 8+


text:
Q: Topology Proof with Neighborhoods and Open Sets I am trying to prove this theorem:

$A^o\cup A^{ext}\cup\ A^b=\mathbb{R}$

I don't really know where to start. $A$ is a subset of $\mathbb{R}$.

A: Let it be that $x\in\mathbb R$ and $A\subseteq\mathbb R$.
We discern the following statements:

*

*an open set $U$ exists with $x\in U\subseteq A$.

*an open set $U$ exists with $x\in U\subseteq A^c$.

*for every open set $U$ with $x\in U$ we have $U\cap A^c\neq\varnothing$ and $U\cap A\neq\varnothing$
Note that exactly one of these statements is true.

A: I use more standard notions: $\overline{A}$ for closure, $A^e$ for exterior and $\partial A$ for boundary.
By definition
$$
\partial A = \overline{A}-A^o\quad\text{and }\quad A^e=\overline{A}^c
$$
Since $A^o\subset \overline{A}$
$$
\partial {A}\cup A^o=(\overline{A}-A^o)\cup A^o=(\overline{A}\cap A^{o^c})\cup A^o=(\overline{A}\cup A^o)\cap(A^{o^c}\cup A^o)=\overline{A}\cap \Bbb{R}=\overline{A}
$$
Thus
$$
\partial {A}\cup A^o\cup A^e=\overline{A}\cup\overline{A}^c=\Bbb{R}
$$


text:
Q: ESX Packet Loss I'd like to test my software with some amount of packet loss.  I see that I can do this with pfSense in the traffic shaping.  But that's a lot of hassle to set up and create a couple of extra virtual switches and so on.
Can I do this directly in ESX to a particular network interface or across an entire virtual switch?

A:
Can I do this directly in ESX to a particular network interface or
  across an entire virtual switch?

No. You'll need to route the traffic through a linux or BSD box to mangle the packets.

A: As EEAA stated, nothing you can do specifically in ESX(i) to acomplish this, however...
There a fairly simple free tool called "WANEM" http://packetlife.net/blog/2011/jan/12/emulating-wans-wanem/
Basically you boot from the iso, setup an IP, configured your default route (client side) to the wanem IP, set your tcp parameter and away you go.


text:
Q: beginner/VTK_marching Cube_vertices and faces/ Hi I would like to know how can I get the coorinates of vertices and the face after marching cube
vtkSmartPointer<vtkMarchingCubes> surface =
    vtkSmartPointer<vtkMarchingCubes>::New();
surface->SetInputData(imageData);
surface->ComputeNormalsOn();

I would like to know how can I see the values of marching cube results? how can I access the coordinates of vertices and the faces?
Thank you


text:
Q: How to clear the complete back stack (and possible solution) I have three activities A, B and C.
A is the main activity of my application.
A and C can also be started from the Options Menu, B is started from A.
I would like the following behavior:

*

*application starts with A: back stack is {A}

*from A, I navigate to B   : back stack is {A,B}

*from the options menu, I start C : back stack is {C}

1 and 2 are trivial but I don't succeed in getting 3 to work.
I tried quite a lot of FLAG_ACTIVITY combinations but without success
and I'm getting the impression that this isn't possible.
I'm thinking about creating a DummyRoot activity that is just used to start another activity (actual activity name to start is passed in Intent.getExtras()).  I can give this DummyRoot activity the FLAG_ACTIVITY_CLEAR_TOP.
By doing so, I would get

*

*application starts with DummyRoot(A): back stack is {DummyRoot, A}

*from A, I navigate to B   : back stack is {DummyRoot, A,B}

*from the options menu, I start DummyRoot(C) : back stack is {DummyRoot, C}

Do you foresee problems with this approach?
Is this needed in the first place or is it possible to clear the back stack in a more elegant way?

A: So when you press back whilst in C, you want the application to quit? If so, you will need to use Flags in your manifest and when you start the Activity using the Intent. A combination here will allow you to clear the current Task and then start a fresh one with your new Activity in it. It does not seem a valid UX, but should do the trick. Please read up on the FLAGS in the documentation for more info on what they will actually do.


text:
Q: Inserting geometry into spatialite - no geometry I have created a test spatialite database and I am having trouble inserting geometry into the table. I have successfully created the geometry column in the table and then I run the insert command. The weird thing is that it runs without error, and the attributes get passed in, however the geometry column is empty when I view it through a ODBC connection, as well as no geometry coming through in QGIS.
My code to create the table:
with sqlite3.connect(r'somedatabase.sqlite') as conn:

    conn.enable_load_extension(True)

    conn.execute("SELECT load_extension('mod_spatialite')")
    conn.execute("SELECT InitSpatialMetaData()")

    c = conn.cursor()

    c.execute("""CREATE TABLE IF NOT EXISTS gid(gid_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                latitude REAL, longitude REAL)""")
    c.execute("SELECT AddGeometryColumn('gid','the_geom', 4283,'POINT','XY')")
    conn.commit()

And this is the code to create the geometry
someGeometry = [(150.895,-33.961),(150.896,-33.959),(150.893,-33.960)]
for longitude,latitude in someGeometry:
    c.execute("""INSERT INTO gid(gid_id,latitude,longitude,the_geom)
                 VALUES(NULL,?,?,GeomFromText('POINT((%f %f)',4283))""" %(longitude,latitude),
                    (latitude,longitude,))

conn.commit()

I have also tried to remove the python string formatting by inserting only 1 point with specific coordinates like this
c.execute("""INSERT INTO gid(gid_id,latitude,longitude,the_geom)
                 VALUES(NULL,?,?,GeomFromText('POINT((150.895,-33.961)',4283))""",(latitude,longitude,))


text:
Q: Intersection of non transverse submanifolds Hi!
Probably this is an easy question, but i can't see the answer.
Let $X$ be a a smooth real manifold with $\dim(X)=d$ and $M,N\subset X$ two smooth submanifolds
with $\dim(M)=m$ and $\dim(N)=n$. The submanifolds $M,N$ intersect but not transversely.
What can i say about connected components of $M\cap N$? More precisely, is it possible to find  three manifolds $X,M,N$ as above such that a connected component of $M\cap N$ is not a manifold? Or a connected component that is not smooth? (In all the examples i thought, connected components of $M\cap N$ were smooth)
Thank you in advance.

A: You could try the real quadric surface $x^2+y^2-z^2=1$ and the hyperplane $x=1$. They intersect along a union of two (intersecting) lines ($z=\pm y$, $x=1$).

A: Let $M$ be any manifold, and let $Z$ be a closed subset of $M$.  Suppose there exists a smooth function $f:M\to\mathbb{R}$ with $f^{-1}\{0\}=Z$.  We can then take $X=M\times\mathbb{R}$ and identify $M$ with $M\times\{0\}$ and put $N=\{(m,f(m)):m\in M\}$.  Then $M$ and $N$ are embedded submanifolds of $X$ with $M\cap N=Z$.
Moreover, I think it is true that such a function $f$ exists for every closed subset $Z$, no matter how wild or fractal. I don't remember the argument in detail, but if I recall correctly it is not too hard.  One issue is to patch together things done locally using a partition of unity, and another is to express $f$ as a countable sum of nonnegative smooth functions $f_n$ which need to be rescaled aggressively to force the higher derivatives of the sum to converge.


text:
Q: How to reduce billing on my AWS RDS instance We currently pay somewhere between 85-100 USD on a monthly basis for RDS usage. But most of the times we don't access our database instances. Is there a way to reduce the billing by bringing down the instance or go in for a shared database mode. What kind of alternatives exist?

A: You can delete an instance at any time with DeleteDBInstance.  By default, a final snapshot will be created .  Then, you can recreate it at a later time.  See this FAQ.  The final snapshot storage cost is $0.15 per GB-month.

A: Even I was facing this issue. With AWS; RDS is much more expensive than EC2 instances. And database is something which needs to run for 24*7 in my case as compared to EC2 instances which can be optimized.
The way I opted for reducing my costs for RDS is go for "Reserved Instance" .. Anyway RDS is something which I will always need ( until I am on AWS ). This way I could reduce my costs by around 50%.

A: There are several options you can leverage to reduce RDS costs. You mention that you are not using your RDS instance most of the time, so that is the first obvious place to look for savings:

*

*If you only use the instance for, say, 8 hours/day, 09:00 - 17:00, set up a scheduled job to shut down the instance at 17:00 and start it back up at 09:00.

*Look at serverless RDS instances. They shut down after an idle period. You should be aware, however, that if you have monitoring hooked into your RDS instance, the monitoring will create enough workload to prevent the instance from ever going to sleep, so it is only suitable for a very narrow range of uses and needs to be considered very carefully.

*As mentioned elsewhere in the thread, switch to an EC2 instance and manage your own database. That will save you approximately half in costs compared to a similarly specced RDS instance.
For more finely grained savings approaches, you may want to look at this article a colleague of mine wrote on reducing RDS costs in AWS.

A: AWS added the ability to shut down (but not delete!) RDS instances when you are not using them. That way, you only pay for the data storage, which is much cheaper than the actual running DB. You can use the AWS Instance Scheduler to automatically shut down RDS DBs and EC2 Instances on a scheduled basis, such as at night and on weekends in non-production environments.
You can find more info on this, plus other AWS cost optimization tips in the AWS Production Readiness Checklist.


text:
Q: Get the workitems of a particular project using TFS api in Powershell Hi I am trying to get the workitems of a particular project only using below code but i am getting the work item count of all the projects. Please help?
$user = "username"
$token = "PAT"
$count=0
Function QueryWorkItem{

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))

$uri = "http://(url)/tfs/DefaultCollection/(project name)/_apis/wit/wiql?api-version=2.2"
$body = "{
'query':'Select [System.WorkItemType],[System.Title],[System.State],[System.Id] FROM WorkItems '
}"
$result = Invoke-RestMethod -Uri $uri -Method Post -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Body $body

foreach($i in $result.WorkItems){
$result2 = Invoke-RestMethod -Uri https://(uri)/_apis/wit/workItems/$($i.id)?api-version=2.2 -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method Get
foreach ($j in $result2.fields )
{

    if ($j.'System.WorkItemType' -cmatch "Feature")
{

Write-Output ("work item ID: $($i.id) ") |  Out-File -Append Tasks.txt
Write-Output "WorkItem type:" $j.'System.WorkItemType'|  Out-File -Append Tasks.txt
Write-Output "Title:" $j.'System.Title'|  Out-File -Append Tasks.txt
Write-Output "Team Project:" $j.'System.TeamProject'|  Out-File -Append Tasks.txt
Write-Output "--------------------------------------------------------"|  Out-File -Append Tasks.txt

$global:count++
}

}
}

    }

    QueryWorkItem
      Write-Output "count:" $count

A: The PowerShell CmdLets offer an extensive list of features that wrap the Client Object model or that call into the REST API directly.
https://github.com/igoravl/tfscmdlets
Example:
# Connect to the FabrikamFiber team project collection
# (Will be used as default for the -Collection argument when required by a cmdlet)
Connect-TfsTeamProjectCollection http://vsalm:8080/tfs/FabrikamFiberCollection

# Get a list of team projects in the currently connected TPC
Get-TfsTeamProject

# List the existing iterations in the FabrikamFiber team project
Get-TfsIteration -Project FabrikamFiber

# Connect to the FabrikamFiber team project
# (will be used as default for the -Project argument when required by a cmdlet)
Connect-TfsTeamProject FabrikamFiber

# Get all bugs in the current team project
Get-TfsWorkItem -Filter '[System.WorkItemType] = "Bug"'

A: The query should looks like:
Select [System.WorkItemType],[System.Title],[System.State],[System.Id] FROM WorkItems WHERE [System.TeamProject] = @project

More information, please refer to the link below:
https://learn.microsoft.com/en-us/vsts/collaborate/wiql-syntax

A: Your work item query doesn't filter on System.TeamProject, so it's querying across team projects. Add a WHERE clause to your query.


text:
Q: "I'll revenge" vs "I'll take revenge" Throughout my life I have thought that the correct expression is to take revenge; however, I have also heard people saying I'll revenge. Which is correct?

A: Revenge is most commonly used as a noun, e.g. "I vow to take revenge on him for stealing my girlfriend." The words "to take" are optional, and you could just as easily say: "I vow revenge...". You can also substitute "upon" for "on", but it sounds more pompous.
Revenge is less commonly used as a verb. The construction is always in a very specific form, from what I've seen. Usage: "I will revenge myself on him in the most bloody way!" Note the use of the first person reflexive pronoun, the preposition "on" (which can be replaced with "upon") and an object (the party you are going to wreak vengeance upon). Note that this usage would sound highly affected and pompous to most speakers, and should be reserved for when you're going for the "grand effect", e.g. in a bombastic literary work.
Contrast this to avenge, which is always a verb, and vengeance, which is always a noun.

A: I believe what you have heard is an eggcorn.  It's simply someone who has misheard and reused the phrase "I'll avenge".

A: Revenge is both a noun and verb. Examples :
He revenged himself for the insult. (As a verb)
He took revenge on the neighbour who had insulted him. (As a noun)


text:
Q: Kernel writing logs every second I'm looking in /var/log/messages and I'm seeing this sort of logging every second:

May  5 16:54:55 dag kernel: [86219.516013] EDAC MC0: CE page 0xfe5e7,
  offset 0x400, grain 128, syndrome 0xe0, row 4, channel 0, label "":
  i3000 CE
May  5 16:54:56 dag kernel: [86220.516020] EDAC MC0: CE page 0xfe5e7,
  offset 0x400, grain 128, syndrome 0xe0, row 4, channel 0, label "":
  i3000 CE

(server name is dag).
I have no idea why it's writing these logs every second and it makes tracing other problems difficult due to all the noise.
Can someone pleas tell me how to disable this or turn down the verbosity?

A: This bug report mentions the same and he fixed it by changing his RAM. Seems to be a hardware problem.

A: Running this command made EDAC a bit more quiet:
echo 0 > /sys/module/edac_core/parameters/edac_mc_log_ce


text:
Q: How to continuously check if there is a change within the Database of Firebase? I'm trying to make an multiplayer pen and paper S.O.S game and I found online some people were able to something similar using Firebase. I've hit a road block and can't find a proper solution for it.
How my app works currently the player 1 is able to create a new game and enters the game activity the game code is displayed. Player 2 can join the game by typing the game code that was generated and join the game, his/her information is inserted to the database. My problem is that player 1 , while waiting in the game activity, has no way to know if player 2 has join the game.
What I want to know if there is a way to check the database continuously while player 1 is waiting for player 2 to join. I tried ondatachange but I found that method is only triggered once, and I need a method to check/triggered continuously or at least check if there a change within database if player 2 has joined the game.
Firebase Database Structure
Before Player 2 Joins
----
   Game
   |
   -------(Game Code)
               |
               ---------(Game Code)
               ---------(Player 1 Details)

After Player 2 Joins
----
   Game
   |
   -------(Game Code)
               |
               ---------(Game Code)
               ---------(Player 1 Details)
               ---------(Player 2 Details)

A: Since you are using Realtime Database, not Firestore. You can learn more by reading this documentation page.
What you are looking for is something like:
val postListener = object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        // Get Post object and use the values to update the UI
        val post = dataSnapshot.getValue<Post>()
        // ...
    }

    override fun onCancelled(databaseError: DatabaseError) {
        // Getting Post failed, log a message
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException())
        // ...
    }
}
postReference.addValueEventListener(postListener)

Where you will have your listener do something like:
postReference.child("Game").child("Game Code").addValueEventListener(postListener)

And check in your listener if player 2 exists. The listener code will only get triggered when something changes on the cloud side of Firebase. So when a new player is added your listener code will be called.
I hope this helps.

A: there is snapshotListeners for the database, check out official documentation from :
https://firebase.google.com/docs/firestore/query-data/listen#kotlin+ktx
or watch this youtube video
https://www.youtube.com/watch?v=-kre5cmoR8Q
happy hacking..


text:
Q: Concatenate two tables with union Concatenate two tables in PostgreSQL version 9.5.1 with UNION; and check if the value in column name appears in one or both of these tables with a Boolean.
Here is my minimal example code:
WITH things_a(name) AS (
            VALUES ('AAA'),('BBB'),('CCC')),
     things_b(name) AS (
            VALUES ('BBB'),('CCC'),('DDD'))
SELECT *
FROM
  (SELECT name AS name,
      TRUE AS in_a,
          NULL::boolean AS in_b
   FROM things_a
   UNION SELECT name AS name,
        NULL AS in_a,
        TRUE AS in_b
   FROM things_b) AS things
ORDER BY name

For which I would like to have the following outcome:
name   | in_a    | in_b
------------------------
AAA    | t       | f
BBB    | t       | t
CCC    | t       | t
DDD    | f       | t

But there might be an alternative approach of course

A: Do you really want to use UNION?
You could simply use:
WITH things_a(name) AS (
            VALUES ('AAA'),('BBB'),('CCC')),
     things_b(name) AS (
            VALUES ('BBB'),('CCC'),('DDD'))
SELECT COALESCE(things_a.name,things_b.name) as name,
       things_a.name is not null as in_a,
       things_b.name is not null as in_b
from things_a full outer join things_b
     on things_a.name=things_b.name
order by 1
;

Or is your implied question asking for the missing parts of your sample code?
Then the following might be what you are looking for:
WITH things_a(name) AS (
            VALUES ('AAA'),('BBB'),('CCC')),
     things_b(name) AS (
            VALUES ('BBB'),('CCC'),('DDD'))
SELECT name, COALESCE(bool_or(in_a),false) as in_a, coalesce(bool_or(in_b),false) in_b
FROM
  (SELECT name AS name,
      TRUE AS in_a,
          NULL::boolean AS in_b
   FROM things_a
   UNION SELECT name AS name,
        NULL AS in_a,
        TRUE AS in_b
   FROM things_b) AS things
group by name
ORDER BY name;


text:
Q: How to make dynamic input parameters based on another query response in an Integromat app? I am implementing an API that has an endpoint which returns a list of custom fields for objects such as company, lead, etc.
When creating a lead, the user should be able to enter custom fields alongside the hardcoded ones.
How can this be done dynamically in the Mappable parameters of a module?

A: You can create an RPC (procedure for getting of dynamic input fields via API) and combine it with static parameters like in the example below:
Mappable parameters:
[
    {
        "name": "id",
        "type": "uinteger",
        "label": "Static parameter"
    },
    "rpc://getDynamicFields"
]

Ref: https://docs.integromat.com/apps/structure-blocks/expect#rpc
How to create RPC you can find here: https://docs.integromat.com/apps/app-structure/rpcs#fields-rpc


text:
Q: card-content on materialize not fit in its class i am used card materialize in my page the page looks like this
cards
you can see my card content and description is in my image, i follow guide from materialize but it not work in my page
this is my code

            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta name="description" content="">
            <meta name="author" content="">

            <link rel="apple-touch-icon-precomposed" href="<?php echo base_url(); ?>assets/home-user/assets/img/favicon/apple-touch-icon-152x152.png">
            <meta name="msapplication-TileColor" content="#FFFFFF">
            <meta name="msapplication-TileImage" content="<?php echo base_url(); ?>assets/home-user/assets/img/favicon/mstile-144x144.png">
            <link rel="icon" href="<?php echo base_url(); ?>assets/home-user/assets/img/favicon/favicon-32x32.png" sizes="32x32">
            <title>Home</title>
            <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

            <link href="<?php echo base_url(); ?>assets/home-user/materialize/css/materialize.css" rel="stylesheet" type="text/css">

            <link href="<?php echo base_url(); ?>assets/home-user/template.css" rel="stylesheet" type="text/css">

                        Card Title

I am a very simple card. I am good at containing small bits of information.
                          I am convenient because I require little markup to use effectively.

                          This is a link

i dont know whats wrong with my code thanks

A: load materialize css and js files and also jquery file...  here is a working snippet

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">

            Card Title

I am a very simple card. I am good at containing small bits of information.
              I am convenient because I require little markup to use effectively.

              This is a link


text:
Q: Scanning a String for strings I'm trying to write a function that reads in a line from a file using fgets().
After reading the line, I want to take the line apart and make it into smaller strings.
Depending on the first word in the line, the line that I read in can have 3-5 smaller strings that are separated by a white space.
Example:
Line: remove apple 12345
string1: remove
string2: apple
string3: 12345
Line: add tomato red leaf
string1: add
string2: tomato
string3: red
string4: leaf
From the example above, if 1st string is remove, I need to read 2 other strings (apple, 12345).
If the  first string is add, I need to read 3 other strings (tomato, red, leaf).
Is there anyway that I can decide the number of times to read and do this using sscanf?
while( fgets( buf, sizeof buf, course_file ) != NULL ){
    sscanf( buf, "%s", &string1);
    printf( "%s\n", buf );
}

It is not compulsory that I use sscanf, I'm open to other suggestions.

A: The function typically used to tokenize strings is strtok, but it is not thread-safe; its modern version is strtok_r should be used instead.
Start tokenizing the buf in the first call, check the first token, and then go into one of several loops that depend on the content of the first token:
while( fgets( buf, sizeof buf, course_file ) != NULL ) {
    char *saveptr;
    char *tok = strtok_r(buf, " ", &saveptr);
    if (!strcmp(tok, "delete")) {
        for (int i = 0 ; i != 3 ; i++) {
            tok = strtok_r(NULL, " ", &saveptr);
            // Do something with the token...
        }
    } else if (!strcmp(tok, "add")) {
        for (int i = 0 ; i != 4 ; i++) {
            tok = strtok_r(NULL, " ", &saveptr);
            // Do something else with the token...
        }
    } else {
        // Error
    }
}


text:
Q: Hover with overlay and not affecting text color I'm trying to make the color of the image darker when it's hovered, and without affecting the color of the text attached to it at the same time. I tried to use opacity but it doesn't work as expected.

.imageone {
  position: relative;
  width: 100%;
}

.imageone:hover {
  opacity: 0.9;
}

#header {
  position: absolute;
  left: 100px;
  top: 200px;
  color: white;
}

A Movie in the Park:
Kung Fu Panda

A: Approach 1:  Using CSS filter, e.g. filter: brightness(0.5);

.imageone {
  position: relative;
}

.imageone img {
  transition: filter .25s;
}

.imageone img:hover {
  filter: brightness(0.5);
}

#header {
  position: absolute;
  left: 100px;
  top: 200px;
  color: white;
}

A Movie in the Park:
Kung Fu Panda

Approach 2:  Using a pseudo element to cover the image with background-color: rgba();

.imageone {
  position: relative;
  display: inline-block;
}

.imageone:before {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  transition: background-color .25s;
}

.imageone:hover:before {
  background-color: rgba(0,0,0,.5);
}

#header {
  position: absolute;
  left: 100px;
  top: 200px;
  color: white;
}

A Movie in the Park:
Kung Fu Panda


text:
Q: What is a constant vector? If the acceleration vector and velocity vector are antiparallel and constant vectors(?) what is the type of motion of the particle/body?
Also, what are constant vectors?

A: Since this is physics, such a question is best answered by a computation. Acceleration is the derivative of velocity:
$$\vec{a}=\frac{d\vec{v}}{dt}$$
If it's constant, then this can be be integrated as:
$$\vec{v}=\vec{a}t+\vec{v}_0$$
with $\vec{v}_0$ the initial velocity. Since you're asking for velocity to be also constant, then:
$$\vec{v}=\vec{v}_0$$
You can derive that to return to acceleration:
$$\vec{a}=\frac{d\vec{v}_0}{dt}=\vec{0}$$
So the only way to have constant acceleration and velocity is to have zero-acceleration, and constant (zero or non-zero) velocity.

A: A constant vector has one direction and one magnitude,
if v and a are antiparallel, then  magnitude of v decreases till it is 0 and then increases,


text:
Q: Flat tree of objects while keeping father and child I have a class Employee which has a tree structure with property team
public class Employee {

    private String name;
    private List<Employee> team;
}

Using Java lambdas I need to flat this tree into same level list while converting Employee class into the following ConvertedEmployee while storing names in dedicated lead and subordinates properties. So ConvertedEmployee is in some sense a node which keeps parent and children. And I need to have a list of those.
    public class ConvertedEmployee {

    private String name;
    private String lead;
    private List<String> subordinatesNames;
}

So final result should be List<ConvertedEmployee>
I was thinking to use recursion here.
But I can only flat the tree and can't rebuild it's parents.
EDIT:
Input is instance of Employee object that basically has a tree inside team

A: A non-recursive solution using concatenation of the streams followed by filtering out the "duplicated" entries which do not have lead field set:
public static List<ConvertedEmployee> convert(List<Employee> staff) {
    return staff
        .stream()
        .flatMap(e -> Stream.concat(
            // subordinates of current employee
            e.getTeam()
             .stream()
             .map(sub -> new ConvertedEmployee(
                 sub.getName(), e.getName(),
                 sub.getTeam().stream().map(Employee::getName).collect(Collectors.toList())
             )),
            // current employee by themself
            Stream.of(new ConvertedEmployee(
                 e.getName(), null,
                 e.getTeam().stream().map(Employee::getName).collect(Collectors.toList())
            ))
        ))
        .collect(Collectors.collectingAndThen(
            Collectors.toMap(
                ConvertedEmployee::getName,
                c -> c,
                (e1, e2) -> e1.getLead() != null ? e1 : e2.getLead() != null ? e2 : e1,
                LinkedHashMap::new
            ),
            map -> new ArrayList<>(map.values())
        ));
}

Test for the following setup:
Employee intern = new Employee("intern", Collections.emptyList());
Employee junior = new Employee("junior", Collections.emptyList());
Employee middleDev = new Employee("mid", Arrays.asList(junior));
Employee devOps = new Employee("devOps", Collections.emptyList());
Employee teamLead = new Employee("teamLead", Arrays.asList(intern, middleDev));
Employee pm = new Employee("mgr", Arrays.asList(teamLead, devOps));

List<Employee> staff = Arrays.asList(intern, junior, middleDev, devOps, teamLead, pm);

convert(staff).forEach(System.out::println);

Output:
ConvertedEmployee(name=intern, lead=teamLead, subordinatesNames=[])
ConvertedEmployee(name=junior, lead=mid, subordinatesNames=[])
ConvertedEmployee(name=mid, lead=teamLead, subordinatesNames=[junior])
ConvertedEmployee(name=devOps, lead=mgr, subordinatesNames=[])
ConvertedEmployee(name=teamLead, lead=mgr, subordinatesNames=[intern, mid])
ConvertedEmployee(name=mgr, lead=null, subordinatesNames=[teamLead, devOps])


text:
Q: Image gets mixed up after orientation in iPhone I'm currently working on an app which is like a photo gallery. It supports orientations too. The UIImageView which contains the UIImage, is in UIViewContentModeScaleAspectFit. When I change the orientation of the device, some part of the UIImage gets displayed on the part of the view which is not a part of the aspect fit region.Any ideas to tackle it??

A: I just got similar kind of problem while using zooming effect. After changing the orientation of device while the image is zoomed in, it overlaps the imageView. Try to zoom out the image just after changing the orientation. That worked for me.


text:
Q: Why is $\mathbb R^n$ so important in algebraic topology? If you study the different tools from algebraic topology, you realise that most (if not all) of them are somehow meant to compare the space with Euclidean space:

*

*Homotopy theory deals with maps from $S^n\subset\mathbb R^{n+1}$ into the space.

*Singular homology deals with maps from $\Delta^n\subset\mathbb R^{n+1}$ into the space.

*Simplicial homology only studies spaces built from simplices (which are subspaces of Euclidean space)

*Cellular homology does the same with $n$-cells.

All of these tools are excellent for studying spaces that are built up from Euclidean space using the operations from point set topology, identifying and crossing stuff here and there. But you would think that these spaces form an extremely small corner of the entire category of topological spaces. I would assume that there are many other (possibly not very "interesting," from a concrete point of view) spaces that are very different from Euclidean ones and which are extremely hard to compare to them. So why does it seem that the entire toolbox from algebraic topology is only concerned with Euclidean-like spaces? I would assume that the explanation is some combination of the following, mainly the last one:

*

*Euclidean spaces have some (to me unknown) universal property in the category of topological spaces that makes them very distinguished objects, a natural choice to compare others to; or

*Most of the concrete problems that we want to solve are naturally occurring in Euclidean space or something very similar.

Can one or both of these explain this issue?

A: My algebraic topology professor had a slogan: "Point set topology looks at 'simple' properties of 'exotic' spaces whereas algebraic topology looks at 'exotic' properties of 'simple' spaces."
General topology lays out things like connected, path connected, locally connected, etc. Then you start to look at how these properties are related. You ask questions like: "If I'm sequentially compact, am I also compact? pseudocompact?" "What's a really weird space which has properties 4 and 6 but not 1 or 5."
Algebraic topology is trying to get at more fine tuned data. So we work in an "easy" setting: I'm connected, compact, ... heck, I'm a compact manifold. How can you tell me apart from this other nice space? I need some really finely tuned properties to do this. In comes homology / cohomology / homotopy etc.
When it comes down to it, the "nice" spaces like a torus or sphere are already "hard enough" to deal with, so we aren't as concerned with more difficult things.
Think of general topology like using a telescope and algebraic topology like using a microscope. You aren't going to begin by pointing your microscope up at the sky. Point it as your desk first.
Alternatively, we care a lot about $\mathbb{R}^n$ related spaces because that's where the lion's share of applications lie. :)

A: Some random answers:
1) Algebraic topology is still topology, and we care about things like continuity, smoothness, etc. that we wouldn't get if we were working in the more general setup of, say, algebraic geometry.
2) Algebraic topology is a technical area of mathematics, and relaxing $\mathbb{R}^n$ to a more general space will cause some important things to break. For example, one of the reasons CW-complexes are popular (aside from a combination of generality and simplicity) is that Whitehead's theorem holds for them; that's not true for a general category.
3) The $S^n$ in homotopy theory isn't arbitrary; it comes from the fact that $S^{n+1}$ is the suspension of $S^n$. In a sense, $S^0$ is the "simplest" nontrivial pointed space; it's just a basepoint with one more point added.
4) We still want to study manifolds even in algebraic topology, and manifolds are built out of copies of $\mathbb{R}^n$. (Looking at manifolds based on, say, general Hilbert spaces works well but does differ from the finite-dimensional case.)
5) We don't restrict ourselves to topological $n$-manifolds. There's a lot of work in algebraic topology about finding conditions ensuring (or preventing)  that a "reasonably nice" space is actually a topological manifold.


text:
Q: Removing tags from this `tag_names` attribute when then are removed form the input field? I have a Tag model:
class Tag < ActiveRecord::Base
  has_many :taggings, :dependent => :destroy
  has_many :posts, :through => :taggings
  has_many :subscriptions
  has_many :subscribed_users, :source => :user, :through => :subscriptions
end

and a Post model:
class Post < ActiveRecord::Base
  attr_accessible :title, :content, :tag_names

  belongs_to :user

  has_many :taggings, :dependent => :destroy
  has_many :tags, :through => :taggings

  attr_writer :tag_names
  after_save :assign_tags

  def tag_names
    @tag_names || tags.map(&:name).join(' ')
  end

  private

  def assign_tags
    return if @tag_names.blank?
    @tag_names.split(" ").each do |name|
      tag = Tag.find_or_create_by_name(name)
      self.tags << tag unless tags.include?(tag)
    end
  end
end

The assign_tags method stores the saved tags in :tag_names and displays it in an input field in this fashion: tag1 tag2 tag3 (values are separated by spaces).
views/posts/_form.html.erb:

    <%= f.label :tag_names %>

    <%= f.autocomplete_field :tag_names, autocomplete_tag_name_posts_path, :"data-delimiter" => ' '%>

As you can see, assign_tags, enables me to add/push tags to tag_names. But if I delete a tag from the input field and save. The tag will still show up.
Any suggestions to help me solve this issue?
(Maybe tag_names should just empty itself before the tags are pushed in. But no idea how to code that).

A: Before assigning tags, you'll want to clear the tags for that item. e.g.
def assign_tags
  self.tags = []
  return if @tag_names.blank?
  @tag_names.split(" ").each do |name|
    tag = Tag.find_or_create_by_name(name)
    self.tags << tag unless tags.include?(tag)
  end
end

Update:
Or, a method that will hit the database a bit less:
def assign_tags
  ntags = []
  @tag_names.to_s.split(" ").each do |name|
    ntags << Tag.find_or_create_by_name(name)
  end
  self.tags = ntags
end

If you wanted to get really crazy with the write-less-do-more paradigm, you could do:
def assign_tags
  self.tags = @tag_names.to_s.split(" ").inject([]) do |arr, name|
    arr << Tag.find_or_create_by_name(name)
    arr
  end
end

Alternatively, I'd recommend looking into the acts-as-taggable-on gem.


text:
Q: Parsing an array of dictionnaries in a django for loop In a Django application, I want to use a dictionary as elements of a result.html page:

    {% for element in products%}

        {{ element['q0']['Results'][0]['Name'] }}

    {% endfor %}

But it returns Could not parse the remainder: '['q0']['Results'][0]['Name']' from 'element['q0']['Results'][0]['Name']':
    return render(request, 'todo/result.html', {'products': top_products})
  File "C:\Python36\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Python36\lib\site-packages\django\template\loader.py", line 61, in render_to_string
    template = get_template(template_name, using=using)
  File "C:\Python36\lib\site-packages\django\template\loader.py", line 15, in get_template
    return engine.get_template(template_name)
  File "C:\Python36\lib\site-packages\django\template\backends\django.py", line 34, in get_template
    return Template(self.engine.get_template(template_name), self)
  File "C:\Python36\lib\site-packages\django\template\engine.py", line 143, in get_template
    template, origin = self.find_template(template_name)
  File "C:\Python36\lib\site-packages\django\template\engine.py", line 125, in find_template
    template = loader.get_template(name, skip=skip)
  File "C:\Python36\lib\site-packages\django\template\loaders\base.py", line 30, in get_template
    contents, origin, origin.template_name, self.engine,
  File "C:\Python36\lib\site-packages\django\template\base.py", line 155, in __init__
    self.nodelist = self.compile_nodelist()
  File "C:\Python36\lib\site-packages\django\template\base.py", line 193, in compile_nodelist
    return parser.parse()
  File "C:\Python36\lib\site-packages\django\template\base.py", line 478, in parse
    raise self.error(token, e)
  File "C:\Python36\lib\site-packages\django\template\base.py", line 476, in parse
    compiled_result = compile_func(self, token)
  File "C:\Python36\lib\site-packages\django\template\defaulttags.py", line 814, in do_for
    nodelist_loop = parser.parse(('empty', 'endfor',))
  File "C:\Python36\lib\site-packages\django\template\base.py", line 449, in parse
    raise self.error(token, e)
  File "C:\Python36\lib\site-packages\django\template\base.py", line 447, in parse
    filter_expression = self.compile_filter(token.contents)
  File "C:\Python36\lib\site-packages\django\template\base.py", line 563, in compile_filter
    return FilterExpression(token, self)
  File "C:\Python36\lib\site-packages\django\template\base.py", line 663, in __init__
    "from '%s'" % (token[upto:], token))
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '['q0']['Results'][0]['Name']' from 'element['q0']['Results'][0]['Name']'

It was sent by views.py:
def getmatch(request):
    # cosas cosas cosas para obtener top_products

    print(top_products[0])
    return render(request, 'todo/result.html', {'products': top_products})

Here is an example of a product top_products[0]:
{
  "q1": {
    "Id": "q1",
    "Limit": 20,
    "Offset": 0,
    "TotalResults": 0,
    "Locale": "fr_FR",
    "Results": [],
    "Includes": {},
    "HasE rrors": false,
    "Errors": []
  },
  "q0": {
    "Id": "q0",
    "Limit": 10,
    "Offset": 0,
    "TotalResults": 1,
    "Locale": "fr_FR",
    "Results": [
      {
        "EANs": [
          "8011003827336"
        ],
        "Description": "L'aur a divine d'une femme habillée d'une essence éblouissante et sensuelle…\nEros pour Femme est le mythe signé Versace, qui déclenche la passion débordante d'Eros au pre mier regard.\n\nMais qui séduit qui ?\nEros pour Femme est une invitation à s'abandonner au désir, en osmose avec les forces de la nature apaisée.\n\nAudacieuse, cré ative et sensuelle, comme seule peut l'être la maison Versace, cette Eau de Toilette révèle une aura radieuse et une séduction irrésistible.",
        "ImageUrl": "https://w ww.sephora.fr/dw/image/v2/BCVW_PRD/on/demandware.static/-/Sites-masterCatalog_Sephora/default/dw99b648b2/images/hi-res/SKU/SKU_5/359845_swatch.jpg?sw=250&sh=250&sm=f it",
        "Name": "Eros pour Femme - Eau de Toilette",
        "Id": "P2615007",
        "CategoryId": "parfum_719097",
        "BrandExternalId": "versace_c45bfd",
        "Brand": {
          "Id": "versace_c45b fd",
          "Name": "VERSACE"
        },
        "Active": true,
        "ProductPageUrl": "https://www.sephora.fr/p/eros-pour-femme---eau-de-toilette-359845.html",
        "Disabled": false,
        "ISBNs": [],
        "FamilyIds": [],
        "UPCs": [],
        "StoryIds": [],
        "ModelNumbers": [],
        "Attributes": {},
        "QuestionIds": [],
        "AttributesOrder": [],
        "ReviewIds": [],
        "ManufacturerPartNumber s": [],
        "QAStatistics": {
          "QuestionHelpfulVoteCount": 0,
          "FirstAnswerTime": "None",
          "LastQuestionAnswerTime": "None",
          "FirstQuestionTime": "None",
          "FeaturedAnswerCount": 0,
          "LastAnswerTime": "None",
          "TagDistribution": {},
          "ContextDataDistribution": {},
          "TotalAnswerCount": 0,
          "FeaturedQuestionCount": 0,
          "LastQuestionTime": "None",
          "Question NotHelpfulVoteCount": 0,
          "BestAnswerCount": 0,
          "TagDistributionOrder": [],
          "AnswerHelpfulVoteCount": 0,
          "HelpfulVoteCount": 0,
          "AnswerNotHelpfulVoteCount": 0,
          "Total QuestionCount": 0,
          "ContextDataDistributionOrder": []
        },
        "TotalQuestionCount": 0,
        "TotalAnswerCount": 0,
        "ReviewStatistics": {
          "ContextDataDistributionOrder": [
            "Gender ",
            "Age",
            "Eyes",
            "Skin",
            "loyalty"
          ],
          "ContextDataDistribution": {
            "Gender": {
              "Id": "Gender",
              "Values": [
                {
                  "Count": 7,
                  "Value": "Female"
                }
              ]
            },
            "Age": {
              "Id": "Age",
              "Valu es": [
                {
                  "Count": 1,
                  "Value": "13to17"
                },
                {
                  "Count": 2,
                  "Value": "18to24"
                },
                {
                  "Count": 1,
                  "Value": "25to34"
                },
                {
                  "Count": 1,
                  "Value": "35to44"
                },
                {
                  "Count": 1,
                  "Value": "45to 54"
                },
                {
                  "Count": 1,
                  "Value": "plus54"
                }
              ]
            },
            "Eyes": {
              "Id": "Eyes",
              "Values": [
                {
                  "Count": 2,
                  "Value": "Marrons"
                },
                {
                  "Count": 3,
                  "Value": "Bleus"
                },
                {
                  "Count": 1,
                  "Value": "N oirs"
                }
              ]
            },
            "Skin": {
              "Id": "Skin",
              "Values": [
                {
                  "Count": 1,
                  "Value": "Normale"
                },
                {
                  "Count": 2,
                  "Value": "Seche"
                },
                {
                  "Count": 2,
                  "Value": "Mixte"
                },
                {
                  "Count": 1,
                  "Value": " Deshydratee"
                }
              ]
            },
            "loyalty": {
              "Id": "loyalty",
              "Values": [
                {
                  "Count": 2,
                  "Value": "Yes--Im-a-VIB"
                },
                {
                  "Count": 2,
                  "Value": "Yes--Im-a-VIB-Rouge"
                },
                {
                  "Count": 2,
                  "Value": "No"
                }
              ]
            }
          },
          "AverageOverallRating": 4.428571428571429,
          "NotHelpfulVoteCount": 1,
          "FeaturedReviewCount": 0,
          "NotRecommendedCount": 1,
          "HelpfulVoteCount": 19,
          "RatingDis tribution": [
            {
              "RatingValue": 5,
              "Count": 5
            },
            {
              "RatingValue": 2,
              "Count": 1
            },
            {
              "RatingValue": 4,
              "Count": 1
            }
          ],
          "RecommendedCount": 5,
          "RatingsOnlyReviewCount": 0,
          "To talReviewCount": 7,
          "FirstSubmissionTime": "2017-05-28T22:46:00.000+00:00",
          "LastSubmissionTime": "2020-03-21T19:01:26.000+00:00",
          "SecondaryRatingsAveragesOrder": [],
          "SecondaryRatingsAverages": {},
          "OverallRatingRange": 5,
          "TagDistributionOrder": [],
          "TagDistribution": {}
        },
        "TotalReviewCount": 7,
        "FilteredQAStatistics": {
          "Ques tionHelpfulVoteCount": 0,
          "FirstAnswerTime": "None",
          "LastQuestionAnswerTime": "None",
          "FirstQuestionTime": "None",
          "FeaturedAnswerCount": 0,
          "LastAnswerTime": "None",
          "TagD istribution": {},
          "ContextDataDistribution": {},
          "TotalAnswerCount": 0,
          "FeaturedQuestionCount": 0,
          "LastQuestionTime": "None",
          "QuestionNotHelpfulVoteCount": 0,
          "Best AnswerCount": 0,
          "TagDistributionOrder": [],
          "AnswerHelpfulVoteCount": 0,
          "HelpfulVoteCount": 0,
          "AnswerNotHelpfulVoteCount": 0,
          "TotalQuestionCount": 0,
          "ContextDat aDistributionOrder": []
        },
        "FilteredReviewStatistics": {
          "ContextDataDistributionOrder": [
            "Gender",
            "Age",
            "Eyes",
            "Skin",
            "loyalty"
          ],
          "ContextDataDistribution": {
            "Gen der": {
              "Id": "Gender",
              "Values": [
                {
                  "Count": 7,
                  "Value": "Female"
                }
              ]
            },
            "Age": {
              "Id": "Age",
              "Values": [
                {
                  "Count": 1,
                  "Value": "13to17"
                },
                {
                  "Count": 2,
                  "Value": "18to24"
                },
                {
                  "Count": 1,
                  "Value": "25to34"
                },
                {
                  "Count": 1,
                  "Value": "35to44"
                },
                {
                  "Count": 1,
                  "Value": "45to54"
                },
                {
                  "Count": 1,
                  "Value": "plus54"
                }
              ]
            },
            "Eyes": {
              "Id": "Eyes",
              "Value s": [
                {
                  "Count": 2,
                  "Value": "Marrons"
                },
                {
                  "Count": 3,
                  "Value": "Bleus"
                },
                {
                  "Count": 1,
                  "Value": "Noirs"
                }
              ]
            },
            "Skin": {
              "Id": "Skin",
              "Values": [
                {
                  "Count": 1,
                  "Value": "Nor male"
                },
                {
                  "Count": 2,
                  "Value": "Seche"
                },
                {
                  "Count": 2,
                  "Value": "Mixte"
                },
                {
                  "Count": 1,
                  "Value": "Deshydratee"
                }
              ]
            },
            "loyalty": {
              "Id": "loyalty",
              "Values": [
                {
                  "Count": 2,
                  "Value": "Yes--Im-a-VIB"
                },
                {
                  "Count": 2,
                  "Value": "Yes--Im-a-VIB-Rouge"
                },
                {
                  "Count": 2,
                  "Value": "No"
                }
              ]
            }
          },
          "AverageOverallRating": 4.428571428571429,
          "NotHelpfulVoteCo unt": 1,
          "FeaturedReviewCount": 0,
          "NotRecommendedCount": 1,
          "HelpfulVoteCount": 19,
          "RatingDistribution": [
            {
              "RatingValue": 5,
              "Count": 5
            },
            {
              "RatingValue": 2,
              "Count ": 1
            },
            {
              "RatingValue": 4,
              "Count": 1
            }
          ],
          "RecommendedCount": 5,
          "RatingsOnlyReviewCount": 0,
          "TotalReviewCount": 7,
          "FirstSubmissionTime": "2017-05-28T22:46:00.000+00 :00",
          "LastSubmissionTime": "2020-03-21T19:01:26.000+00:00",
          "SecondaryRatingsAveragesOrder": [],
          "SecondaryRatingsAverages": {},
          "OverallRatingRange": 5,
          "TagDistri butionOrder": [],
          "TagDistribution": {}
        }
      }
    ],
    "Includes": {},
    "HasErrors": false,
    "Errors": []
  },
  "d": {
    "attributs": {
      "Doux": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Délicat": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Elegant": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Mature": {
        "claimed_benefit": 0,
        " perceived_benefit": 0
      },
      "Sexy": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Féminin": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Frais": {
        "claimed_ benefit": 0,
        "perceived_benefit": 0.14285714285714285
      },
      "Classe": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Mou": {
        "claimed_benefit": 0,
        "perceived_benefit": 0.14285714285714285
      },
      "Décontracté": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Comme les autres": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Jeu ne femme": {
        "claimed_benefit": 1,
        "perceived_benefit": 0.14285714285714285
      },
      "charmant": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Gai": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Propre": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Eté": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Rafraîchissant ": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Chaud": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Masculin": {
        "claimed_benefit": 0,
        "perceived_benefit ": 0
      },
      "Fiable": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Mystérieux": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Furtif": {
        "claimed_benefit": 0,
        "perceived_benefit": 0.14285714285714285
      },
      "Fort": {
        "claimed_benefit": 0,
        "perceived_benefit": 0.14285714285714285
      },
      "Hivernal": {
        "claimed_benefit": 0,
        "perceived_ benefit": 0
      },
      "Herbacé": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Plantes": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Big brands": {
        "claimed_be nefit": 0,
        "perceived_benefit": 0
      },
      "Luxueux": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      },
      "Connu": {
        "claimed_benefit": 0,
        "perceived_benefit": 0.2857142857142857
      },
      "A la mode": {
        "claimed_benefit": 0,
        "perceived_benefit": 0
      }
    }
  },
  "total": 0
}

A: Instead of using square bracket notations, Django Template Language uses dots. So the result should be: {{ element.q0.Results.0.Name }}


text:
Q: Publishing of JS files on tomcat in eclipse I want my javascript files to publish automatically when I change them. The problem I am facing is when I keep the Publishing settings to "Never publish automatically", eclipse does not publish anything (which looks to be expected) . But when I keep the settings to "Automatically publish when resource changes", it publishes js files and restarts the server as soon as I change a java file to make the java changes effective. I end up waiting for 2-3 mins of server startup time for my project. In such a scenario both settings are appearing to be not useful to me.
Is there any setting by which I can avoid the java changes to get effective till the server is restarted but the JS changes start appearing without a restart ?

A: Yes, keep the publish resources option and disable "Modules auto reload by default" from the "Server Options" section in the same view (bottom).


text:
Q: How to shift hue of a color to opposite direction i am not very proficient with shaders this is my attempt to write a shader which picks certain color and shfits the hue in opposite direction.
// convert to  YCC color model color
vec2 RGBToCC(vec4 rgba) {
    float Y = 0.299 * rgba.r + 0.587 * rgba.g + 0.114 * rgba.b;
    return vec2((rgba.b - Y) * 0.565, (rgba.r - Y) * 0.713);
}

vec2 RGBAToCC (float r, float g, float b) {

    float y = 0.299 * r + 0.587 * g + 0.114 * b;
    return vec2((b - y) * 0.565, (r - y) * 0.713);
}

void main() {
        texture2D( tex , uvCoord );
        vec4 src1Color = texture2D(u_tex,  texCoord);
            keyCC = RGBAToCC( colorToPick.r , colorToPick.g , colorToPick.b  );
            vec2 CC = RGBToCC(src1Color);
            float myCol = sqrt(pow(keyCC.x - CC.x, 2.0) + pow(keyCC.y - CC.y, 2.0));
            myCol = smoothstep(range.x, range.y, mask);
         if (myCol == 0.0)
        {
                         // i want to shift the hue of the color to opposite direction
                        // if it is green than shift it toward magenta

        }
}

I am able to pick the color but i am not able to understand how to shift the hue of the color to opposite direction.

A: In the YCbCr color space the two C… components are color balance values with values in the range [-1,1]. Hue inversion is as simple as flipping the sign of the color component vector, i.e. with the variables in your code CC = -CC;


text:
Q: Filter WooCommerce email shipping text value I'm attempting to use the 'woocommerce_order_shipping_to_display' filter to show 'Free' in the WooCommerce email table when no shipping charges will be incurred. In the image, I'm trying to get 'Flat Rate' to display as 'Free'. My PHP is moderate, and I can't get my code quite there. Does anyone see what I could be missing?
My function breaks the actual email so I can't see if it's working or not. When the function is in place, and I resend a processing email, instead of resending, it opens in the same browser window without anything below the main email body table data (screenshot).
/* return custom text on email when shipping is free */
add_filter( 'woocommerce_order_shipping_to_display', 'filter_email_shipping_text', 10, 2 );
function filter_email_shipping_text( $shipping, $this ) {
  global $woocommerce;
  if ( $this->get_shipping_method() ) {
    $shipping = __( 'Free', 'woocommerce' );
  }
  return $shipping;
}

Shipping Email
Broken Post Attempt
UPDATED
I've scavenged for a few similar cases, and I've rewritten the function below. This still doesn't work, but I think I needed to initialise the WC_Order class to tell the function which order to reference. Can anyone help me finish it off?
/* return custom text on email when shipping is free */
add_filter( 'woocommerce_order_shipping_to_display', 'filter_email_shipping_text', 10 );
function filter_email_shipping_text( $shipping ) {
  global $wcdn;
  $order = new WC_Order($wcdn->print->order_id);
  if ( $order->get_shipping_method() || $order->order_shipping = 0 ) {
    $shipping = sprintf(__( 'Free', 'woocommerce' ));
  }
  return $shipping;
}

CONCLUSION
I was able to fix my function and it now works how intended. This is the working function and filter in case anyone need to replicate.
/* return custom text on email when shipping is free */
add_filter( 'woocommerce_order_shipping_to_display', 'filter_email_shipping_text', 10, 2 );

function filter_email_shipping_text( $shipping, $order_id ) {
  global $woocommerce, $post;
  $order = new WC_Order( $order_id );
  if ( $order->order_shipping == 0 ) {
    $shipping = sprintf(__( 'Free!', 'woocommerce' ));
  }
  return $shipping;
}


text:
Q: Is there a code style or design for cross-platform without #ifdef preprocessing (C++17)? I am currently editing Windows Cpp codes for Linux.
But, the way I know
example 1
template <typename T>
static off_t SetFilePointerU(T handle, unsigned int fileOffset, const int flag)
{
#ifdef _WIN32

    return ::SetFilePointer(static_cast<void*>(handle), fileOffset, NULL, flag);

#elif __linux__

    return lseek(handle, fileOffset, flag);

#endif
}
template <typename T>
static unsigned long ReadFileU(T handle, void* readBuffer, const int readSize = READ_BUFFER_SIZE)
{
#ifdef _WIN32

    DWORD outReadSize;

    if (!::ReadFile(static_cast<void*>(handle), readBuffer, readSize, &outReadSize, NULL))
    {

    }

    return outReadSize;

#elif __linux__

    return read(handle, readBuffer, readSize);

#endif
}

example2
#ifdef __linux__
            std::wstring u16FilePath{ updateInfo.strFilePath.begin(), updateInfo.strFilePath.end() };
            std::wstring u16FileName{ updateInfo.strFileName.begin(), updateInfo.strFileName.end() };
            auto pathList = deSerializer.GetRealPaths(u16FilePath);
#elif _WIN32
            auto pathList = deSerializer.GetRealPaths(updateInfo.strFilePath);
#endif

            for (auto& path : pathList)
            {
#ifdef __linux__
                std::u16string u16toWstringPath{ path.begin(),path.end() };
                updateInfo.strFilePath = u16toWstringPath;
#elif _WIN32
                updateInfo.strFilePath = path;
#endif
                if (updateInfo.updateType == 0)
                {
#ifdef __linux__
                    path.append(u16FileName);
#elif _WIN32
                    path.append(updateInfo.strFileName);
#endif
                    std::transform(path.begin(), path.end(), path.begin(), tolower);
                    updateDatInfos.emplace(path, updateInfo);
                }
                else
                {
#ifdef _WIN32
                    updateDatInfofilePath = updateInfo.strFilePath;
                    updateDatInfofilePath += L"\\";
                    updateDatInfofilePath += updateInfo.strFileName;
                    std::filesystem::remove(updateDatInfofilePath);
#elif __linux__
                    std::u16string u16UpdateDatInfofilePath{ updateInfo.strFilePath.begin(), updateInfo.strFilePath.end() };
                    u16UpdateDatInfofilePath += u"/";
                    u16UpdateDatInfofilePath += updateInfo.strFileName;
                    std::filesystem::remove(u16UpdateDatInfofilePath);
#endif

This is the same way as above.
I think that there is a lot of preprocessing in the code, and the readability may decrease in the future.
Are there other methods for cross-platform development?
Q)I am using ifdef in several places in my code.
But I don't want to use #ifdef in multiple places in multiple files.
Is there any other good way?


text:
Q: Where do I post a question about Microsoft Live Meeting crashing? And should I even post it? My question initially was going to be where to post a general question about stack exchange (namely, where to post a question on a particular topic). Then I found this post (and subsequently just found the same thing addressed in the FAQ), so I decided to post here.
SuperUser seems to be the closest website but I wasnt sure if my topic was ok. It has to do with software (Microsoft Live Meeting crashing when sharing out a Windows 7 VM) but I wanted to make sure since I didnt find any others like that in a quick search of the site and questions about "software" (via the site FAQ) seems really broad. Also, more candidly I'm afraid of being rebuked/policed by somebody who wants to up their repuation/points/score/counts in this game, so I figured maybe I should ask if this place is appropriate to ask my question before I ask my question. Unfortunately you need 5 reputation to post on that meta, but none on this one and that's why I'm posting here (I'm sure somebody can link me to a post as to why that is as well).
The second part to my question is whether I should even post my "question" to begin with. SO has been an invaluable resource to me so I like to add to the vast repository of information on SE. Recently I was having a problem (with Live Meeting crashing) for which I couldnt find a solution online. I found the solution myself (or rather I found the root cause and remedied it). I would like to tell the world (internet) my problem and how I fixed it. So I dont have a question, I have a solution. I could put it on a blog, but I dont blog. I could put it in the form of a question, and then answer my own question (which is what I plan to do) but I feel there should be some place where I can just post solution to problems that you find on your own. Stack Exchange doesnt appear to be it, but maybe somebody can offer an alternative?

A: Ask the question on SuperUser, then answer it yourself.  This is all fine and good.
The only problem you might get with your question is that it could be seen as "too localized".  Program crashes are caused by problems with an individual's setup about as much as known issues.  I'm guessing.  Maybe.
If someone (or many someones) close your question as too localized, your ego should be able to handle it.  If not, please exit the Internet at the nearest point of egress.


text:
Q: How can we pass variable in oscmd command in sas I am using oscmd command to run some operating system operation from sas, but want to make it generic by passing the varible in oscmd command.
I am using below code:
%global name =skstar; filename oscmd pipe "python test.py --inputvar=&name.";
The value of variable'name'is not replace in command.
EDIT: the above part is working now , its just a quotation mistake. but wanted to know the way to abort the oscmd cli command ,if in case parameter value passed is wrong

A: maybe your datastep is wrong but you not write there. It's work fine:
%let name=test words;
filename oscmd pipe "echo &name.";

data _null_;
 infile oscmd;
 input;
 put _infile_;
run;

/*log:
NOTE: The infile OSCMD is:
      Unnamed Pipe Access Device,
      PROCESS=echo test words,RECFM=V,LRECL=32767

test words
NOTE: 1 record was read from the infile OSCMD.
      The minimum record length was 10.
      The maximum record length was 10.
NOTE: DATA statement used (Total process time):
      real time           0.18 seconds
      cpu time            0.03 seconds

*/


text:
Q: Python - get elapsed time using datetime With the datetime module, I can get the current time, like so:
>>> datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2017-08-29 23:01:32'

I have access to the time at which a file was created, in the same format:
>>> data['created']
'2017-08-29 20:59:09'

Is there a way, using the datetime module, that I can calculate the time between the two, in hours?

A: Performing subtraction on two datetime objects will result in a timedelta. You can use datetime.strptime to get that second datetime object, access the seconds attribute of that timedelta and calculate the hours from there:
from datetime import datetime

...

file_created = datetime.strptime(data['created'], '%Y-%m-%d %H:%M:%S')
difference = (datetime.now() - file_created).seconds

print("Hours since creation: " + str(difference // 3600)) # 3600 seconds in 1 hour


text:
Q: How to show collection list in firestore? There are documents in the collection,
There is a collection in that document,
The collection contains documents, and the documents contain values.
.
This is the structure.
Collection> Document> Collection> Document> id:aa / age:20 /....
.
How do I see the collection list contained in a document in the first collection?
I want to know the list of collections in the 3rd digit.

A: You can list subcollections using server-side SDKs, for example in Node.JS (from the doc):
firestore.doc('col/doc').listCollections().then(collections => {
  for (let collection of collections) {
    console.log(`Found subcollection with id: ${collection.id}`);
  }
});

On the other hand, client and mobile SDKs cannot list subcollections, as described in this answer, and this one. You would need to either store the subcollections' names in a document field, or use predictable subcollection names.


text:
Q: Python Selenium: Firefox set_preference to overwrite files on download? I am using these Firefox preference setting for selenium in Python 2.7:
ff_profile = webdriver.FirefoxProfile(profile_dir)

ff_profile.set_preference("browser.download.folderList", 2)
ff_profile.set_preference("browser.download.manager.showWhenStarting", False)
ff_profile.set_preference("browser.download.dir", dl_dir)
ff_profile.set_preference('browser.helperApps.neverAsk.saveToDisk', "text/plain, application/vnd.ms-excel, text/csv, text/comma-separated-values, application/octet-stream")

With Selenium, I want to recurringly download the same file, and overwrite it, thus keeping the same filename – without me having to confirm the download.
With the settings above, it will download without asking for location, but all downloads will creates duplicates with the filename filename (1).ext, filename (2).ext etc in MacOS.
I'm guessing there might not be a setting to allow overwriting from within Firefox, to prevent accidents(?).
(In that case, I suppose the solution would be to handle the overwriting on the disk with other Python modules;  another topic).

A: This is something that is out of the Selenium's scope and is handled by the operating system.
Judging by the context of this and your previous question, you know (or can determine from the link text) the filename beforehand. If this is really the case, before hitting the "download" link, make sure you remove the existing file:
import os

filename = "All-tradable-ETFs-ETCs-and-ETNs.xlsx"  # or extract it dynamically from the link
filepath = os.path.join(dl_dir, filename)
if os.path.exists(filepath):
    os.remove(filepath)


text:
Q: PostgreSQL query takes 100x longer when I make the WHERE clauses more restrictive, counterintuitively I have a PostgreSQL query that's taking more than 15 seconds. When I change some of the values in the WHERE clauses, the query goes over 100x faster, even though the changes broaden the scope of the query.
Query #1 takes 15.2 seconds: SELECT p.category_id, count(*) FROM cr JOIN p ON p_id = p.id WHERE p.category_id = 48 AND cr.created_date > '2019-08-23 21:00:00 +0000' GROUP BY p.category_id;
Query #2 takes 44 milliseconds: SELECT p.category_id, count(*) FROM cr JOIN p ON p_id = p.id WHERE p.category_id = 48 AND cr.created_date > '2017-08-23 21:00:00 +0000' GROUP BY p.category_id; The only change is to created_date, where I've included two more years worth of cr rows, yet the query is super fast.
Query #3 takes 292 milliseconds: SELECT p.category_id, count(*) FROM cr JOIN p ON p_id = p.id WHERE p.category_id < 49 AND cr.created_date > '2019-08-23 21:00:00 +0000' GROUP BY p.category_id;. The only change from query #1 is to category_id, where I've included 47 more possible ids (1-48 instead of just 48), yet the query is still far faster than the original.
I'm at a loss. Queries #2 and #3 should be much more time-consuming, but it's only the first one that takes a long time.
Edit:
Here's the output when I do EXPLAIN (ANALYZE, BUFFERS) SELECT ... with query #1:
GroupAggregate  (cost=289.67..301.73 rows=1 width=12) (actual time=19075.641..19075.642 rows=1 loops=1)
  Group Key: p.category_id
  Buffers: shared hit=606998
  ->  Nested Loop  (cost=289.67..301.71 rows=1 width=4) (actual time=10.354..19069.554 rows=14609 loops=1)
        Buffers: shared hit=606998
        ->  Index Scan using _idx_category_id on p  (cost=0.42..8.44 rows=1 width=8) (actual time=0.018..3.676 rows=2642 loops=1)
              Index Cond: (category_id = 48)
              Buffers: shared hit=544
        ->  Bitmap Heap Scan on cr  (cost=289.25..293.26 rows=1 width=4) (actual time=7.203..7.211 rows=6 loops=2642)
              Recheck Cond: ((p_id = p.id) AND (created_date > '2019-08-23 21:00:00+00'::timestamp with time zone))
              Heap Blocks: exact=14591
              Buffers: shared hit=606454
              ->  BitmapAnd  (cost=289.25..289.25 rows=1 width=0) (actual time=7.199..7.199 rows=0 loops=2642)
                    Buffers: shared hit=591863
                    ->  Bitmap Index Scan on cr_p_id_index  (cost=0.00..9.88 rows=193 width=0) (actual time=0.006..0.006 rows=6 loops=2642)
                          Index Cond: (p_id = p.id)
                          Buffers: shared hit=7981
                    ->  Bitmap Index Scan on cr_created_date_index  (cost=0.00..276.71 rows=9637 width=0) (actual time=7.189..7.189 rows=79774 loops=2642)
                          Index Cond: (created_date > '2019-08-23 21:00:00+00'::timestamp with time zone)
                          Buffers: shared hit=583882
Planning time: 0.431 ms
Execution time: 19075.698 ms

And here it is for query #2:
GroupAggregate  (cost=0.85..720.03 rows=1 width=12) (actual time=31.628..31.630 rows=1 loops=1)
  Group Key: p.category_id
  Buffers: shared hit=24780
  ->  Nested Loop  (cost=0.85..719.92 rows=20 width=4) (actual time=0.024..27.561 rows=16281 loops=1)
        Buffers: shared hit=24780
        ->  Index Scan using _idx_category_id on p  (cost=0.42..8.44 rows=1 width=8) (actual time=0.015..1.883 rows=2642 loops=1)
              Index Cond: (category_id = 48)
              Buffers: shared hit=544
        ->  Index Scan using cr_p_id_index on cr  (cost=0.43..709.55 rows=193 width=4) (actual time=0.002..0.007 rows=6 loops=2642)
              Index Cond: (p_id = p.id)
              Filter: (created_date > '2017-08-23 21:00:00+00'::timestamp with time zone)
              Buffers: shared hit=24236
Planning time: 0.251 ms
Execution time: 31.663 ms

And here it is for query #3:
HashAggregate  (cost=52583.40..52583.67 rows=27 width=12) (actual time=389.141..389.150 rows=22 loops=1)
  Group Key: p.category_id
  Buffers: shared hit=89513, temp read=1187 written=1173
  ->  Hash Join  (cost=20169.93..52535.14 rows=9651 width=4) (actual time=235.938..363.334 rows=79992 loops=1)
        Hash Cond: (cr.p_id = p.id)
        Buffers: shared hit=89513, temp read=1187 written=1173
        ->  Index Scan using cr_created_date_index on cr  (cost=0.43..30914.94 rows=9651 width=4) (actual time=0.010..50.387 rows=79992 loops=1)
              Index Cond: (created_date > '2019-08-23 21:00:00+00'::timestamp with time zone)
              Buffers: shared hit=78529
        ->  Hash  (cost=14955.75..14955.75 rows=317740 width=8) (actual time=235.394..235.394 rows=321138 loops=1)
              Buckets: 131072  Batches: 8  Memory Usage: 2608kB
              Buffers: shared hit=10984, temp written=957
              ->  Seq Scan on p  (cost=0.00..14955.75 rows=317740 width=8) (actual time=0.010..127.499 rows=321138 loops=1)
                    Filter: (category_id < 49)
                    Rows Removed by Filter: 3
                    Buffers: shared hit=10984
Planning time: 0.241 ms
Execution time: 389.209 ms

A:
->  Index Scan using _idx_category_id on p  (cost=0.42..8.44 rows=1 width=8) (actual time=0.015..1.883 rows=2642 loops=1)

When the estimated number of rows is off by a factor of 2642, bad plans will happen.
If you ANALYZE the table (ANALYZE P;), does that fix the problem?  If so, then you have to wonder why the autovacuum system was not doing an autoanalyze on it.

A: There are multiple reasons you see this difference. Following are few example.

*

*If you run the same query more than one time then there is a possibility result will be given from cache. So please do slight change (at least in add/remove few seconds in date value used in query) in query and check.

*Number of matching rows will increase the time taken.

You can check the performance by explain method in postgres. It will return appropriate result, you need compare cost return by this explain method. This is the best way to compare query results.
Ref: https://www.postgresql.org/docs/9.3/sql-explain.html
You can improve the query by following ways very soon.

*

*Add appropriate index based on column type (date, string) and operator (=, like, ~=) you have used. Postgres have different indexes, you can use those based on situation. If you want to use date type column in index then use brin index which is specially intended for date related querying. If you want to check equality the or like then use btree index. If you did not add index then it will search whole table when you querying. When you adding index it will fasten by search based on appropriate index.

*Try to use batch processing. Get specific no of rows (1000 rows) at same time instead of loading all records at same time. If you load all records at same time
then it will create memory related issue and it will take much time to load all  data.

*Increase your postgres default configuration like suggested in following page based on your machine configuration. It will also help you to improve the performance.
https://pgtune.leopard.in.ua/#/