text:
Q: In a Postgres transaction, what is the best way to delete if exists, and fail otherwise? In Postgres, I want to do a bunch of deletes and writes in a transaction, but I want to fail the transaction if a row I am intending to delete does not exist. What is the best way to do this?

A: Use a PL/pgSQL code block (in a FUNCTION, PROCEDURE or DO statement) and raise an exception if your DELETE did not find any rows. You can use the special variable FOUND:
DO
$do$
BEGIN
   DELETE FROM tbl1 WHERE id = 1;

   IF NOT FOUND THEN
      RAISE EXCEPTION 'Failed to delete!';
   END IF;

   INSERT INTO tbl2 (col1) VALUES ('foo');
END
$do$;

Raising an exception rolls back the whole transaction.
The manual:

Note in particular that EXECUTE changes the output of GET DIAGNOSTICS, but does not change FOUND.

See:

*

*Dynamic SQL (EXECUTE) as condition for IF statement

A: This idea will cause an exception if no row is deleted:
delete from mytable
where id = 123
and 1/(select count(*) from mytable where id = 123) > 0

This works by the subquery, which should have the same where clause as the delete's where clause, returning 0 if there are no matching row(s) to delete, which causes a divide by zero error that will automatically fail the transaction causing a rollback of all work.


text:
Q: Package 'octave-octcdf' has no installation candidate (Ubuntu 18 LTS) I need to install octave-octcdf package to work with Octave. I tried, sudo apt-get install -y octave-octcdf. But this receives an error as following;
user@PowerEdge-R540:~/user/tools$ sudo apt-get install -y octave-octcdf
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package octave-octcdf is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'octave-octcdf' has no installation candidate

Can anyone help to properly install octave-octcdf package?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery fancybox won't open div I'm trying to get a form to pop up when the Auto Loan Calculator link at the bottom of  this page is clicked.
The function call I am making looks like this
$(window).load(function() {
    $('#auto-calc-link').click(function(){
        $.fancybox.open($('#auto-loan-container'));
    });
});

The head section is a bit of a mess at the moment, but the files for the fancybox are definitely linked... Console isn't spitting anything out so I don't know where to go.

A: Try this.
$(document).ready(function() {
        $(".fancybox").fancybox({
            type: "iframe",
            helpers   : {
      overlay : {
      closeClick: false}
      // prevents closing when clicking OUTSIDE fancybox
      },
      closeClick  : false, // prevents closing when clicking INSIDE fancybox
      scrolling     : 'no',
      width         : 550,
      height        : 0,
      autoScale     : true,
      openEffect    : 'elastic',
      closeEffect   : 'fade',
      closeBtn : true,

        }).trigger("onclick");

    });

And you should have this link below.


text:
Q: Is there any faster way to perform group by row counts using two table in mysql? I am trying to find the total number of outlets(nation_id wise) that exist in the orders table in a given date range.
select  o2.nation_id,count(o2.id) as outlet_count
    from  outlets o2
    where  o2.id in (
        SELECT  distinct o.outlet_id
            from  orders o
            where  order_date >= '2022-05-01 00:00:00'
              and  order_date <= '2022-06-30 23:59:59'
                    )
    group by  o2.nation_id ```

Now, this query gives the exact result but it takes around 3 seconds. Is there any way to perform this query faster? Probably less than 1 second.
N.B.: Outlets table contains around 25k data and orders table contains around 1.2M rows.

A: Avoiding IN will boost the performance and creating indices for nation_id & id columns in outlets table and outlet_id column of orders table will definitely improve the speed.
select  o2.nation_id,  count(Ord.outlet_id) as outlet_count
from  outlets o2
LEFT JOIN
    (
    SELECT  distinct o.outlet_id
        from  orders o
        where  order_date >= '2022-05-01 00:00:00'
          and  order_date <= '2022-06-30 23:59:59'
    ) Ord ON o2.id = Ord.outlet_id
group by  o2.nation_id

A: Give this a try.  It's something tricky that I just invented and tested (on different tables):
SELECT  ou.nation_id, COUNT(*) AS outlet_count
    FROM ( SELECT o.outlet_id, MIN(order_date)
               FROM orders AS o
               WHERE o.order_date >= '2022-05-01'
                 AND o.order_date  < '2022-05-01' + INTERVAL 1 MONTH
               GROUP BY o.outlet_id
         ) AS olist
    JOIN outlets AS ou  ON ou.id = olist.outlet_id
    GROUP BY ou.nation_id

The GROUP BY together with the MIN (or MAX, etc) is a trick to get the Optimizer to hop through the index, touching only one row per outlet_id.  Leaving out the MIN or changing to DISTINCT failed to involve the optimization.  (Caveat:  Different versions of MySQL/MariaDB may work differently here.)
orders:  INDEX(outlet_id, order_date)  -- required for the trick

If there are any issues, please provide SHOW CREATE TABLE and EXPLAIN SELECT ...


text:
Q: Update ANN's training set Assume an ANN has trained by 1GB size training data using a long time.
Do we need  train the data again when just a few rows in the training data changed?
or is the design of  ANN  error?

A: In general, the answer would be yes. Here's why...
First of all, 1GB of training data is a relative measure, since it gives no indication of the number of training samples. Perhaps each training sample is 1MB in size (maybe an image), leaving you with only about 1,000 samples which may not be enough.
Secondly, it is important to know the architecture of the neural network in order to address the question of retraining fully. If the components in your training set that was updated correspond to nodes that may be heavily influenced in terms of the usage, then a retrain is most certainly in order. Of course, the converse is not necessarily true, as it may not be immediately apparent how the interconnectedness of neural network may be influenced by a change in the input.
Thirdly, a neural network is meant to represent a type of complex pattern-matcher, trained to recognize some input relationship, and produce a possible output relationship. From this naive point of view, a change in input should surely correspond to a change in output. As such, a change in the training data may very well correspond to a change in the expected output data. And, even if it doesn't, the input pattern has changed, which may imply that the output pattern also changed.
Let's consider the following example. Assume your neural network is trained to match paintings with artists and it's been success in making the following match to Leonardo da Vinci:

Now it may be trained well enough to also assert that the following images are "painted" by the same artist:

This may be because you trained your neural network on your favourite past-time of balloon an Lego figurines. However, now a number of your input samples change, specifically those associated with the Mona Lisa. Instead they resemble your new favourite past-time... freehand mouse-drawing:

Despite what you say, in general the artistry of the above image doesn't really match that of the earlier ones. As such, your pattern-matcher may not appropriately recognize this as a piece of art made by Leonardo da Vinci. So it's fair to say that retraining it on images of this sort should be in order.

You probably have a number of options:

*

*Test how effective it is to retrain your neural network given the change in training data. That would allow you to answer the question yourself, and give some insight into the architecture of your neural network.

*Retrain your neural network on just the changes, which could be considered new training data. The value of this might depend heavily on your architecture, the complexity of the samples as well as the training quantity (not size).

*Perform a complete retrain and test the efficacy.


text:
Q: how to get first row and last column in nested loop Scanner scanner = new Scanner(System.in);
        System.out.print("Masukkan nilai : ");
        int input = scanner.nextInt();
        int kolom = input -1;
            for(int i=1;i<input;i++){
                for(int j=input;j>i;j--){
                    System.out.print("*");
                }
                System.out.println();
            }

output of code is :

but i want the output like :

so i think i need get the first row and last column
how to do that

A: Please try this
Scanner scanner = new Scanner(System.in);
System.out.print("Masukkan nilai : ");
int index = scanner.nextInt();

for (int i = 0; i < index; i++) {
    System.out.print("*");
}
System.out.println();

for (int i = 1; i < index; i++) {
    for (int j = index; j > i; j--) {
        if (j == index || j == i + 1) {
            System.out.print("*");
        } else {
            System.out.print(" ");
        }
    }
    System.out.println();
}

A: for(char c='*',i=0; i<input; c=' ',i++)
  for(int j=0; j<input-i; j++)
    System.out.print(j==0 ? "*" : j<input-i-1 ? c : "*\n");


text:
Q: EMPTY CDATA in XML <![CDATA[]]>

or

Is there a difference or downside to each? Do I need to do anything while parsing the XML? What do you prefer?

A: As far as the XML parser is concerned there is NO difference.  If you wish to force CDATA creation during XSLT output there is an option (cdata-section-elements) that can be used to cause certain elements to output CDATA.


text:
Q: Oracle nested CONNECT BY clauses causing poor performance The query below is taking about a minute. I believe the poor performance is caused by the two "IN (SELECT..." clauses. I have a table of terms where one may be connected to another via the term_relationship table. These relationships can be recursive, e.g. dog is a type of mammal, mammal is a type of animal. This recursion could be any depth but probably not more than ~10 levels. I am trying to select all terms which have a (potentially recursive) relationship with type A and have a (potentially recursive) relationship with type B. I think that replacing the two "IN (SELECT..." clauses with restrictions on the outer query would improve performance but cannot figure out how to do this using the CONNECT BY clauses. Can anyone help with this?
SELECT term_name
FROM term
WHERE term_id IN
   (SELECT term_id
    FROM term_relationship
    START WITH related_term_id = 123
    CONNECT BY NOCYCLE PRIOR term_id = related_term_id)
AND term_id IN
   (SELECT term_id
    FROM term_relationship
    START WITH related_term_id = 456
    CONNECT BY NOCYCLE PRIOR term_id = related_term_id)

A: Instead of doing the same CONNECT BY query twice with only differing start values how about you do it once by providing both start values to one instance of the subquery.  This change will get you all the term_ids related to either of your starting values, however, you want only those term_ids related to both of your starting values.  To get that, you then need to group the results by by term_id and limit to those results having a count of more than one:
SELECT term_name
  FROM term
 WHERE term_id IN
    (SELECT term_id
       FROM term_relationship
      START WITH related_term_id in (123, 456)
    CONNECT BY NOCYCLE PRIOR term_id = related_term_id
      group by term_id having count(*) >= 2)

Edit
With the above code I made an assumption about your data that may not be correct. I assumed a tree like structure where you were starting with nodes on a branch and traveling up towards the root like in diagram A, however, if your data looks like diagram B, then the above query will fail if you start at nodes 7 and 9 as node 7 has two paths back to node 1, and the above query would return node 1 twice, thereby misidentifying it as a common node.
A)   -(1)-                    B)   -(1)-
    /  |  \     (8)               /  |  \     (8)
  (2)  |  (3)    |              (2)  |  (3)    |
   |  (4)  |    (9)              |  (4)  |    (9)
  (5)     (6)                   (5)     (6)
           |                      \     /
          (7)                      -(7)-

The query below corrects for this and will correctly identify that for starting nodes 7 and 9 no nodes are in common, however, with starting nodes 7 and 4 node 1 is identified as a common node:
SELECT term_name
  FROM term
 WHERE term_id IN
    (SELECT term_id
     FROM term_relationship
    START WITH related_term_id in (123, 456)
  CONNECT BY NOCYCLE PRIOR term_id = related_term_id
    group by term_id
   having count(distinct connect_by_root related_term_id) >= 2)


text:
Q: Order confirmation page is with no information? I am using this code to redirect a payment module on order confirmation.
Tools::redirect(__PS_BASE_URI__.'order-confirmation.php?key='.$key1.'&id_cart='.$cart->id.'&id_module='.$this->module->id.'&id_order='.$this->module->currentOrder);

but i am getting a page with this link /prestashop/en/order-confirmation?key=67db4962c0c85b3241be97dcbedd869d&id_cart=301&id_module=82&id_order=265
that is with no information of order confirming at all.Can anybody help me with this to fix ?
Can anybody help me to set a template after order confirmation?
I am also attaching a screenshot.

A: If you are making a payment module you need to register two hooks:

*

*displayPayment
This hook displays your payment option's HTML at payment selection page.

*displayPaymentReturn
This hook displays your confirmation page HTML after you validate an order and redirect it to order-confirmation controller.


text:
Q: How to save the ouput of a python file using subprocess and append all those in a single file? Have a python code that generates different output everytime i run that.
How to save the all ouput that has been generated when i run that python script on loop using suprocess
Code I am using is overwriting the file not appending.

f = open("blah.txt", "w")
subprocess.call(["python","loop.py"], stdout=f)

A: Open your file in append mode ('a')
f = open("blah.txt", "a")

Mode    Description
---     ---
'r'     This is the default mode. It Opens file for reading.
'w'     This Mode Opens file for writing.
If file does not exist, it creates a new file.
If file exists it truncates the file.
'x'     Creates a new file. If file already exists, the operation fails.
'a'     Open file in append mode.
If file does not exist, it creates a new file.
't'     This is the default mode. It opens in text mode.
'b'     This opens in binary mode.
'+'     This will open a file for reading and writing (updating)

A: open file in append mode instead of write mode
and if u want error also to be logged in the same file then.

f = open("blah.txt", "a")

subprocess.call(["python","loop.py"], stdout=f,stderr=f)


text:
Q: Finding the number of solutions to $\cos^4(2x)+2\sin^2(2x)=17(1+\sin 2x)^4$ for $x\in(0,2\pi)$
Number of solution of the equation
$\cos^4(2x)+2\sin^2(2x)=17(1+\sin 2x)^4\; \forall $ $x\in(0,2\pi)$

what i try
$\cos^4(2x)+2\sin^2 2x=17(1+\sin^2(2x)+2\sin 2x)^2$
$1+\sin^4 (2x)=17(1+\sin^4 2x+2\sin^2 2x+4\sin^24x+4\sin 2x(1+\sin^2 2x))$
$16\sin^4 (2x)+68\sin^3 2x+34\sin^2 2x+68\sin 2x+68\sin^2 4x+16=0$
How do i solve it Help me please

A: Hint: Your equation is equivalent to
$$2 (\sin (2 x)+2) (2 \sin (2 x)+1) (-7 \sin (2 x)+2 \cos
   (4 x)-6)=0$$

A: You're not required to find all solutions, just to find how many there are.
Let $u=\sin(2x)$. Then the trigonometric equation in $x$ becomes a polynomial equation in $u$:
$$
0 = (1 - u)^4 + 2 u^2 - 17 (1 + u)^4 = -2 (8 u^4 + 36 u^3 + 47 u^2 + 36 u + 8)
$$
Now plot this function of $u$ and see how many solutions are in the interval $[-1,1]$ so that $u$ can be the sine of something.
The graph below tells us that there is exactly one solution in $[-1,1]$.

A: Wrong expansion jacky
$$16\sin^42x+68\sin^32x+102\sin^22x+68\sin 2x+16=0$$
$$16(\sin 2x+\csc 2x)^2+68(\sin 2x+\csc 2x)+70=0$$
$$\sin 2x +\csc 2x=-15.0479,-1.9521$$
Rejecting $-1.9521$ (Why)
Thus, $$\sin^22x+(15.0479)\sin 2x+1=0$$
Both the roots of the quadratic are negative and since their product is $1$ only one root will lie on the interval $(-1,0)$
So there should be $4$ solutions


text:
Q: Go: print URI in template files (echo framework) I'm using echo framework. I'm stuck when trying to print URI :mynumber as variable in template files.
All variable working fine except the URI :mynumber. I have no idea how to include :mynumber together with Name & Age
Below is my server.go:
package main

import (
    "github.com/labstack/echo"
    "html/template"
    "io"
    "net/http"
)

type Person struct {
    Name, Age, Mynumber string
}

type (
    Template struct {
        templates *template.Template
    }
)

func (t *Template) Render(w io.Writer, name string, data interface{}) error {
    return t.templates.ExecuteTemplate(w, name, data)
}

func main() {
    e := echo.New()

    p := Person{Name: "Mike San", Age: "35"}

    t := &Template{
        templates: template.Must(template.ParseFiles("public/views/testhere.html")),
    }
    e.Renderer(t)

    e.Get("/testing/:mynumber", func(c *echo.Context) {
        c.Render(http.StatusOK, "onlytestingtpl", p)
    })

    e.Run(":4444")
}

Below is public/views/testhere.html:
{{define "onlytestingtpl"}}My name is {{.Name}}. I'm {{.Age}} years old. My number is {{.Mynumber}}.{{end}}

For your reference, below is example is print URI without template file:
package main

import (
    "github.com/labstack/echo"
    "net/http"
)

func main() {
    e := echo.New()

    e.Get("/users/:id", func(c *echo.Context) {
        id := c.Param("id")
        c.String(http.StatusOK, "My number is "+id)
    })

    e.Run(":4444")
}

A: You simply need to retrieve it from the URL as per your working sample:
number := c.Param("mynumber")

And set it on the Person instance you're passing in:
p.Mynumber = number

Which would result in:
e.Get("/testing/:mynumber", func(c *echo.Context) {
    number := c.Param("mynumber")
    p.Mynumber = number
    c.Render(http.StatusOK, "onlytestingtpl", p)
})


text:
Q: Implementing Google Analytics for iOS As someone coming from experience with Flurry Analytics, can someone explain the correct location for implementing event tracking and custom variables in Google Analytics for iOS? The example that Google provides shoves everything into the AppDelegate. Not sure if they did that for the sake of brevity or not.I can see why the init call goes in the AppDelegate:
//AppDelegate.m
- (void)applicationDidFinishLaunching:(UIApplication *)application {

   [[GANTracker sharedTracker] startTrackerWithAccountID:@"UA-0000000-1"
                                    dispatchPeriod:kGANDispatchPeriodSec
                                          delegate:nil];

   //...

}

But what about these calls that collect specific data related to a specific view? Can they go into their respective ViewControllers instead of the AppDelegate?
[[GANTracker sharedTracker] setCustomVariableAtIndex:1
                                                   name:@"iPhone1"
                                                  value:@"iv1"
                                              withError:&error]

[[GANTracker sharedTracker] trackEvent:@"my_category"
                                   action:@"my_action"
                                    label:@"my_label"
                                    value:-1
                               withError:&error]

[[GANTracker sharedTracker] trackPageview:@"/app_entry_point"
                               withError:&error]

Questions
1) What Google Analytics for iOS calls shown above need to be in the AppDelegate?
2) What Google Analytics for iOS calls shown above can be put into the ViewControllers?
Thanks

A: You put first part into AppDelegate, that's right.
In viewDidLoad method of each viewController put:
NSError *error;

 if (![[GANTracker sharedTracker] trackPageview:@"/app_entry_point"
 withError:&error]) {
 // Handle error here
 }

where @"/app_entry_point" should be the name of ViewController, for ex.: "/mainWindow".
Next piece of code used to track for your methods, used inside methods.
     NSError *error;
     if (![[GANTracker sharedTracker] trackEvent:@"my_category"
     action:@"my_action"
     label:@"my_label"
     value:-1
     withError:&error]) {
     // Handle error here
     }


text:
Q: Is this cosmological scenario possible? Is it possible that the universe is infinitely large and contains an infinite amount of mass that is distributed in such a way that gravitational force is never infinite? If so, is it possible that the infinite amount of mass that is outside of our light cone could affect us with gravitational force?

A: Is it possible that the universe is infinitely large and contains an infinite amount of mass that is distributed in such a way that gravitational force is never infinite?
Yes, in the sense that it is possible that for each mass, the total of all the forces on it is finite. To avoid an infinite force we should avoid point sized masses, so we'll use some rigid balls of mass 1 gram and all of radius 1cm.  Then we can place one at the origin. Then 4 more in a square around it at the four corners, with a length of 2m, with the first ball at the center.  The total of the forces on the center ball is $2G$ $g^2/m^2$ (and the total force is zero since forces add like vectors).  Next we place 4 more, but on a square of 2 times the length (also centered on the first ball).  The total of the forces due to those is 1/4 as much, so $G/2$ $g^2/m^2$.  Do it again, four more masses, on a square of 2 times the length of the last one, so get 1/4 the total of the forces.
So we have the total of the forces from all the squares on the center ball is
$$ 2G g^2/m^2 (1+1/4+1/16+1/64 + \dots) = 2G (4/3) g^2/m^2 < \infty$$
And that's the mass that is closest to the most, so the total of the forces on any other ball is lower.
Basically when you through the word infinite around its hard to conclude much of anything that must happen, because there is a lot of leeway.
If so, is it possible that the infinite amount of mass that is outside of our light cone could affect us with gravitational force?
We don't know whether there is an infinite amount of mass outside our past light cone.  But something currently outside our past light cone can have an older version of itself that was inside the cone, and that can affect us.  Just like someone can write you a letter before they die but it might not get to you until after they are dead, you can still read the letter and be affected by their earlier thoughts that happened early enough to affect you now.
And again, infinite or finite wasn't the issue here for this second question.


text:
Q: Closed form solution to $\int_0^1\arctan^2(x)\,\sqrt{x}\,dx$ I need to compute this integral:
$$\int_0^1\arctan^2(x)\,\sqrt{x}\,dx$$
I tried integration by parts, and also introducing a parameter $\arctan(a\,x)$ and differentiation wrt it, but these approaches did not lead to anything useful. Please help.

A: The integrand has a closed-form antiderivative in terms of elementary functions and dilogarithms. Mathematica can find it if we help it by first converting the arctangent into a combination of logarithms:
$$\arctan(x)=\frac i2\ln(1-i x)-\frac i2\ln(1+ix)$$
After some simplifications it takes this form. Its correctness can be checked manually using direct differentiation. Plugging the integration limits and performing some simplifications, we get the same result as given by Cleo.

A: $$\frac{\pi^2}{24}-\frac{2\pi}3+\frac1{36\sqrt{2}}\left[5\pi^2+12\left(4+\ln\left(\frac{1+\sqrt2}2\right)\right)\left(\pi-2\ln\left(1+\sqrt2\right)\right)-48\operatorname{Li}_2\left(\sqrt2-1\right)\right]$$

A: The integration range is small: $[0, 1]$ so one of the method could be to use Taylor series for the $\arctan(x)$ function:
$$\arctan^2(x) = \sum_{n = 0}^{+\infty}\sum_{m = 0}^{+\infty}\frac{(-1)^n (-1)^m}{(2n+1)(2m+1)}x^{2n+1}x^{2m+1}$$
And write $\sqrt{x} = x^{\frac{1}{2}}$ to obtain:
$$I = \int_0^1\sum_{n = 0}^{+\infty} \sum_{m = 0}^{+\infty}\frac{(-1)^n (-1)^m}{(2n+1)(2m+1)}x^{2n+1}x^{2m+1} x^{\frac{1}{2}}$$
namely
$$I = \sum_{n = 0}^{+\infty} \sum_{m = 0}^{+\infty}\frac{(-1)^n (-1)^m}{(2n+1)(2m+1)}\int_0^1x^{2n+1}x^{2m+1} x^{\frac{1}{2}}$$
That will lead you to (after a trivial integration)
$$I = \sum_{n = 0}^{+\infty} \sum_{m = 0}^{+\infty}\frac{(-1)^n (-1)^m}{(2n+1)(2m+1)}\frac{1}{\left(2(n+m) + \frac{7}{2}\right)}$$


text:
Q: (System of Linear equations problem) Do I need this to solve the problem? I encountered this problem:
Farmer Joe needs to buy tools. He can go to two different stores, but only wants to go to one. At Lowes, 5 shovels and 12 clippers are 14.58. 6 shovels  and  14 clippers are also 16.50 at Lowes. At Home Depot, a shovel is $1.89 and a clipper $0.42. Joe needs to buy 8 shovels and 20 clippers, and wants the cheapest option. Where should he buy his tools from?
In this problem, is the information about how much 6 shovels and 14 clippers is in total necessary to solving this solution? Because in my mind, I found the price of 5 shovels and 12 clippers from Home Depot and compared it with the price of 5 shovels and 12 clippers from Lowes to get my answer. Is my way of thinking erroneous?

A: Consider a related but different problem where there are two stores.  The store "One Dollar Store" where everything costs one dollar, and the store "Everything Free But Shovels" where everything is free except shovels and those cost two dollars each.  From here on I'll just call these stores store $O$ and store $E$ for short.
We look at the total cost of buying two shovels and four clippers from each store and we find that it cost a total of six dollars from store $O$ and it costs a total of four dollars from store $E$.  For this particular purchase then, store $E$ has the lower total price.
Now, what if we were to purchase three shovels and two clippers?  Well, store $O$ would charge us a total of five dollars while store $E$ would charge us six dollars.  For this purchase, store $O$ has the lower total price.
Despite that store $O$ had a more expensive final bill for the first particular purchase than store $E$, having changed the amounts of things being bought store $E$ happened to have the more expensive final bill the second time around.
The same thing could potentially happen with your original problem.  Even if you were to compare which store had the cheaper total cost of the specific purchase five shovels and 12 clippers, this does not give you enough information to know which store would be the cheaper option for buying eight shovels and twenty clippers.

Given the information in the problem, you should be able to determine exactly how much an individual shovel costs at Lowes as well as exactly how much an individual pair of clippers costs at Lowes.  You are already told this information for Home Depot.  You can then using that information determine the final total for the bill of our desired purchase from each store.


text:
Q: glibc detected (memory error) on inserting into std::map I have the following code:
struct VRfile{
    char sessionID[10];
    char file[20];
    int first;
};

std::map (int ,struct VRfile *) maps;
struct VRfile *vrinfo = (struct VRfile*)malloc (sizeof(struct VRfile*));
 strcpy(vrinfo->sessionID, sessionId.c_str());
  strcpy(vrinfo->file, filename.c_str());

 socketmap.insert(std::pair(int , struct VRfile *) (thisfd,vrinfo));

I'm getting an error at the socketmap.insert(std::pair(int , struct VRfile *) (thisfd,vrinfo)); line:
Error: *** glibc detected *** memory corruption: 0x080aa7b0 ***
/lib/libc.so.6[0x6222dd]
/lib/libc.so.6(__libc_malloc+0x67)[0x623e97]
/usr/lib/libstdc++.so.6(_Znwj+0x27)[0x45d7ab7]

backtrace:
0  0x002eb402 in __kernel_vsyscall ()
1  0x005e0df0 in raise () from /lib/libc.so.6
2  0x005e2701 in abort () from /lib/libc.so.6
3  0x0061928b in __libc_message () from /lib/libc.so.6
4  0x006222dd in _int_malloc () from /lib/libc.so.6
5  0x00623e97 in malloc () from /lib/libc.so.6
6  0x045d7ab7 in operator new(unsigned int) () from /usr/lib/libstdc++.so.6

Then it points to the line of code I have mentioned above. Can nyone tell me why this is happening?

A: You're not allocating enough space for your structure—you're only allocating a pointer's worth (4 or 8 bytes, depending on your pointer size), when in fact you should be allocating somewhere on the order of 36 bytes (specifically, sizeof(VRfile).  So, you're stomping on the heap by writing random values into it (a so-called heap overrun), which is messing up the data structures used by malloc to track memory.  When it detects this corruption, it throws its hands up and terminates your program.
However, since this is C++ and not C, you should really be using operator new instead of malloc to allocate dynamic memory.  You don't have to deal with the size of the memory you're allocating, it's implicit in the variable type.  Secondly, there's no reason to always say struct VRfile instead of just VRfile—that's only needed in plain C code (not C++), and only when there isn't a proper typedef (which there usually is).
So, just write this:
VRfile *vrinfo = new VRfile;

And of course, when you delete your map (or remove any element from it, for that matter), make sure to delete each value in it to avoid leaking memory.  For example:
// This could also be implemented using a functor and std::for_each
for(std::map<int, VRfile*>::iterator iter = maps.begin(); iter != maps.end(); ++iter)
    delete iter->second;
maps.clear();

A: In your malloc call, you're allocating enough memory for a pointer to a VRfile instead of a VRfile (probably just a typo).
VRfile *vrinfo = (VRfile*)malloc(sizeof(VRfile));

Note also that in C++ you don't need to use struct when referencing the type.


text:
Q: Checkbox missing Hi guys i have problem creating my layout, previously i use this layout and it is working but today when i reopen my xml, my check box is missing, anyone have any idea that can help me solve the problem ??
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical" >

<TableLayout
    android:id="@+id/TableLayout01"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#E7FEFF" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="#FFFFF0"
            android:text="Opp SAFRA Tampines"
            android:textSize="22dp"
            android:textStyle="bold"
            android:width="1000dp" />
    </LinearLayout>

    <View
        android:layout_height="2dip"
        android:background="#FF0000" />

    <TableRow android:id="@+id/TableRow01" >

        <TextView
            android:background="#E7FEFF"
            android:text="  5"
            android:textSize="18dp" />
    </TableRow>

    <TableRow>

        <TextView
            android:id="@+id/text02"
            android:background="#E7FEFF"
            android:text="  Pasir Ris Int"
            android:textSize="15dp"
            android:width="100dp" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.1"
            android:background="#E7FEFF"
            android:checked="false" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  15:25   15:36    15:47"
            android:textSize="13dp" />
    </TableRow>

    <View
        android:layout_height="2dip"
        android:background="#FF0000" />

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:stretchColumns="2"
            android:text="  8"
            android:textSize="18dp" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  Tampines Int"
            android:textSize="15dp"
            android:width="850px" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:background="#E7FEFF"
            android:checked="false" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  15:26   15:27    15:36"
            android:textSize="13dp" />
    </TableRow>

    <View
        android:layout_height="2dip"
        android:background="#FF0000" />

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:stretchColumns="2"
            android:text="  15"
            android:textSize="18dp" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  Tampines Int"
            android:textSize="15dp"
            android:width="850px" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:background="#E7FEFF"
            android:checked="false" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  15:23   15:28    15:30"
            android:textSize="13dp" />
    </TableRow>

    <View
        android:layout_height="2dip"
        android:background="#FF0000" />

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:stretchColumns="2"
            android:text="  18"
            android:textSize="18dp" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  Tampines Int"
            android:textSize="15dp"
            android:width="850px" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:background="#E7FEFF"
            android:checked="false" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  15:30   15:31    15:34"
            android:textSize="13dp" />
    </TableRow>

    <View
        android:layout_height="2dip"
        android:background="#FF0000" />

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:stretchColumns="2"
            android:text="  21"
            android:textSize="18dp" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  Pasir Ris Int"
            android:textSize="15dp"
            android:width="850px" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:background="#E7FEFF"
            android:checked="false" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  15:23   15:26    15:39"
            android:textSize="13dp" />
    </TableRow>

    <View
        android:layout_height="2dip"
        android:background="#FF0000" />

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:stretchColumns="2"
            android:text="  23"
            android:textSize="18dp" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  Tampines Int"
            android:textSize="15dp"
            android:width="850px" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:background="#E7FEFF"
            android:checked="false" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  15:29   15:30    15:39"
            android:textSize="13dp" />
    </TableRow>

    <View
        android:layout_height="2dip"
        android:background="#FF0000" />

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:stretchColumns="2"
            android:text="  59"
            android:textSize="18dp" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  Changi Village Ter"
            android:textSize="15dp"
            android:width="850px" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:background="#E7FEFF"
            android:checked="false" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  15:20   15:31    15:45"
            android:textSize="13dp" />
    </TableRow>

    <View
        android:layout_height="2dip"
        android:background="#FF0000" />

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:stretchColumns="2"
            android:text="  65"
            android:textSize="18dp" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  Tampines Int"
            android:textSize="15dp"
            android:width="850px" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:background="#E7FEFF"
            android:checked="false" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  15:21   15:31    15:40"
            android:textSize="13dp" />
    </TableRow>

    <View
        android:layout_height="2dip"
        android:background="#FF0000" />

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:stretchColumns="2"
            android:text="  67"
            android:textSize="18dp" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  Tampines Int"
            android:textSize="15dp"
            android:width="850px" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:background="#E7FEFF"
            android:checked="false" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  15:23   15:25    15:29"
            android:textSize="13dp" />
    </TableRow>

    <View
        android:layout_height="2dip"
        android:background="#FF0000" />

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:stretchColumns="2"
            android:text="  168"
            android:textSize="18dp" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  Woodland Reg Int"
            android:textSize="15dp"
            android:width="850px" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:background="#E7FEFF"
            android:checked="false" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  15:30   15:39    15:59"
            android:textSize="13dp" />
    </TableRow>

    <View
        android:layout_height="2dip"
        android:background="#FF0000" />

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:stretchColumns="2"
            android:text="  518"
            android:textSize="18dp" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  Pasir Ris Int"
            android:textSize="15dp"
            android:width="850px" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:background="#E7FEFF"
            android:checked="false" />
    </TableRow>

    <TableRow>

        <TextView
            android:background="#E7FEFF"
            android:text="  15:21   15:39    15:55"
            android:textSize="13dp" />
    </TableRow>

    <View
        android:layout_height="2dip"
        android:background="#FF0000" />

    <TableRow>

        <ImageButton
            android:id="@+id/next"
            android:layout_width="650dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:src="@drawable/next" />
    </TableRow>
</TableLayout>

A: Remove below property from each CheckBox :
android:layout_weight

Add below properties to each TextView which is placed with CheckBox in Row :
android:layout_width="0dp"
android:layout_weight="1"

Example :
<TableRow>

   <TextView
      android:background="#E7FEFF"
      android:text="  Tampines Int"
      android:layout_width="0dp"
      android:layout_weight="1"
      android:textSize="15dp"
      android:width="850px" />

    <CheckBox
      android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="#E7FEFF"
                android:checked="false" />
        </TableRow>


text:
Q: OpenLayers is not showing the additional layer I am trying to implement openportguide layers on osm. Instead of adding layers one by one I created a function that gets the values and create url based on selection. So far it is not working.Couldn't figure out what is the problem.
Html:

<link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://openlayers.org/en/v4.6.5/css/ol.css" rel="stylesheet"/>

Js:
window.app = {};
    var app = window.app;
    //Custom Controls

    var layers = [];

    app.WeatherControl = function (opt_options) {
        var options = opt_options || {};

            //Weather Layers
            var weatherUI = document.createElement('div');
            weatherUI.style.cursor = 'pointer';
        weatherUI.style.textAlign = 'center';
        weatherUI.className = 'weatherui ol-unselectable ol-control';
        weatherUI.id = 'weatherlayerid';
        weatherUI.style.zIndex = '3';
            weatherUI.title = 'Please Select a Weather Layer';
        var weatherText = document.createElement('div');
        weatherText.style.zIndex = '3';
        weatherText.innerHTML = '

 Weather Layers

Common	<input type="checkbox" id="wind_stream" data-opacity="1">Wind Stream	<input type="checkbox" id="wind_barb" data-opacity="1">Wind Barbs	<input type="checkbox" id="gust" data-opacity="0.3">Wind Gust	<input type="checkbox" id="air_temperature" data-opacity="1"> Air Temp.	<input type="checkbox" id="surface_pressure" data-opacity="1">Surface Pressure	<input type="checkbox" id="precipitation" data-opacity="1">Precipitation	<input type="checkbox" id="precipitation_shaded" data-opacity="0.3">Precipitation(S)	<input type="checkbox" id="significant_wave_height" data-opacity="1">Wave Height

Marine	<input type="checkbox" id="primary_wave_height_direction" data-opacity="1">Wave Direction	<input type="checkbox" id="primary_wave_period" data-opacity="0.3">Wave Period	<input type="checkbox" id="swell_height_direction" data-opacity="1">Swell Direction	<input type="checkbox" id="swell_period" data-opacity="0.3">Swell Period	<input type="checkbox" id="sea_surface_current" data-opacity="0.3">Currents	<input type="checkbox" id="sea_surface_temperature" data-opacity="1">Sea Temp.	<input type="checkbox" id="sea_ice_coverage" data-opacity="0.3">Ice Coverage	<input type="checkbox" id="sea_ice_thickness" data-opacity="1">Ice Thickness

Time	<input type="radio" id="h0" class="timecheckbox" name="time" value="0h" onclick="TimeButtonClicked(this)" checked="">Current	<input type="radio" id="h6" class="timecheckbox" name="time" value="6h" onclick="TimeButtonClicked(this)">6h	<input type="radio" id="h12" class="timecheckbox" name="time" value="12h" onclick="TimeButtonClicked(this)">12h	<input type="radio" id="h24" class="timecheckbox" name="time" value="24h" onclick="TimeButtonClicked(this)"> 24h	<input type="radio" id="h36" class="timecheckbox" name="time" value="36h" onclick="TimeButtonClicked(this)">36h	<input type="radio" id="h48" class="timecheckbox" name="time" value="48h" onclick="TimeButtonClicked(this)">48h	<input type="radio" id="h60" class="timecheckbox" name="time" value="60h" onclick="TimeButtonClicked(this)">60h	<input type="radio" id="h72" class="timecheckbox" name="time" value="72h" onclick="TimeButtonClicked(this)">72h

Beaufort Scale

0

1

2

3

4

5

6

7

8

9

10

11

12

Gust - Beaufort Scale

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Precipitation Scale - mm/h

0

0.1

0.2

0.4

0.7

1

2

4

7

10

20

40

70

Wave & Swell Height(m)

0

0.5

1

1.5

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Wave & Swell Period(s)

0

2

4

6

8

10

12

14

16

18

20

22

24

26

28

30

Currents(kn)

0

0.2

0.5

1

1.5

2

2.5

3

4

5

6

7

8

Ice Coverage(%)

0

1

10

20

30

40

50

60

70

80

90

';
            weatherUI.appendChild(weatherText);

        $('input[id="wind_stream"]', weatherText).click(function () { $("#graph-windbeaufort").toggle(this.checked) });

        $('input[id="wind_barb"]', weatherText).click(function () { $("#graph-windbeaufort").toggle(this.checked) });

        $('input[id="gust"]', weatherText).click(function () { $("#graph-windgust").toggle(this.checked) });

        $('input[id="precipitation_shaded"]', weatherText).click(function () { $("#graph-precipitation").toggle(this.checked) });

        $('input[id="primary_wave_height_direction"]', weatherText).click(function () { $("#graph-waveheight").toggle(this.checked) });

        $('input[id="swell_height_direction"]', weatherText).click(function () { $("#graph-waveheight").toggle(this.checked) });

        $('input[id="primary_wave_period"]', weatherText).click(function () { $("#graph-waveperiod").toggle(this.checked) });

        $('input[id="swell_period"]', weatherText).click(function () { $("#graph-waveperiod").toggle(this.checked) });

        $('input[id="sea_surface_current"]', weatherText).click(function () { $("#graph-currents").toggle(this.checked) });

        $('input[id="sea_ice_coverage"]', weatherText).click(function () { $("#graph-icecover").toggle(this.checked) });

        $('input:radio', weatherText).click(function (e) {
                map.getOverlays().clear();
                var ly = $("#weatherlayers input[type='checkbox']:checked");
                $.each(ly, function (i, val) {
                    updateLayers(val);
                })
        });

        $('input:checkbox', weatherText).click(function (e) {
                updateLayers(this);
        });

        function updateLayers(control) {
            var base_URL = 'http://weather.openportguide.de/tiles/actual/';
            var checked = control.checked;
            var time = $("#weatherlayers  input[type='radio']:checked").val();
            var opacity = $(control).data("opacity");
            var layername = control.id;
            for (_layer in map.getOverlays().getArray()) {
                if (map.getOverlays().getAt(_layer).title == layername + time) {
                    if (checked == false) {
                        map.getOverlays().removeAt(_layer);
                        return;
                    }
                }
            }
            if (checked == false)
                return;
            var weatheroverlaylayer = new ol.layer.Tile({
                title: layername + time,
                visible: false,
                opacity: opacity,
                source: new ol.source.XYZ({
                    url: base_URL + layername + "/" + time + "/" + "{z}/{x}/{y}.png",
                })
            })

            layers.push(weatheroverlaylayer);

        };

        ol.control.Control.call(this, {
            element: weatherUI,
            target: options.target
        });

        $('[data-toggle="collapse"]', weatherText).click(function (e) { e.preventDefault(); $('#accordion').toggle() });

    };
    ol.inherits(app.WeatherControl, ol.control.Control);

 var oSM = new ol.layer.Tile({
        source: new ol.source.OSM()
    });

layers.push(oSM);

var map = new ol.Map({
      controls: ol.control.defaults().extend([
            new app.WeatherControl()
        ]),
        layers: layers,
        target: 'map',
        view: new ol.View({
          center: ol.proj.fromLonLat([-5.3525700, 36.1447400]),
          zoom: 6
        })
      });

A: The problem is in this row:

layers.push(weatheroverlaylayer);

Because it is in a function that is called on user click, it is after the map initialization. When initializing map you can specify layers that are added to the map in the moment of initialization. When the map is already initialized you have to use function

map.addLayer(weatheroverlaylayer)

which adds layer to allready defined map. Doc is here.


text:
Q: How to invoke an ActiveX Control using javascript in an ASP.NET page I'm trying to create an Active X component that will start an application on a client machine. I've created an Active X control which is quite straight forward in .NET. ALl it does is call the Process class and call Start.
Now i want to be able to call the starting method on this class from javascript passing in a few parameters on the page (which are then passed down as command line arguments).
I followed the guide here: http://www.c-sharpcorner.com/UploadFile/mgold/HyperlinkExec03012007191054PM/HyperlinkExec.aspx
This guide talks about using a hyperlink to start the javascript but i'm using a button. Here is my HTML (i'm trying this in just plain HTML instead of ASP.NET to keep things simple for now but i want to go to ASP.NET eventually)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >

    <body>
        <button type="button" onclick="javascript:launch()">Click me!</button>
        <script type="text/javascript">
            function launch()
            {
                alert('test')
                var myLauncher = new ActiveXObject('CardWriterApplicationLauncher');
                myLauncher.LaunchCardWriter('test', 'test', 'test');
            }
        </script>

    </body>
</html>

How when i click the button i get the error "Automation server can't create object". I know that my COM dll is registered properly in the GAC and with regasm, so what could i be doing wrong?
Also any alternative solutions to launching the application on the users desktop from a web page would be greatly appreciated. Browser security setting can be modified as required as the client PCs are under our control and are on a private network with no internet access.
Thanks

A: If you have public properties or methods in the ActiveX control can you not just call those directly referencing the <Object>'s ID using JavaScript?
So the ActiveX control is already loaded on the page using the <object> tag, and you're just calling its method.

A: Throw away the browser for a moment and go to the client machine, make sure you can create the activex object correctly on the machine, use a simple vb script or dummy app.
Create a file called something.vbs, in it put the following code
Set MyObj = CreateObject("CardWriterApplicationLauncher")

Once you have verified that part is working go to your browser.
Its likely your issue has nothing to do with your browser.
Also I just noticed CardWriterApplicationLauncher isn't a valid Object Identifier they ususally require a . in them.  eg word.application


text:
Q: How to upgrade SystemD to 246+ on Ubuntu 20.04? I'm using ROS on Ubuntu 20.04 with a CAN-FD adapter card. In systemd 246+ (20.04 uses 245), systemd-networkd adds support for CAN-FD specific settings to allow the system to boot automatically.
Is there a way for me to get systemd to a newer version without changing the version of Ubuntu (since I need to stay on 20.04 for the specific ROS integration)?
If I could follow instructions to compile a newer systemd, or just get a link to some suggestions, that would be very nice!
Thank you!

A: This is a high-risk operation since systemd is the start of a long dependency chain.
What you are asking for is basically to turn your Ubuntu 20.04 into a bleeding-edge system with new components on very deep system levels. You'd need a lot of expertise to do that successfully.
Also, are you sure that it's systemd that limits hardware compatibility with that CAN-FD card? Wouldn't that rather be kernel related?


text:
Q: How to convert from mm/dd/yyyy format to yyyy-mm-dd in python 3.0 when given 1/4/2014 So the I generally understand how I would convert from mm/dd/yyyy format to yyyy-mm-dd if the initial date given was something like 01/04/2014. However I am only given 1/4/2014  (without zeroes). Is there a clean and more efficient way of converting this in python 3 rather than writing a bunch of if statements?

A: >>> from datetime import datetime
>>> date = datetime.strptime("1/4/2014", "%m/%d/%Y")
>>> datetime.strftime(date, "%Y-%m-%d")
'2014-01-04'

Python datetime strftime()
How strptime and strftime work

A: from datetime import datetime
date = datetime.strptime("1/4/2014", "%m/%d/%Y")
print(datetime.strftime(date, "%Y-%m-%d"))
'2014-01-04'

A: Abdou's suggestion using the datetime module is best, because you get the benefit of datetime's sanity-checking of the values.  If you want to do it using only string manipulations, then notice that you can supply a fill character when invoking a string's rjust method:
>>> "1".rjust(2,"0")
'01'

so:
>>> x = "1/4/2345"
>>> f = x.split("/")
>>> f[2] + "-" + f[0].rjust(2,"0") + "-" + f[1].rjust(2,"0")
'2345-01-04'

A: Assuming that you don't need to validate the input dates, you don't need any if statements, or date processing functions: you can do it all with the string .split and .format methods.
def us_date_to_iso(us_date):
    return '{2}-{0:>02}-{1:>02}'.format(*us_date.split('/'))

# test

for s in ('1/4/2014', '1/11/1999', '31/5/2015', '25/12/2016'):
    print(s, us_date_to_iso(s))

output
1/4/2014 2014-01-04
1/11/1999 1999-01-11
31/5/2015 2015-31-05
25/12/2016 2016-25-12


text:
Q: MYSQL IF NOT LIKE A THEN LIKE B i want to make a sql query l
but how do I perform an IF...THEN in an SQL SELECT statement like: "
select name from table1,table2 where if( name like a then name like a ) else name like b"

A: You can use the OR operator, which connects two Boolean clauses:
WHERE name LIKE ...
   OR name LIKE ...

Note that OR has lower precedence than AND, so if you want to combine this with other restrictions, you'll need to use parentheses; for example:
WHERE ( name LIKE '%a%' OR name LIKE '%b%' )
  AND id < 1000

A: SQL isn't a programming language, it doesn't have if, then, else etc.  If the required condition can be expressed in set operations such as AND and OR you can do it.
Otherwise you need to write a Stored Procedure, Stored Function or Stored Routine.  See http://dev.mysql.com/doc/refman/5.1/en/stored-routines.html, which will allow you to write procedural code.  The set operations are usually much faster.

A: MySQL supports IF statements and CASE statements.  Try something like this assuming a and b are columns in one of your tables and name is a column in your other table:
 select name
    from table1,table2
    where name like
       case
          when name like a
          then a
          else b
       end

And some sample fiddle: http://sqlfiddle.com/#!2/c6ce6/1
You may be wanting to use '%' with your LIKE query -- if so, CONCAT accordingly.  This same logic can be used with string values instead if needed.
Please post your table structure, sample data, and desired output so we can fully understand your question though and provide the best answer.

A: Ever tried mysql stored procedure http://www.mysqltutorial.org/getting-started-with-mysql-stored-procedures.aspx?
And you may want to check this out: using "if" and "else" Stored Procedures MySQL
Hope this helps! :)


text:
Q: Change variable in Express Session I'm using the express-session package and I want to change the variable "_id" in the session.
Here my session init
app.use(session({
    secret: "secretshhhhhh",
    resave: true,
    saveUninitialized: false,
}))

After the login page I try to store the id with these few lines:
req.session._id = user._id.toString()
req.session.save(function (err) {
    req.session.save(function (err) {
         console.log(req.session)
    })
})

The console.log print the session with the id, but when I try to get the _id in an other page express send me back a null object. Here an exemple of printing session without the _id
return res.status(200).send(req.session);

I tried many methods but none of these worked for me.
EDIT:
Here my whole function to put it in session
module.exports.login_post = async function (req, res) {
    User.findOne({ email: req.body.email }, function (err, user) {
        if (user == null) {
            return res.status(400).send({
                message: "User not found"
            })
        }
        else {
            if (user.validPassword(req.body.password)) {
                req.session._id = user._id.toString()
                req.session.save(function (saveErr) {
                    req.session.reload(function (reloadSave) {
                        console.log(req.session, saveErr, reloadSave)
                    })
                })
            }
        }
    })
}

Here my whole function to get it from session
module.exports.session_get = function(req, res) {
    return res.status(200).send(req.session);
}

module.exports.session_destroy = function(req, res) {
    req.session.destroy();
    return res.status(200).send({
        message: "Session detroyed"
    });
}


text:
Q: Calculating 'most selected value' in columns Im trying to calculate the most selected value of a column just using mysql, but I dont know If this is possible or If I will need to also use php ...
All values are integers rangin form 1 to 12, which are the ids of the selections made in the frontend and the table (id:table) looks like this:
id | value_1 (int) | value_2 (int) | value_3 (int)

EDIT:
With this I can get the most selected of column 'value_1' :
SELECT value_1, count( * ) total
FROM table
GROUP BY value_1
ORDER BY total DESC
LIMIT 1

How could I get all the most selected values in the tree columns (value_1 | value_2 | value_3) in single SQL sentence?

Following the duplicated quiestion link I have also tried with this, but It returns an error:
select value_1, count(*) total
from (
    select @r := if(total>@r,total,@r) maxcount, value_1, total
    from (select @r:=0) initvars, (
        select value_1, count(*) total
        from table
        group by value_1
    ) X ) Y
where total = @r

MYSQL ERROR : #1140 - Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause

A: SELECT id,
    COUNT(val1)As 'First Value',
    COUNT(val2)As 'Second Value',
    COUNT(val3)As 'Third Value'
FROM alez
GROUP BY id
ORDER BY id DESC

The ID with the highest number selected will occur first. Then they will be sorted from highest to lowest based on the number that was selected the most.

A: Just to clarify to users that read through this post I managed to do it but using also PHP. It would be nice to do it with just once MYSQL sentence but I couldnt figure out how to do that :
$array_sql = array("value_1", "value_2", "value_3");

//Loop
foreach($array_sql as $val){
    $SQL =  "
    SELECT $val, count( * ) total
    FROM table
    GROUP BY $val
    ORDER BY total DESC
    LIMIT 1
    ";

    ${'result_'.$val} = mysql_query($SQL) or die(mysql_error());//$result_mvp

}

//results for value_1
$row_1 = mysql_fetch_array($result_value_1);
$val1 = $row_1['total']; // Most selected option for value_1

//results for value_2
$row_2 = mysql_fetch_array($result_value_2);
$val2 = $row_2['total']; // Most selected option for value_2

//results for value_3
$row_3 = mysql_fetch_array($result_value_3);
$val3 = $row_3['total']; // Most selected option for value_3


text:
Q: Pick row with highest value and return rowname For each column I would like to select the rowname that has the highes value across all rows.
Please see my input and output example.
> df.t[,1:5][1:5,]
                MMRF_1021 MMRF_1024 MMRF_1029 MMRF_1030 MMRF_1031
ENSG00000004468  8.195680  7.500753  7.912472  8.886945  6.780892
ENSG00000081237  4.401101  6.135663  6.525512  4.496787  7.927844
ENSG00000139193  6.124573  6.585169  5.547023  6.254043  2.764494
ENSG00000156738 -1.491527  2.237000  7.192401  8.032151 -4.253239
ENSG00000174059 -5.663732 -4.477220 -5.663732 -4.237282 -4.792564

out
MMRF_1021 ENSG00000004468
MMRF_1024 ENSG00000004468
MMRF_1029 ENSG00000004468
MMRF_1030 ENSG00000004468
MMRF_1031 ENSG00000081237

A: We can transform the dataframe and use max.col
data.frame(col = names(df), value  = rownames(df)[max.col(t(df))])

#        col           value
#1 MMRF_1021 ENSG00000004468
#2 MMRF_1024 ENSG00000004468
#3 MMRF_1029 ENSG00000004468
#4 MMRF_1030 ENSG00000004468
#5 MMRF_1031 ENSG00000081237

data
df <- structure(list(MMRF_1021 = c(8.19568, 4.401101, 6.124573, -1.491527,
-5.663732), MMRF_1024 = c(7.500753, 6.135663, 6.585169, 2.237,
-4.47722), MMRF_1029 = c(7.912472, 6.525512, 5.547023, 7.192401,
-5.663732), MMRF_1030 = c(8.886945, 4.496787, 6.254043, 8.032151,
-4.237282), MMRF_1031 = c(6.780892, 7.927844, 2.764494, -4.253239,
 -4.792564)), class = "data.frame", row.names = c("ENSG00000004468",
"ENSG00000081237", "ENSG00000139193", "ENSG00000156738", "ENSG00000174059"))

A: In this case, get the column wise index of max value with sapply, convert the named vector to a two column data.frame (stack) and transform the index to the row names by using that index as numeric index
transform(stack(sapply(df.t, which.max))[2:1], values = row.names(df.t)[values])
#   ind          values
#1 MMRF_1021 ENSG00000004468
#2 MMRF_1024 ENSG00000004468
#3 MMRF_1029 ENSG00000004468
#4 MMRF_1030 ENSG00000004468
#5 MMRF_1031 ENSG00000081237

Or make it a bit more compact
stack(lapply(df.t, function(x) row.names(df.t)[which.max(x)]))

Or using max.col with stack
stack(setNames(row.names(df.t)[max.col(t(df.t))],  names(df.t)))[2:1]
#      ind          values
#1 MMRF_1021 ENSG00000004468
#2 MMRF_1024 ENSG00000004468
#3 MMRF_1029 ENSG00000004468
#4 MMRF_1030 ENSG00000004468
#5 MMRF_1031 ENSG00000081237

The similar option in tidyverse would be to use summarise_all to loop over all columns get the index with which.max, convert to a two column data.frame and change the index
library(dplyr)
library(tidyr)
df.t %>%
   summarise_all(which.max) %>%
   pivot_longer(everything()) %>%
   mutate(value = row.names(df.t)[value])

Or we can avoid the last step with
df.t %>%
   summarise_all(~ row.names(df.t)[which.max(.)]) %>%
   pivot_longer(everything())

Or another option is to do the pivot_longer first, then do a group by operation
df.t %>%
   pivot_longer(everything()) %>%
   group_by(name) %>%
   summarise(value = row.names(df.t)[which.max(value)])

Or using map with enframe
library(purrr)
library(tibble)
map(df.t, ~ row.names(df.t)[which.max(.x)]) %>%
     enframe %>%
     unnest(c(value))

data
df.t <- structure(list(MMRF_1021 = c(8.19568, 4.401101, 6.124573, -1.491527,
-5.663732), MMRF_1024 = c(7.500753, 6.135663, 6.585169, 2.237,
-4.47722), MMRF_1029 = c(7.912472, 6.525512, 5.547023, 7.192401,
-5.663732), MMRF_1030 = c(8.886945, 4.496787, 6.254043, 8.032151,
-4.237282), MMRF_1031 = c(6.780892, 7.927844, 2.764494, -4.253239,
-4.792564)), class = "data.frame", row.names = c("ENSG00000004468",
"ENSG00000081237", "ENSG00000139193", "ENSG00000156738", "ENSG00000174059"
))


text:
Q: How to daemonize a process in C using fork() func. - socket programming i ve searched quite a lot already and am aware that maybe i already came across some helpful answers but were unable to understand them...not really much of a programmer i am: )
the case is i would like to implement a daemon - background process totally independent of what is happening in the meantime - to parse data which are being received from the server (am writing IRC client) but to do it in non-blocking way using select().
Here s fragment of my code.
But i cant get to printf under the comment //rest of the program
i hope it s understandable enough.
pID=fork();
        if(pID < 0){
            //failed to execute fork()
            perror("Error while forking");
            getchar();getchar();
            exit(1);
        }
        if(pID > 0){
            exit(0);
            }
        //child down here
            umask(0);
            //setting new session
            sID = setpgid(0,0);
            if(sID < 0){
                perror("Error while setting new session");
                getchar();getchar();
                exit(1);
            }
            while(1){
                sleep(1);
                if((readReady = readReadiness(sockfd))==0)
                    continue;
                else{
                    //here am going to recv() data from server
                    printf("I am child and parsing\n"); //testing if its in background -i would like it not to print to stdout (run in background)

                }
            }

        //rest of the program down here
        printf("Why isnt it printing to stdout ??\n");

should i use grandchild ? (double forking ?)
or... ?
Thanks in advance

A: My comment above was neither answer nor suggestion; it was a question.
I don't see why you need to fork again - you have a process without a controlling terminal (thanks to setpgid) as you desire. You can process received data in the while(1) loop.  Looks like you are set to go - the 'rest of the program' goes in the while loop.
EDIT
Calling fork creates a child copy of the running process. Calling setsid in the child will disconnect the child from the terminal but will not affect the parent (which exits anyway). I suggest you start off with something like:
static void
process_stuff(int sockfd)
{
    while (1) {
        /* receive data on socket and process */
    }
}

void
run_daemon(int sockfd, int foreground)
{
    if (!foreground) {
        if (fork()) {
            exit(EXIT_SUCCESS); /* parent */
        }
        /* child */
        setsid();
    }
    process_stuff(sockfd);
}

The reason for having the if (foreground) clause is that it allows you to debug the server in the foreground under gdb when it doesn't work.


text:
Q: Installshield multilangague supported application I have to create the language package for my customer released application, what is the best approach to create language package setup, so it will be installed on top customer release application.
I supposed to provide option to user to install and uninstall the language package as well.Suggest me the best way to do this through installshield 2011.

A: I would do it this way.
Surely your application stores the installation folder in the registry when it's installed. Then your language pack searches for this registry entry.

*

*If the install location is not stored in the registry, then your application is not installed: report an error and exit.

*Otherwise you know where to copy the language files, so proceed to installing your language pack.

Your language pack will have its own entry in Add/Remove Programs.
If you don't want it, there are two other options:

*

*Register the language pack as an update to your application. Then it will displayed only when user chooses to see installed updates.
How to do it is explained in Filtering the Add or Remove Programs List.

*Hide your package from Add/Remove Programs. In this case you have to provide another way to uninstall the package.

There's one other thing: The uninstaller for your main application should (could) provide options to uninstall all the installed language packs. You don't want to make users uninstall them manually, right?
It is tricky. The simplest approach that comes to my mind is your main uninstaller enumerates the installed languages packs and schedules its removal. Yet this may be not UAC-friendly.
Approaches to implementing removal of languages packs depend on how these packages are created. If your uninstaller has a bootstrapper, an .exe rather than bare .msi, then it could be quite easy. The bootstrapper initiates uninstall process for the main application. If it's successful, it proceeds to removing language packs. And it would be UAC-friendly: the bootstrapper asks for elevation when started, thus all the processes it starts will also be elevated.


text:
Q: Why is it taking forever to install RSAT I'm developing in a windows 10 environment.
I need Active Directory Module for Powershell.
A pre-requisite is to install RSAT.
I used the script provided here: https://gallery.technet.microsoft.com/Install-the-Active-fd32e541/view/Discussions#content
after more than 2 hours, this it's still installing:

Anyone have any pointers?  Thank you!


text:
Q: Convertir fecha UNIX timestamp a date Cuando me llega la información a mi API llega con el formato Unix TimeStamp
Por ejemplo: 1535440000 necesito convertir este formato a YYYY-mm-ddTHH:MM:ssZ por ej: 2018-05-31T16:49:27.698Z.
Estoy trabajando en JavaScript y MongoDB. ¿Existe alguna función para realizar esta transformación?
Un saludo y gracias

A: En javascript multiplicas el valor por 1000 para obtenener el tiempo en milisegundos y obtienes con toISOString la fecha en formato formato ISO8601.

var data = 1535440000;
var date = new Date(data * 1000).toISOString();
alert(date);

Origen aqui.


text:
Q: How to handle dependency injection when using a common base controller for multiple controllers in .NET CORE I have a UserController and a BaseController with some functions and dependencies injected as below. The BaseController is shared between multiple controllers. But All the controllers do not need all the injected dependencies from the BaseController. Controller1 Needs dependencies D1 and D2 but Controller2 requires only D1 from BaseController. How can I achieve this?
In the below code, UserController does not require the injected webHostEnvironment from the base but I need to inject it as it present in BaseController else Visual Studio throws compiler error of missing dependency. Please let me know if additional details are required to resolve the issue.
UserController
using MyApp.Data;
using MyApp.Models;
using MyApp.Models.ViewModels;
using MyApp.Utilities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace MyApp.Controllers
{
    [Authorize]
    public class UserController : BaseController
    {
        private readonly ApplicationDbContext db;
        private readonly ILogger<UserController> logger;
        private readonly RoleManager<IdentityRole> roleManager;
        private readonly IEmailSender emailSender;

        public UserController(  ApplicationDbContext db,
                                ILogger<UserController> logger,
                                UserManager<ApplicationUser> userManager,
                                RoleManager<IdentityRole> roleManager,
                                IEmailSender emailSender,
                                IWebHostEnvironment webHostEnvironment) : base (userManager, webHostEnvironment)
        {
            this.db = db;
            this.logger = logger;
            this.roleManager = roleManager;
            this.emailSender = emailSender;
        }

        [HttpGet]
        public IActionResult Index()
        {
            var userList = userManager.Users;
            return View(userList);
        }

        [HttpGet]
        public async Task<IActionResult> Read(string? id)
        {
            var user = await userManager.FindByIdAsync(id);
            if (user == null)
            {
                return RecordNotFound();
            }
            UserViewModel model = new()
            {
                Id = user.Id,
                FirstName = user.FirstName,
                LastName = user.LastName,
                UserName = user.UserName,
                Email = user.Email,
                PhoneNumber = user.PhoneNumber,
            };
            return View(model);
        }
    //And Some more Action Methods for the controller
    }
}

BaseController
using MyApp.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace MyApp.Utilities
{
    [Authorize]
    public class BaseController : Controller
    {
        protected readonly UserManager<ApplicationUser> userManager;
        protected readonly IWebHostEnvironment webHostEnvironment;

        public BaseController(  UserManager<ApplicationUser> userManager,
                                IWebHostEnvironment webHostEnvironment)
        {
            this.userManager = userManager;
            this.webHostEnvironment = webHostEnvironment;

        }

        [HttpGet] [HttpPost]
        public IActionResult RecordNotFound()
        {
            TempData[HelperStatic.ErrorMessage] = HelperStatic.recordNotFoundMsg;
            return View("Index");
        }

        [HttpPost]
        public IActionResult SaveNew()
        {
            TempData[HelperStatic.SuccessMessage] = HelperStatic.recordSavedMsg;
            return RedirectToAction("Create");
        }

        //And Many other Reusable Methods for all controllers
    }
}

A: It would seem what you have here is too much going on in your base controller.
If you have actions within the base controller that are not applicable to all, then they are living in the wrong place.
For example (from what you've given), this action looks like it should maybe live e.g. on an error controller:
[HttpGet] [HttpPost]
public IActionResult RecordNotFound()
{
    TempData[HelperStatic.ErrorMessage] = HelperStatic.recordNotFoundMsg;
    return View("Index");
}

And you redirect to 'Error/RecordNotFound' rather than having this live within every inheriting controller.
You cannot have dependencies on your base constructor that are not also injected on sub classes.  If this is causing you a problem, it's because there's too much going on in the base!


text:
Q: How can I access the value of ForeignKey inside the model definions? I have Car model
class Automovil(Item_Inventario):
    brand = models.CharField(max_length=50, default='Acme')
    model = models.CharField(max_length=50, default='Acme')

   price = models.FloatField(default=0.0)

And a Sales model
class Sale(models.Model):
    salesman = models.ForeignKey(settings.AUTH_USER_MODEL)
    buyer = models.CharField(max_length=50, default='')
    buyer_id = models.CharField(max_length=50, unique=True,
                                default='00000000')
    car = models.ForeignKey(settings.MODELO_AUTO)
    amount = models.FloatField(default=car.price)
    date = models.DateField(default=timezone.now)

And I would like to calculate amount with the price of the car in question, unfortunately I can't do car.price inside the model definition. So how can I accomplish this?

A: You can't relate fields like that when defining a model. The easiest way would be  overriding Model.save() method:
class Sale(models.Model):
    car = models.ForeignKey(settings.MODELO_AUTO)
    amount = models.FloatField()
    ...

    def save(self, *args, **kwargs):
        self.amount = self.car.price
        super(Sale, self).save(*args, **kwargs)

A: I guess you need to calculate amount, you can define a signal to do this:
#models.py

from django.db.models.signals import pre_save

class Automovil()...

class Sale(models.Model):
    ...
    amount = models.FloatField()
    ...

def calculate_amount(sender, instance, *args, **kwargs):

    instance.amount = instance.car.price

pre_save.connect(calculate_amount, sender=Sale)


text:
Q: MenuItem's sub menu don't open I have a MenuItem with sub-buttons in a ToolBar:
<ToolBar x:Name="toolBar" VerticalAlignment="Top">
      <Button x:Name="btnNew" Content="New"/>
      <MenuItem x:Name="miWindow" Header="Add windows">
             <Button x:Name="btnScore1" Content="Score"/>
             <Button x:Name="btnScore2" Content="Score (complete)"/>
      </MenuItem>
 </ToolBar>

When I click on it, my sub-menu don't open. Did I forget something ?
Also, I tried to handle the click event of the MenuItem, but it's never fired.

A: It should be inside a Menu Tag:
<ToolBar x:Name="toolBar" VerticalAlignment="Top">
    <Button x:Name="btnNew" Content="New"/>
    <Menu>
        <MenuItem x:Name="miWindow" Header="Add windows">
            <Button x:Name="btnScore1" Content="Score"/>
            <Button x:Name="btnScore2" Content="Score (complete)"/>
        </MenuItem>
    </Menu>
</ToolBar>


text:
Q: Not using Async in Rocket 0.5+? I read Rocket v0.5 now uses the Tokio runtime to support Async. I know Async can offer great scalability when we have lots of (like hundreds or thousands of) concurrent IO-bound requests. But many web/REST server apps simply don't fall into that category and in such cases, I feel like Async would only complicate stuff. Sorry if that sounds like a dumb question, but with Rocket 0.5+ will I still be able to write a traditional non-async code the same way as before? Does Async-support in Rocket 0.5+ mean that we will only get Async behaviour for async fn handlers? If so, will the Tokio runtime still play any role in non-async code?

A: Sure you can.
Look at the first examples in the web page:
#[get("/")]
fn index() -> &'static str {
   "Hello, world!"
}

There is no async/await anywhere. The nicest thing of Rocket5 is that you can choose which views are sync are which are async, simply by making them so, and you can mix them together as you see fit.
For example this will just work:
#[get("/sync")]
fn index1() -> &'static str {
   "Hello, sync!"
}
#[get("/async")]
async fn index2() -> &'static str {
   "Hello, async!"
}

The Rocket runtime is all async under the hood, but that doesn't need to be exposed to your view handlers at all. When a non-async handler is run, it will be as if Rocket used spawn_blocking().


text:
Q: Python Erro no if Estou a ter um erro no if e não sei como corrigir este erro, estou a usar o Python 3.6 e Pandas para leitura, escrita e data analysis.
df1 = pd.read_csv("JonnyTheBoy10.csv", usecols=['ART_TIPO', 'ART_DESIG', 'PORTA', 'CP4', 'CP3', 'LOCALIDADE'])
df2 = pd.read_csv("JonnyTheBoyFull.csv", usecols=['ART_TIPO', 'ART_DESIG', 'PORTA', 'CP4', 'CP3', 'LOCALIDADE'])

    if df1["CP4"] == df2["CP4"] and df1["CP3"] == df2["CP3"]

Tenho este erro:
Traceback (most recent call last):
  File "C:/Users/User01/Desktop/Normmm/Norm.py", line 11, in <module>
    if df1["CP4"] == df2["CP4"] and df1["CP3"] == df2["CP3"]:
  File "C:\anaconda\lib\site-packages\pandas\core\ops.py", line 818, in wrapper
    raise ValueError(msg)
ValueError: Can only compare identically-labeled Series objects

A:
Ok, depois do verdadeiro chat nos comentários, e vc ter me mandado os csv's, "resolvi o seu problema" (que isso não se repita, ahahaha), vamos lá. O problema é que vc precisa comparar cada linha dos dataframes, e voce esta comparando as colunas inteiras, isso não pode; mesmo porque os dataframes tem tamanhos diferentes (por isso da o erro), fiz testes com os csv's que vc me enviou, nenhuma linha do csv menor é totalmente identica à linha relativa (mesmo indice) ao csv maior, veja o codigo:

Clique aqui para ver codigo abaixo rodando.
import pandas as pd
df1 = pd.read_csv("JonnyTheBoy10.csv", usecols=['ART_TIPO', 'ART_DESIG', 'PORTA', 'CP4', 'CP3', 'LOCALIDADE'])
df2 = pd.read_csv("JonnyTheBoyFull.csv", usecols=['ART_TIPO', 'ART_DESIG', 'PORTA', 'CP4', 'CP3', 'LOCALIDADE'])

all_equals=[]
cp3_equal=[]
cp4_equal=[]

for index, row in df1.iterrows():
    if str(row.CP4)==str(df2.CP4[index]) and str(row.CP3)==str(df2.CP3[index]):
        all_equals.append(row)

    if  str(row.CP3)==str(df2.CP3[index]):
        cp3_equal.append(row)

    if str(row.CP4)==str(df2.CP4[index]):
        cp4_equal.append(row)

print ('Igualdades em ambos: ', len(all_equals))
print ('Igualdades em CP3: ', len(cp3_equal))
print ('Igualdades em CP4: ', len(cp4_equal))

Igualdades em ambos:  0
Igualdades em CP3:  9
Igualdades em CP4:  0

Vou deixar a explicação inicial (abaixo) porque pode servir para outras pessoas em outros contextos.

Veja esse exemplo:
df1 = pd.DataFrame([['A', 'B'], ['C', 'D']])
df2 = pd.DataFrame([['C', 'D'], ['A', 'B']])
df1==df2
       0      1
0  False  False
1  False  False

Agora, o mesmo exemplo, mas com o df2 'indexado'.
df1 = pd.DataFrame([['A', 'B'], ['C', 'D']])
df2 = pd.DataFrame([['C', 'D'], ['A', 'B']], index=[1,0])
df1==df2
....
raise ValueError('Can only compare identically-labeled '
...

Veja que foi levantado uma exceção com o mesmo erro que vc relata, eu suprimi a msg inteira para ficar mais fácil.

Solução 1: Drope os indices:

df1.reset_index(drop=True) == df2.reset_index(drop=True)
       0      1
0  False  False
1  False  False

Solução 2: Faça sort em axis=0:

df1.sort_index()==df2.sort_index()
      0     1
0  True  True
1  True  True

Note que == é 'sensitivo' à ordem das colunas.

Aplicando ao exemplo da sua questão.

No caso da sua questão, tente apenas mudar o if para:
if df1.reset_index(drop=True)["CP4"] == df2.reset_index(drop=True)["CP4"] and
df1.reset_index(drop=True)["CP3"] == df2.reset_index(drop=True)["CP3"]


text:
Q: Trying to Reduce HTTP Requests With CSS Sprites But Now Images Don't Appear Properly To try and reduce the number of HTTP requests I have combined groups of related images into sprites.
I understand the methodology behind it but I can't seem to get it to work correctly for the ones I am working one and would love some help.
Here is the new markup and css (previous markup just had individual img tags wrapped in the anchor tag):

Region:

        ... 5 more

CSS is as seen below:
#footer-flags {
    float:right;
}
#footer-flags ul {
    list-style-type: none;
    margin:-3px 0 0 0;
    overflow:hidden;
    padding:0;
}
#footer-flags ul li {
    background-image: url(/img/flags/flags-sprite.jpg);
    height: 11px;
    width: 14px;
    float:left;
    padding-left:5px;
    padding-top:3px;
}
#footer-flags #de {
    background-position: 0px 0px;
}
#footer-flags #fr {
    background-position: 0px -11px;
}
#footer-flags #hr {
    background-position: 0px -22px;
}
#footer-flags #ie {
    background-position: 0px -33px;
}
#footer-flags #nl {
    background-position: 0px -44px;
}
#footer-flags #uk {
    background-position: 0px -55px;
}
#footer-flags #us {
    background-position: 0px -66px;
}

#footer-flags ul li.active {
    background:url("/img/flags/flag-highlight.png") no-repeat scroll left top transparent;
    margin-right:-5px;
    padding:3px 5px 5px;
}

The sprite image is 14px x 77px (so the flags are positioned on top of each other).
Here is a fiddle if anyone prefers it: http://jsfiddle.net/WNXNz/4/
The error itself is just that the flag images are strewn all over the place and the links don't seem to be there aswell, i.e. the images aren't clickable.
From what I can see I think I have implemented it correctly but it's likely my CSS is a nightmare because I have only had to use a sprite before and it was just for one image.

A: CSS Sprites shouldn't be used for HTML img. You now have empty links: this is bad for accessibility and SEO.
Accessibility: you can check the relevant WCAG 2.0 Technique H30: Providing link text that describes the purpose of a link for anchor elements
People that disable images, CSS, use a screen reader or use the High Contrast mode in Windows won't be able to know there's a link there or won't know what it can possibly do.
SEO: I'm not a SEO specialist, all I can tell is that searchbots will have to guess from the destination what is the purpose of your link, that's not by far the best way to rank well in search engines.
That said, CSS sprites are great for background images :)


text:
Q: Tabular in frame: get rid of horizontal spacing I'm trying to surround a tabular with a thick frame:
\setlength\fboxrule{2pt}
\setlength{\fboxsep}{0pt}
\fcolorbox{black}{gray}{
    \begin{tabular}{@{}p{2cm}|p{2cm}@{}}
        A & B \\ \hline
        C & D \
    \end{tabular}
}

Although I set \fboxsep to 0pt and use @{}, there is still some horizontal margin between the frame and the tabular:
http://flyx.org/files/framedtabular.png
I want the horizontal line to reach the frame at both ends. How can I achieve that?

A: You are a victim of end of line space. Put % as shown in the following code:
\documentclass{article}
\usepackage{xcolor}
\begin{document}
  \setlength\fboxrule{2pt}
\setlength{\fboxsep}{0pt}
\fcolorbox{black}{gray}{%    %% <------- here
    \begin{tabular}{@{}p{2cm}|p{2cm}@{}}
        A & B \\ \hline
        C & D
    \end{tabular}%   %% <------- here
}
\end{document}

For details on adding % at the end refer to This Q and its A.


text:
Q: Indirect modification of overloaded property when building a PHPUnit test for Braintree webhook I am trying to build a test with PHPUnit to test my Braintree hook. I have this test case which uses the dataProvider below:
/**
 * @covers SubscriptionExpiredHook::processHook()
 * @dataProvider dataProvider
 */
public function testProcessHook($subscriptionId)
{
    $subscriptionExpiredHook = new SubscriptionExpiredHook($this->siteManager);

    $notification = $this->getMockBuilder('Braintree\WebhookNotification')
        ->disableOriginalConstructor()
        ->getMock();

    $notification->subscription->id = $subscriptionId;

    $router = $this->getRouterMock();

    $subscriptionExpiredHook->setSubscription(new Subscription($router));

    $response = $subscriptionExpiredHook->processHook($notification);

    $this->assertEquals(200, $response->getStatusCode());
}

public function dataProvider()
{
    return [
        [
            'subscription_id' => 'CRM1872',
        ]
    ];
}

The line that is causing the problem is this:
$subscriptionId = $hook->subscription->id;

...and this is the error I get when I run the test:

1)
  CRMPiccoBundle\Tests\Braintree\Hooks\SubscriptionExpiredHookTest::testProcessHook
  with data set #0 ('CRM1872') Indirect modification of overloaded
  property Mock_WebhookNotification_e65192ec::$subscription has no
  effect

Is there a way that I can set the subscription id to allow this test to proceed or am I looking at it the wrong way?

A: Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
WebhookNotifications are not currently mockable, though making webhook testing more robust is on our roadmap. For the time being, use WebhookTesting::sampleNotification to pack a sampleNotification with the type of the WebhookNotification as well as the subscription_id. You can view an example usage here.
Note that $webhookNotification->subscription will not give you an entire object, and you will have to run a find against your sandbox to retrieve the entire subscription.


text:
Q: Loading a DLL from another DLL I have a C++ - DLL A which is going to call another DLL B.
In case I use the command
LoadLibrary(L"...\\whole path\\B.dll");

everything is working fine. But assuming that sometimes the path may change due to maintenance reason for example I came up with
LoadLibraryEx("B.dll", NULL, LOAD_LIBRARY_SEARCH_APPLICATION_DIR);

to allow moving the DLLs without expecting loading problems.
This command is searching in the application's installations directory (see: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684179(v=vs.85).aspx).
Using Visual Studio 2010 Express it worked for me when I placed B.dll in the folder where the A.dll is saved.
Some days ago I installed Visual Studio 2015 Express. I placed the B.dll in the corresponding folder. It did not work. I copied it then into every other folder related to my A.dll though B.dll could not be found.
Note, both DLLs have been rewritten in VS2015! It is, thus, not a problem of different VS versions.
Does anyone have an idea how to fix this?
EDIT: (former problem understood, related question)
After reading comments I found out this command redirects my DLL to search in Excels directory (which is calling A.dll).
But what I want to do is:
VBA will call a DLL A.dll by using an absolute path. All other DLLs like B.dll, C.dll, and so on will be in the same folder as A.dll. But those DLL I want to call giving a relative path. My intention is to change the path only once in the VBA code when I move all DLLs.
How do I do this?


text:
Q: How to get the elements when there is an internal web page tab in powershell I am trying to automate to some extent data packet analysis using nGeniusOne. nGeniusOne would open all tools in internal tabs. I have noticed that unless there is a ie navigate I am not able to find the elements. What I mean by that is that when I click on a tool and there is a dashboard which opens in an internal tab I still only have the elements from the original page and not the new tab. Can some one please help me with how to find the new elements that have been loaded.
For reference images about what I am looking at you can see
https://www.netscout.com/product/enterprise/ngeniusone-service-assurance-platform
In the first image "Service Dashboard" is a tab that would open when you click on the link in the "All Modules" tab.
Code snippet below:
$ie = New-Object -ComObject 'internetExplorer.Application'
$ie.Visible= $true
$ie.Navigate("http://XXX.XXX.XXX.XX:XXXX/common/NSLogin.jsp?redirect=/console")

while ($ie.Busy -eq $true){Start-Sleep -seconds 1;}

$usernamefield = $ie.Document.getElementByID('usernameText')
$usernamefield.value = $username

$passwordfield = $ie.Document.getElementByID('passwordText')
$passwordfield.value = $password

$Link=$ie.Document.getElementsByTagName("input") | where-object {$_.className -eq "submBtn"}
$Link.click()

while ($ie.Busy -eq $true){Start-Sleep -seconds 1;}

$Link=$ie.Document.getElementsByTagName("img") | where-object {$_.alt -eq "Data Mining"}
while ($Link -eq $null){Start-Sleep -seconds 1;$Link=$ie.Document.getElementsByTagName("img") | where-object {$_.alt -eq "Data Mining"}}
$Link.click()

while ($ie.Busy -eq $true){Start-Sleep -seconds 1;}

#Data mining opens in a new internal tab.

$i = 0
while ($Link -eq $null){Start-Sleep -seconds 1;
    $Link=$ie.Document.getElementByID("jqg_ui-id-11_ui-id-11-ns-row-4");
    Write-Host "Still not found";
    $i = $i+1;
    if($i -eq 10){break}}
$Link.click()

the above is never found even though I can see it using developer tools in IE


text:
Q: CSS loading within in-page style tags, but not from external stylesheet I'm using this slide-in effect from CSS-tricks. It partly uses the visible plugin, and the animation is done via CSS.
http://css-tricks.com/slide-in-as-you-scroll-down-boxes/
It works when the CSS is loading in-page within style tags, but when I load it from an external stylesheet it doesn't. I've checked that the stylesheet is loading and it is. I'm wanting to load it externally to keep my CSS in one file. I've tried getting this to work in both HTML and wordpress, but get the same result. I use HTML5 Reset files. Thanks, Tim.
I've tried using: @import url("slidein.css"); within style tags but that didn't work.
In Wordpress I load the javascript within an external file, ie.
<script src="<?php echo get_template_directory_uri(); ?>/js/index.js"></script>

within HTML:
<script src="js/index.js"></script>

The CSS in Wordpress:
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/slidein.css" />

and HTML:
<link rel="stylesheet" type="text/css "href="assets/css/slidein.css" />

The javascript within index.js:
$.fn.offScreen = function(distance){

        var $t              = $(this),
            $w              = $(window),
            viewTop         = $w.scrollTop(),
            viewBottom      = viewTop + $w.height(),
            _top            = $t.offset().top - distance,
            _bottom     = $t.offset().top + $t.height() + distance;

   return {
     top: _bottom <= viewTop,
     bottom: _top >= viewBottom
   }

};

var win = $(window);

var allMods = $(".module");

allMods.each(function(i, el) {
  var el = $(el);
  if (!el.offScreen(150).bottom) {
    el.addClass("already-visible");
  }
});

win.on("scroll resize",function(event)
{

  allMods.each(function(i, el) {
    var el = $(el);
    if (!el.offScreen(150).top && !el.offScreen(150).bottom)
    {
      el.removeClass("already-visible off-screen-top off-screen-bottom");
      el.addClass("come-in");
    }
    else
    {

        if(el.offScreen(150).top)
        {
            el.addClass("off-screen-top");
        }
        else
        {
            el.addClass("off-screen-bottom");
        }
    }
  });//allMods.each()

});//win.scroll()

win.trigger("scroll");

The CSS:
* {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

section {
  background: #eee;
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  overflow: hidden;
}

.module {
  width: 48%;
  min-height: 200px;
  background: white;
  position: relative;
  float: left;
  padding: 20px;
  margin-right: 4%;
  margin-bottom: 4%;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  transform-origin: center center;
}
.module:nth-child(even) {
  margin-right: 0;
}
.module.off-screen-top {
  transform: translateY(-150px);
}
.module.off-screen-bottom {
  transform: translateY(150px);
}

body {
  background: url(http://s.cdpn.io/3/blurry-blue.jpg);
  background-size: cover;
  padding: 30px;
}

.come-in {
  transform: translateY(0);
  transition: transform 0.8s ease-out;
}

.come-in:nth-child(odd) {
  transition-duration: 0.5s;
}

.already-visible {
  transform: translateY(0);
  transition: none;
}
@keyframes come-in {
  to {
    transform: translateY(0);
  }
}

A: In WordPress, you should use wp_enqueue_style() to enqueue your external stylesheets, making sure to hook to wp_enqueue_scripts. For example:
function my_enqueue_scripts() {
    wp_enqueue_style( 'style-name', get_stylesheet_uri() );
}

add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );

Ref: http://codex.wordpress.org/Function_Reference/wp_enqueue_style


text:
Q: What is the SonarQube Web API to retrieve all projects/resources which are using a specific quality profile? What is the SonarQube Web API to retrieve all projects/resources which are using a specific quality profile ? I know we have API to get all profiles used for a project, But my requirement is just in contrast.
Resources: https://docs.sonarqube.org/pages/viewpage.action?pageId=2392180
Profiles: https://docs.sonarqube.org/pages/viewpage.action?pageId=2392177
Can anyone help here?
Thanks and regards,
Narasimha

A: Use the web service api/qualityprofiles/projects to retrieve projects associated with a specific quality profile.