text:
Q: Guidline 4.1 - Copycats So my app was rejected yesterday and I am not sure why exactly and what the reasons mean exactly.
Here is the message from the review team..

Your app or its metadata appears to contain misleading content.
Specifically, your app includes content that resembles Stevo The Mad
  Man without the necessary authorization.
Next Steps
You may attach documentary evidence in the App Review Information
  section in App Store Connect. In accordance with section 3.2(f) of the
  Apple Developer Program License Agreement, you acknowledge that
  submitting falsified or fraudulent documentation can result in the
  termination of your Apple Developer Program account and the removal of
  your apps from the App Store. Once Legal has reviewed your
  documentation and confirms its validity, we will proceed with the
  review of your app.
Alternatively, please remove the third-party content from your app and
  its metadata

Now I should mention that Stevo The Mad Man is a influencer based in London and not to get mixed up with Steve-O.
I am working on an official game for Stevo and we've been in constant communication during the development process.
Im just wondering did this game get rejected because there was no proof that I was allowed to make a game based on his likeliness?

A: yes,it got rejected becuase of that,to avoid this.
either delete the refernce,or
 re-upload and write a note in additional note,and provide a written letter from him, stating that the app is his,and he is allowing this content.
other than this they wont ever accept it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: cUrl PHP Get request returning 400 BAD REQUEST but works in Postman I've got a simple API call that accepts parameters in the url and sends a bearer token over in the header.  I've printer out the url and pasted into Postman with the applied bearer token and it works, but from within PHP I keep getting a 400 Bad Request error.  Here is the code:
    $ch = curl_init();
    $authorization = 'Authorization: Bearer oireuoijgosrhj9r9regjoregojgjoislgfjs';
    $validate_url = 'https://api.mycustomapi.com/api/envelopes/validate/' . $auth_id .'/' . $content_hash . '/' . $envelope_id;
    curl_setopt($ch, CURLOPT_URL, $validate_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array($authorization ));
    $response = curl_exec($ch);
    $json = json_decode($response, true);
    $sigVer = $json['signatureVerified'];
    // Check HTTP status code
    if (!curl_errno($ch)) {
        switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
            case 200:  # OK
                echo 'response is: ', $sigVer, "\n";
                break;
            case 502:  # server error
                system_message('Received 500 Error from Server');
                break;
            case 400:  # bad request
                echo 'url is: ', $validate_url, "\n";
                system_message('Simple validation must have exactly one content item');
                break;
            default:
                 echo 'Unexpected HTTP code: ', $validate_url, "\n";
        }
    }
    curl_close($ch);

In Postman I get my expected response... not sure why cUrl Php is acting differently.
'validate_url' evaluates to:
https://api.myapiservice.com/api/envelopes/validate/auth0|5e17f7e988b0e90e9bdf2e12/6767b1944f523e790c8badf608de140599a424d174a2cad87859a7093aba039f7dc2baaab9f114bf371828364636ec654e1be6aff55e7f65140e24bbbf1a3a7e/140
when using this url in postman I get the following json response:
{
    "errorCode": 0,
    "errorMessage": null,
    "envelopeId": 140,
    "blockchainAddress": "0xA300991F77519B5f30552F74779eeEdE398fA59e",
    "clientData": "",
    "signatureVerified": true
}

The only setting in postman I'm setting is the Authorization Bearer token which is set to the same bearer token in my cUrl request.  I didn't use my real token or api url in this post however.
If I do a
var_dump($response);
die();

All I get printed to the screen is
string(800) "
HTTP Status 400 – Bad Request
"

A: Figured out what the issue was.  It was simply that one of the vars that I was inserting into my 'validate_url' string was not being urlencoded and since part of that var has a '/' character in it, it was being interpreted as a bad request.


text:
Q: Combining $lookup aggregation inside updateMany? I have a collection of users like this
[
 { _id: ObjectId("61a6d586e56ea12d6b63b68e"), fullName: "Mr A" },
 { _id: ObjectId("6231a89b009d3a86c788bf39"), fullName: "Mr B" },
 { _id: ObjectId("6231a89b009d3a86c788bf3a"), fullName: "Mr C" }
]

And a collection of complains like this
[
 { _id: ObjectId("6231aaba2a038b39d992099b"), type: "fee", postedBy: ObjectId("61a6d586e56ea12d6b63b68e" },
 { _id: ObjectId("6231aaba2a038b39d992099b"), type: "fee", postedBy: ObjectId("6231a89b009d3a86c788bf3c" },
 { _id: ObjectId("6231aaba2a038b39d992099b"), type: "fee", postedBy: ObjectId("6231a89b009d3a86c788bf3b" },
]

I want to check if the postedBy fields of complains are not existed in users, then update by using the updateMany query
By the way, I have an optional way to achieve the goal but must use 2 steps:
const complains = await Complain.aggregate()
        .lookup({
            from: "users",
            localField: "postedBy",
            foreignField: "_id",
            as: "postedBy",
        })
        .match({
            $expr: {
                $eq: [{ $size: "$postedBy" }, 0],
            },
        });
complains.forEach(async (complain) => {
        complain.type = "other";
        await complain.save();
    });

Therefore, can I combine 2 steps into a single updateMany query? Like $match and $lookup inside updateMany query?

A: With MongoDB v4.2+, you can use $merge to perform update at last stage of aggregation.
db.complains.aggregate([
  {
    "$lookup": {
      from: "users",
      localField: "postedBy",
      foreignField: "_id",
      as: "postedByLookup"
    }
  },
  {
    $match: {
      postedByLookup: []
    }
  },
  {
    "$addFields": {
      "type": "other"
    }
  },
  {
    "$project": {
      postedByLookup: false
    }
  },
  {
    "$merge": {
      "into": "complains",
      "on": "_id",
      "whenMatched": "replace"
    }
  }
])

Here is the Mongo playground for your reference.


text:
Q: How to detect if a user leaves a page in PHP There is this function which i want to execute in case the user leaves a particular page. This function will basically change all of the data within a certain column in my database. So in case the user leaves this page, i want this function to be performed by the system. Is there a way to detect if the user already left the page.
Thanks!

A: With 100% reliability, no, it's not possible. Since leaving a particular page is a client-side operation, you have 0 control over what the client does. You can register an onbeforeunload handler via Javascript and hope that the client browser supports it. But again, support for this isn't universal.

A: You can't do this in php but you could use the javascript function onbeforeunload, here an example
<script type="text/javascript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }
</script>

A: You can't do that using PHP since it's a server-side language.
You will need to use JavaScript.

A: Since server-side php only runs the server script and then sends the result to the browser you can't do this with php alone. You could send an ajax request to your php script with the onunload event using javascript, and then run the php script in response to that request.

A: To cover the cases where the user leaves a particular page to navigate to another one inside the same website, you can try to achieve this using page IDs, store the ID of the "page_to_be_left" in a session var, and check if the current page ID matches the one stored in the session var.
Your function could then be triggered if there is no match.

A: You need to use the javascript function
onbeforeunload


text:
Q: How can I render this object in React? My JSON:
{
    "id": 1,
    "userId": 34,
    "cerealId": 1,
    "metadata": {
        "latitude": "47.484574",
        "longitude": "4.341844",
        "precision": "461.43"
    },
    "createdAt": "2020-07-13T00:00:00.000Z",
    "updatedAt": "2020-07-13T00:00:00.000Z"
}

I need to render the object "metadata" and this is my code:

    import React,{useState,useEffect, Fragment} from 'react';
    import {getCookie} from '../helpers/Helpers';
    import moment from 'moment';
    import { read } from './apiAdmin';

    const IndividualSample = (props) => {

        const token = getCookie('accessToken')  //// <-- right one
        //const Id = getCookie('token')

        const [order, setOrder] = useState({});
        const [error, setError] = useState(false);

        const loadSingleOrder = orderId => {
            read(orderId,token).then( data => {
                if (data.error){
                    setError(data.error)
                } else {
                    setOrder(data)
                }
            })
        }

        const showInput = (key, value) => {
            return (

{key}

                    <input type="text" value={value} className="form-control" readOnly/>

            )
        }

        useEffect (() => {
            const orderId = props.match.params.orderId
            loadSingleOrder(orderId)

        },[props])

        const showSingleSample = () => {
            return (

ID Sample: {order.id}

User ID: {order.userId}

Cereal ID: {order.cerealId}

Created At:{" "}
                                {moment(order.createdAt).locale('es').format('LL')}

METADATA :

                        {order.data?.map((p, pIndex) => (

    I need render this --->         {showInput('Latitude:', p.latitude)}
                                    {showInput('Longitude:', p.longitude)}

 ))}

            )
        }

        return(
            <>

Soy Individual samples

                    {showSingleSample()}
                    {JSON.stringify(order.metadata)}

            </>
        )
    }

I can render the other params cerealId, userId etc. But as I didn't receive the object as an array I don't know how render it in the right way.
I can only see the params in JSON.stringify(order.metadata),but I need to render them inside a div tag.
I can't render the 'metadata'. If someone can help me I will appreciate it!

A: metadata is an object, you will have to use Object.entries (polyfill may be needed):

{ Object.entries(order.metadata).map(([key, value]) => (

{key}: {value}

))}

Also, make sure it's order.metadata or order.data.


text:
Q: CONCAT leading 0 in case statement I found an error in a query I inherited from a previous coworker that I am trying to fix but it's a weird issue I haven't encountered before.. here is a snip of the original query:
CAST(CONCAT(DATEPART(YYYY,getdate()),
  (CASE
    WHEN DATEPART(WW,getdate()) < 10
    THEN CONCAT('0', DATEPART(WW,getdate()))
    ELSE DATEPART(WW,getdate())
   END)
) AS INT)

When getdate() = 2021-01-08 10:16:41.440 the query results in
20212

Expected result should be
202102

I found the issue relies in in the CASE statement. When I tried to change the THEN clause to
CAST(CONCAT(DATEPART(YYYY,getdate()),
  (CASE
    WHEN DATEPART(WW,getdate()) < 10
    THEN RIGHT('0'+ CONVERT(VARCHAR(2), DATEPART(WW,getdate())),2)
    ELSE DATEPART(WW,getdate())
   END)
) AS INT)

I still get
20212

But when I run
SELECT RIGHT('0'+ CONVERT(VARCHAR(2), DATEPART(WW,getdate())),2)

I get
02

Can someone explain this? Why does it work outside of the CASE statement, but not within?

A: case expressions return a single value and that has a single type.  If any of the return values are numbers, then the return value is a number, not a string.
To get a string, use datename():
(CASE WHEN DATEPART(WW, getdate()) < 10
      THEN CONCAT('0', DATENAME(WW,getdate()))
      ELSE DATENAME(WW, getdate())
 END)

Or you could simplify your logic:
RIGHT(CONCAT('0', DATENAME(WW, getdate()), 2)

Or simplify everything.  For instance, a number might be sufficient:
YEAR(GETDATE()) * 100 + DATEPART(WW, getdate())

A: Your query has implicit cast to INT:
CAST(CONCAT(DATEPART(YYYY,getdate()),
  (CASE
    WHEN DATEPART(WW,getdate()) < 10
    THEN RIGHT('0'+ CONVERT(VARCHAR(2), DATEPART(WW,getdate())),2)
    ELSE CAST(DATEPART(WW,getdate()) AS VARCHAR(2))  -- adding explicit cast here
   END)
) AS INT)

A: I can advice the simple way:
SELECT
 CAST(
   CONCAT(
     DATEPART(YYYY,getdate()),
     RIGHT(CONCAT('0000', DATEPART(WW,getdate())), 2)
) AS INT);

You can try T-SQL here


text:
Q: Thrust device_malloc and device_new What are the advantages for using Thrust device_malloc instead of the normal cudaMalloc and what does device_new do?
For device_malloc it seems the only reason to use it is that it's just a bit cleaner.
The device_new documentation says:

"device_new implements the placement new operator for types resident
  in device memory. device_new calls T's null constructor on a array of
  objects in device memory. No memory is allocated by this function."

Which I don't understand...

A: So I think I found out one good use for device_new
It's basically a better way of initialising an object and copying it to the device, while holding a pointer to it on host.
so instead of doing:
Particle *dev_p;
cudaMalloc((void**)&(dev_p), sizeof(Particle));
cudaMemcpy(dev_p, &p, sizeof(Particle), cudaMemcpyHostToDevice);

test2<<<1,1>>>(dev_p);

I can just do:
thrust::device_ptr<Particle> p = thrust::device_new<Particle>(1);
test2<<<1,1>>>(thrust::raw_pointer_cast(p));

A: device_malloc returns the proper type of object if you plan on using Thrust for other things. There is normally no reason to use cudaMalloc if you are using Thrust. Encapsulating CUDA calls makes it easier and usually cleaner. The same thing goes for C++ and STL containers versus C-style arrays and malloc.
For device_new, you should read the following line of the documentation:
 template<typename T>
 device_ptr<T> thrust::device_new (device_ptr< void > p, const size_t n = 1)

p: A device_ptr to a region of device memory into which to construct
  one or many Ts.

Basically, this function can be used if memory has already been allocated. Only the default constructor will be called, and this will return a device_pointer casted to T's type.
On the other hand, the following method allocates memory and returns a device_ptr<T>:
template<typename T >
device_ptr<T> thrust::device_new (const size_t n = 1)


text:
Q: Using COM in ASP.NET, or use a standard DLL instead? We are moving a classic ASP application with VB6 COM objects, over to the .NET world, and we are puzzled about how to migrate our COM objects in as straightforward a manner as possible.  I have found a lot of 'how-to' articles, but not much in the way of 'why' articles.  Are we better off rebuilding the COM objects as standard DLLs which query the database (this is a DB-heavy application), or should we rebuild them as new COM objects in C#?  What are the advantages and disadvantages of each approach?  Is there yet a different approach we should consider?  We are not yet a very strong shop in .NET so any and all suggestions are most welcome.
thanks in advance, Mike

A: This is a hard question, as there are a lot of variables. Let's assume, for this thread, that you have a decent amount of separation of concerns and a set of COM DLLs with decent performance.
Assuming the above and taking your post into account (tons of code in the COM components), the path i would normally look at is rewriting the UI in .NET first and use .NET wrappers to call the COM components. This is easily done by referencing the COM component. Moving to some native DLL method might help if you have a performance problem once wrapped, but it is a more complex direction to set up the code to invoke native methods, so I would not head that route first.
You then have two directions to possibly head. Focus on user stories (usability) or focus on migrating individual libraries (COM DLL >> assembly one at a time). I prefer the story direction, althought you will potentially end up with dead code. Rather than think about migrating, I would rewrite one story at a time, so you are focused on doing it right in .NET. Migration ends up with a lot of COM code written in .NET, which is nasty.
I would consider finding at least one .NET expert, whether hired as an employee or a consultant, so you do not let old habits leak in bad code. This expert should be hired primarily to keep you on the right road and not as another set of coding hands. Not saying the person cannot code, but make sure you do not over utilize this person as a warm body, as his primary job, during development, is to keep you from shooting yourself in the foot. If you can get this person in early, consider hiring someone with some architecture experience to help design the application for .NET. It is more expensive to experiment up front than it is to refactor later.
DON'T try migration programs. They DON'T work. You are not only making a development platform shift, you are making a complete paradigm shift. If you try to use any automated tool to migrate code, you will end up with an inferior application.
One other thing. If you are a VB shop, consider moving to C#. It sounds counter productive, as there is a learning curve, but sticking with VB means you will try to write VB6 in VB.NET. The end result is a bad code base that is hard to refactor.

A: My experience would suggest you should re-write the COM objects into a DLL because the risk is low that something will break during conversion and the time this will take is a LOT shorter than re-writing in C#.
Migrating to .NET can only really be done by hand, but once in a COM DLL you can do this on a part by part basis.


text:
Q: todonotes breaks pgfplots and tikz spy with externalization I want to use todonotes in a document that also uses pgfplots, tikz spy and tikz external. Unfortunately, todonotes breaks the layout of pgfplots figures as illustrated by the following example:
\documentclass{article}
\usepackage{tikz}
\usepackage{todonotes}
\usepackage{pgfplots}
\usepackage{lipsum}
\usepackage{xpatch}

\usetikzlibrary{external}
\usetikzlibrary{spy}

\tikzexternalize
[
  mode=list and make,
  % Does not help
  optimize command away={\todo}{1},
]

% Disable externalization for \todo in order to avoid compilation errors.
\xpretocmd\todo{%
  \bgroup\tikzexternaldisable
}{}{}

\xapptocmd\todo{%
  \egroup
}{}{}

\begin{document}

\begin{figure}[tb]
  \centering
  \begin{tikzpicture}
    [
      spy using outlines={%
        connect spies,
        rectangle,
      }
    ]
    \begin{axis}
      [
        xmin=0,xmax=320,
        ymin=0,ymax=300,
      ]

      \coordinate (spyat) at (292,223);
      \coordinate (magat) at (150,90);
    \end{axis}

    \spy[thick] on (spyat) in node at (magat);
  \end{tikzpicture}
\end{figure}

% Adding todo does not work
\lipsum\todo{foo}\lipsum
% Works!
%\lipsum\lipsum

\end{document}

This is how the figure looks like:

And this is how the figure supposed to look:

One way to avoid the broken layout is either not to use todonotes or to disable externalization altogether. The latter is however not an option.
Is there any other way to overcome the problem?

A: Answering my own question. \pgfsyspdfmark written to the .aux file seems to be responsible for the broken layout. Hence, disabling its usage in externalized documents as follows
\ifthenelse{\equal{\tikzexternalrealjob}{\pgfactualjobname}}{}{%
  \renewcommand\pgfsyspdfmark[3]{}%
}

solves the problem. This check requires the ifthen package.
Alternatively, one can use the \tikzifexternalizing command, as suggested in the comments by Max Snippe:
\tikzifexternalizing{%
  \renewcommand\pgfsyspdfmark[3]{}%
}{}


text: Q: Probability of at least two of n independent events occurring subject to some conditions Given a set of independent Bernoulli random variables $\{x_1, \dots x_n\}$, let $p = \sum_{0<i\leq n}\Pr[x_i = 1]$ and $X=\sum_{0<i\leq n} x_i$. We know that for any $i$, we have $\Pr[x_i = 1]\leq \frac{p}{2}$ and need to find a lower-bound for $\Pr[X>1]$ for any $p \in [0, 2]$. (The lower-bound should be a function of $p$.)


text:
Q: How do I get key-value pair from array of JavaScript objects? I have
var results = {};

I wrote code that populates results (from an HTTP GET request) with data in this format:
({
    "result":[
    {
        "Longitude" : "-097.722382",
        "Zipcode" : "78751",
        "ZipClass" : "STANDARD",
        "County" : "TRAVIS",
        "City" : "AUSTIN",
        "State" : "TX",
        "Latitude" : "+30.310606"
    }
]}
)

However, I want results to have TRAVIS as a key, and then add another variable called count, which counts how many total are in that county.
I'm having trouble accessing keys & values; I always seem to get undefined. How do I go about accessing the keys?
Here's my code. Essentially, I'm going through a bunch of zip codes, filtering out only the ones that are in Texas.
var i = 0;
var results = {};

/*
var results = {
  'TRAVIS': 10,
  'DALLAS': 15,
};

*/

function getValues(obj, key) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getValues(obj[i], key));
        } else if (i == key) {
            objects.push(obj[i]);
        }
    }
    return objects;
}

callback = function(response) {
  //console.log('callback('+i+')');
  var str = '';
  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
      console.log('Processing: ' + i);
      // TODO: Parse JSON
      str = str.replace(/['\(\)]/g, "");
        if(str.substring(0,1) == "{"){

      JSON.parse(str);
}

    if(str.substring(0,1) == "{"){

      if( (str.substring(str.search("\"State\"") + 10, str.search("\"State\"") + 14)) == "\"TX\"")
       {  //console.log("THIS IS FROM TEXAS ");

          results[i] = str;

       }
     }

    setTimeout(function() {
      i++;
      if (i >= data.length) {
        console.log(results);

      } else {
        fetch();
      }
    }, 1000)
  });
}

function fetch() {
  //console.log('fetch('+i+')');
  var options = {
    host: 'gomashup.com',
    path: '/json.php?fds=geo/usa/zipcode/'+ JSON.parse(data[i].zip)
  };
  http.request(options, callback).end();
}

fetch();

A: var response = ({
    "result":[
    {
        "Longitude" : "-097.722382",
        "Zipcode" : "78751",
        "ZipClass" : "STANDARD",
        "County" : "TRAVIS",
        "City" : "AUSTIN",
        "State" : "TX",
        "Latitude" : "+30.310606"
    }
]});

You can excess key and value this way...

console.log(response.result[0].County);
console.log(response.result[0].Zipcode);
And also add a key ......
response.result[0].count = 134;
console.log(response);

A: You can use lodash library to filter your result.
let _ = require("lodash");

let res = {
    result: [
        {
            "Longitude": "-097.722382",
            "Zipcode": "78751",
            "ZipClass": "STANDARD",
            "County": "TRAVIS",
            "City": "AUSTIN",
            "State": "TX",
            "Latitude": "+30.310606"
        },
        {
            "Longitude": "-097.722382",
            "Zipcode": "78751",
            "ZipClass": "STANDARD",
            "County": "TRAVIS",
            "City": "AUSTIN",
            "State": "TX",
            "Latitude": "+30.310606"
        },
        {
            "Longitude": "-097.722382",
            "Zipcode": "78751",
            "ZipClass": "STANDARD",
            "County": "abc",
            "City": "AUSTIN",
            "State": "TX",
            "Latitude": "+30.310606"
        }
    ]
}

function test() {
    let groupedResult = _.groupBy(res.result, 'County')
    result = {}
    _.forEach(Object.keys(groupedResult), (County)=>{
        result[County] = groupedResult[County].length
    })
    console.log(result)
}

test();

A: If you do eval(%yourcode%), it will return you an object which has one key 'result' which is pointing at array with only one value inside - an array with your info pairs. So to access these keys, you have to iterate this object - eval(%yourcode%)['result'][0], like this:

initialString = '({"result":[{"Longitude" : "-097.722382","Zipcode" : "78751","ZipClass" : "STANDARD","County" : "TRAVIS","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"}]})';

myObj = eval(initialString)['result'][0];

for (key in myObj) {
  document.write(key + ': ' + myObj[key] + '
');
}

For example, if you gonna have your result object to contain many objects, you should iterate through (myObj = eval(initialString)['result']), like this:

initialString = '({"result":[{"Longitude" : "1","Zipcode" : "78751","ZipClass" : "STANDARD","County" : "TRAVIS","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "2","Zipcode" : "78751","ZipClass" : "STANDARD","County" : "TRAVIS","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "3","Zipcode" : "78751","ZipClass" : "STANDARD","County" : "TRAVIS","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"}]})';

myObj = eval(initialString)['result'];

myObj.forEach(function(infoItem,index) {
  document.write('Item #' + (index+1) + "
");
  for (key in infoItem) {
    document.write('    ' + key + ': ' + infoItem[key] + '
');
  }
});

Oh, if you want to create 'result' object which will contain county as key and zipcode as value, you can do it this way:

// in this example `myObj` has 3 objects inside itself
// we iterate through each and select values that we need

var initialString = '({"result":[{"Longitude" : "1","Zipcode" : "78751","ZipClass" : "STANDARD","County" : "TRAVIS","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "2","Zipcode" : "37465","ZipClass" : "STANDARD","County" : "SOMECOUNTY","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "3","Zipcode" : "90210","ZipClass" : "STANDARD","County" : "MYBELOVEDCOUNTY","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"}]})',
    result = {};

myObj = eval(initialString)['result'];

myObj.forEach(function(infoItem,index) {
  // here we create entries inside 'result' object
  // using county values as keys
  result[infoItem['County']] = infoItem['Zipcode'];
});

document.write(JSON.stringify(result,null,'
'));

Sorry, i finally got what you need) Look:

// in this example `myObj` has 4 objects inside itself
// we iterate through each and select values that we need

var initialString = '({"result":[{"Longitude" : "1","Zipcode" : "78751","ZipClass" : "STANDARD","County" : "TRAVIS","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "2","Zipcode" : "37465","ZipClass" : "STANDARD","County" : "SOMECOUNTY","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "3","Zipcode" : "90210","ZipClass" : "STANDARD","County" : "MYBELOVEDCOUNTY","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "4","Zipcode" : "90210","ZipClass" : "STANDARD","County" : "MYBELOVEDCOUNTY","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"}]})',
    result = {};

myObj = eval(initialString)['result'];

myObj.forEach(function(infoItem,index) {
  // here we create entries inside 'result' object
  // using county value as a keys

  // first we check if an entry with current key exists
  if (result[infoItem['County']]) {
    // if yes, just increment it
    result[infoItem['County']]++;
  } else {
    // if no, make it equal to 1
    result[infoItem['County']] = 1;
  }
});

document.write(JSON.stringify(result,null,'
'));

A: What about using a library like underscore? The could achieve this with the groupBy and map functions.
var grouped = _.groupBy(response.result, function(item){
  return item.County;
});
var result = _.each(grouped, function(value, key, list){
  return list[key] = value.length;
});

Take a look at this Plunker: http://plnkr.co/edit/fNOWPYBPsaNNDVX3M904

A: since youre using nodejs you could install the string store npm module. It converts it into an array and the values can be used easily. more details here.
https://www.npmjs.com/package/stringstore


text:
Q: How to sumif in arrayformula in different ranges I want to use sumif in an array formula to count the number in these ranges C:C R:AH, these ranges contains numbers from 1 to 10 and "above 10" which I consider it as 11 but I can't name it 11 in the sheet
I tried this equation but it didn't work =ARRAYFORMULA(IF(ROW(A:A)=1,"Count of errors",IF(LEN(A:A),IF(IFERROR(REGEXEXTRACT(TRANSPOSE(QUERY(TRANSPOSE(IFS(ISNUMBER({C:AH}), "♦",{C:C,R:AH}="Above 10","♦" )),, 999^99)), "♦"))="♦", 1, 0), )))
I want the equation to sum the numbers in the range C:C,R:AH as in row 1 in the sample data the columns contain Above 10, 4 & 2 so I need the equation to display 17 and so on
Sample Data: https://docs.google.com/spreadsheets/d/1SksZv0h82j5oEZBj2AN5anDFr80AYNR5ettSwkpUKys/edit?usp=sharing

A: all you need is simple MMULT with SUBSTITUTE for "Above 10":
=ARRAYFORMULA({"Count of errors"; IF(LEN(A2:A),
 MMULT(SUBSTITUTE(C2:AH, "Above 10", 11)*1, TRANSPOSE(COLUMN(C2:AH)^0)), )})

for {C2:C, R2:AH} use:
=ARRAYFORMULA({"Count of errors"; IF(LEN(A2:A),
 MMULT(SUBSTITUTE({C2:C, R2:AH}, "Above 10", 11)*1, TRANSPOSE(COLUMN(Q2:AH)^0)), )})


text:
Q: Embedded C, Bootloader configuration for PIC32MX795F512L In MPLAB, I need to use bootloader for  PIC32MX795F512L. I am able to program boot section into  kseg boot memory till 0x8fc00000 and application code into kseg0_program_mem at 0x9d000000. I can jump from bootloader to application using jump to addr command but I am facing problem while jumping from application to bootloader. I have tried with jump to addr (bootloader address) but it won't work. Please assist me

A: Just use a reset command, it will set you back to the processor start address. Check the POR bits for a SW reset to see if you caused the reset or if the board was just powered on.

A: I found this in one of the many pdf's for my PIC32MX270, I believe it's consistent for the whole PIC32MX family:
/* The following code illustrates a software Reset */
// assume interrupts are disabled
// assume the DMA controller is suspended
// assume the device is locked
/* perform a system unlock sequence */
// starting critical sequence
SYSKEY = 0x00000000; //write invalid key to force lock
SYSKEY = 0xAA996655; //write key1 to SYSKEY
SYSKEY = 0x556699AA; //write key2 to SYSKEY
// OSCCON is now unlocked
/* set SWRST bit to arm reset */
RSWRSTSET = 1;
/* read RSWRST register to trigger reset */
_excep_code = RSWRST;
/* prevent any unwanted code execution until reset occurs*/
while(1);

The while(1) will also lock up the uC so that the watchdog should reset the device if all else fails.  I've got this code in my exception handler too (system_exceptions.c if you are using Harmony), that way when something goes wonky (DMA disaster or you try to sprintf(foo_string, "%f", NAN)), the device will reset instead of becoming a paperweight.


text:
Q: What characters are used in English for a person's name? [Edit]
To be clear, this is not a programing question. What is sought an example of set of rules, a government or a business (in an English speaking locale) uses to determine the acceptable character set of people's names.
I am not trying to limit names, but to understand what limits have been applied  in English speaking locales.
[Edit 2018] I did find one about length:
Hawaiian Woman Gets IDs That Fit Her 36-Character Last Name: the state's cards will have room for 40 characters in "first and last names and 35 characters for middle names,"
Any other examples appreciated.
@Mark Beadles suggested addressing what problem would an answer help one solve.  My primary interest stems from decoding old and new government/business records (death certificates, city directories, phone books), both typed and some hand written.  How would various names using atypical letters get mangled, restricted and how that changed over time to accommodate?  Yet much of that could interpretive and opinionated.  Instead, I am looking for rules, preferable published, that specified what names could be published in some English speaking locales.

Obviously the letters A-Z (upper and lower case) are used in a person's name.
Last names like "Smith-Brown", "Van Buren", "O'Brian" also use -, space and '.
Historical ÆLFRÆD and novel names like "Number 16 Bus Shelter and Violence" push the range of acceptable characters.
I am looking for a modern example of some English speaking country or business (like a phone directory publisher) published rules that define acceptable/non-acceptable characters of a name of more than just the usual A to Z.

Other posts:
What non-alphabetic characters are valid in English spelling? discuses English words, but I suspect names have a broader range. I suspect acceptable characters used in names in English speaking lands have a wider range characters than the rest of the language.
Any other letters lost besides thorn, edh, and yogh? discuses early words.

A: English often changes names little these days (though your examples include one where it did change names earlier, the O' form used in Anglicising names beginning with Ó, like O'Brian for the Irish Ó Briain).
For this reason you can expect all manner of characters to be used in names in English-language contexts.
Characters you can safely prohibit:
Non-characters (obviously, you can prohibit them anywhere you a round-tripping or security requirement doesn't stop you).
Control characters.
Line-separators.
Paragraph-separators.
Characters you can safely normalise:
All space [Zs] characters except Ogham space and ideographic space can be replaced with the "normal" space (U+0020) character.
Aside from that, you'd really be better off allowing even currency symbols; they'd be very unusual, but the could appear in a name, especially if someone uses a name they perform under.
You could opt to prohibit alphabetic characters that aren't Latin, and force people to transcribe into Latin, but you're probably better off if you don't. (You aren't making any customers happier and are making some less happy, since it won't affect those of us whose names are in Latin letters, but will annoy those whose names are not).
Besides which, what if you're successful enough to have to widen your support to other languages in the future? You'll just have to loosen such a rule again when that happens.


text:
Q: Create multiple arrays from one set I have an array of items, each have an item_type property that could be one of four different types (this is a cart of items). When I attempt to "pay" for the items in the cart, I need to separate all the items remaining into arrays of each item type to send back to the server so the proper tables can be updated. I was just going to use a map to do this but that would require multiple passes (at least the way I was thinking I needed to do it) but is there a quicker way to take one array and split it into multiple arrays based on a property?
Specifically I need to know which array is which (which one has raffle tickets, donations, etc.) so I can post them to the server with the correct property name so the server knows what array is what and how to proceed with each.
Currently in ember this is how I am working through this. Not a lot of code but still I wonder if there is some refactoring that can be done here
// ARRAYS OF CLASSES
itemsArray: Ember.computed.filterBy('model.items','item_type','bid'),
donationsArray: Ember.computed.filterBy('model.items','item_type','donation'),
ticketsArray: Ember.computed.filterBy('model.items','item_type','ticket'),
rafflesArray: Ember.computed.filterBy('model.items','item_type','raffle'),

// ARRAYS OF JUST CLASS IDS
itemIds: Ember.computed.mapBy('itemsArray','id'),
donationIds: Ember.computed.mapBy('donationsArray','id'),
ticketIds: Ember.computed.mapBy('ticketsArray','id'),
raffleIds: Ember.computed.mapBy('rafflesArray','id'),

A: Ok, so first of all your code is absolutely fine.
I was interested in comparing performance of using observer instead of creating 4 computed properties, so I created this twiddle. I haven't found good way to be absolutely sure 1 way is absolutely faster than another, but you here's another way you could use in your code.
createArrays: Ember.on('init', Ember.observer('model.items.@each.item_type', function() {
    console.log('observer fired');
    const items = this.get('model.items'),
          itemsArray = [],
          donationsArray = [],
          rafflesArray = [],
          ticketsArray = [];

    items.forEach(item => {
        switch (Ember.get(item, 'item_type')) {
        case 'bid':
          itemsArray.pushObject(item);
          break;
        case 'donation':
          donationsArray.pushObject(item);
          break;
        case 'ticket':
          ticketsArray.pushObject(item);
          break;
        default:
          rafflesArray.pushObject(item);
          break;
      }
    });

    this.setProperties({
      itemsArray,
      donationsArray,
      ticketsArray,
      rafflesArray
    });
  })),

But I don't think it's worth changing to.
Another thing you could do is programatically create those 8 computed properties, but it would be more code than it is now probably. If you would have 10 instead of 4 item_type's it would be worth to do.


text:
Q: Compiler says a parameter is type struct ** when I defined it as struct * I think I might be misunderstanding how passing pointers as parameters in C functions works. In the past I have cheated and used global variables and large, single C files with all of the functions in it. I am trying to learn how to use separate C files and link them into a single executable.
Room is a typedeffed struct.
I have prototyped the function in a guarded header file called functions.h:
void init_rooms(Room *rooms[], Room *current_room);
/* (pointer to the room struct array, pointer to current room) */

I then included that header both in main.c and functions.c.
The function definition in functions.c is:
void init_rooms(Room *rooms[], Room *current_room){
current_room = rooms[0];
...}

I call the function in main.c like this:
Room * current_room; /* pointer to current player location */
Room * rooms = malloc(sizeof(struct room)*NUM_ROOMS); /* allocate memory for rooms */
init_rooms(rooms, current_room);

And I get this error:
main.c|11|error: incompatible pointer types passing 'Room *' (aka 'struct room *') to parameter of type 'Room **' (aka 'struct room **'); take the address with & [-Werror,-Wincompatible-pointer-types]|

Now, I'm pretty sure I haven't defined any pointers to pointers here, and it looks to me like I've got the types all the same. Why is the compiler saying that the parameter is **type?
I'm using Clang on Linux, if that makes any difference.
EDIT: I also tried dereferencing the pointers as the compiler suggested, but it then gave me a different error.

A: init_rooms() doesn't take a Room *. It takes an array of them (Room *rooms[]), which is essentially equivalent to
void init_rooms(Room **rooms, Room *current_room);

Without seeing the rest of the code, there's a good chance you want that function to begin:
void init_rooms(Room *rooms, Room *current_room)
{
  current_room = rooms;

but be aware that current_room will only be changed inside the function. If you want its value to change outside, do this:
void init_rooms(Room *rooms, Room **current_room)
{
  *current_room = rooms;

and call it as:
init_rooms(rooms, &current_room);

A: The problem lies in the function argument: Room *rooms[]
In C, arrays are just pointers - and an array of pointers, is just a pointer to a pointer... :)
In your case, defining Room *room[] is the same as Room **room
You might want to change it to Room *rooms


text:
Q: Notificação em uma certa hora sem necessidade de abrir o programa package com.example.dell.notification;
import android.annotation.TargetApi;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.format.Time;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.Button;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState)  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   String currentDateandTime = sdf.format(new Date());

if(currentDateandTime=="2015-05-15"){

}
            showNotification();

}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void showNotification(){

    // define sound URI, the sound to be played when there's a notification
    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    // intent triggered, you can add other intent for other actions
    Intent intent = new Intent(MainActivity.this, NotificationReceiver.class);
    PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);

    // this is it, we'll build the notification!
    // in the addAction method, if you don't want any icon, just set the first param to 0
    Notification mNotification = new Notification.Builder(this)

            .setContentTitle("Vigilia dos Obreiros")
            .setContentText("Hoje, as 22 horas")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent)
            .setSound(soundUri)

            .addAction(R.drawable.abc_ic_ab_back_mtrl_am_alpha, "View", pIntent)
            .addAction(0, "Remind", pIntent)

            .build();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // If you want to hide the notification after it was selected, do the code below
    // myNotification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, mNotification);
}

public void cancelNotification(int notificationId){

    if (Context.NOTIFICATION_SERVICE!=null) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
        nMgr.cancel(notificationId);
    }
}
}

A: Defina um AlarmManager para chamar um BroadcastReceiver que lançará a notificação:
//Definir a data
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.MONTH, 5);
calendar.set(Calendar.DAY, 15);
//calendar.set(Calendar.HOUR_OF_DAY,10) //Se quiser indicar a hora
//calendar.set(Calendar.MINUTE,25)//Se quiser indicar os minutos
Intent intent = new Intent(MainActivity.this, LancaNotificacoaReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(MainActivity.this,0, intent,0);

AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

//Definir o alarme para acontecer no dia determinado
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pIntent);

Defina o BroadcastReceiver LancaNotificacoaReceiver e no método onReceive crie a notificação:
public class LancaNotificacoaReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        //      código da notificação
    }

}

Não esquecer de registar o BroadcastReceiver no AndroidManifest.xml
<receiver android:name="a_sua_package.LancaNotificacoaReceiver"/>


text:
Q: restart count in php for each item I need the code to restart count for each $item
My code is:
 $count = 0;
 $folders = @scandir('Users/');
 foreach($folders as $item){
   if (preg_match("/.*\.php$/",$item)) continue;
   echo $item;
   if (is_dir("Users/$item")){
     $target_folders = @scandir("Users/$item/uploaded/");
     foreach($target_folders as $target_item){
       if ((!preg_match("/^[.]/",$item)) ||(!is_dir("Users/$item/uploaded/$target_item"))) $count++;
     }
   }
 }

if this can be done the help would be much appreciated. this is the last little bit on my project.

A: Set the $count variable equal to zero inside the first foreach loop ( as u_mulder suggested )
$count = 0;
$folders = @scandir('Users/');

foreach($folders as $item){

      $count = 0;
      if (preg_match("/.*\.php$/",$item))
           continue;

      echo $item;

      if (is_dir("Users/$item")){

           $target_folders = @scandir("Users/$item/uploaded/");
           foreach($target_folders as $target_item){

                if ((!preg_match("/^[.]/",$item)) || (!is_dir("Users/$item/uploaded/$target_item")))
                     $count++;

           }
      }
 }

A: Try this:
$count_result=array();
$path = "Users";
$folders = @scandir("$path");
if ($folders) {
    foreach ($folders as $item) {
        $count = 0;
        if ((substr($item, 0, 1) == '.') || (preg_match("/\.php$/", $item)))
            continue;

        if (is_dir($path . "/" . $item)) {
            echo "$item<br>";

            $target_folders = @scandir($path . "/" . $item . "/uploaded/");
            if ($target_folders) {
                foreach ($target_folders as $target_item) {
                    if ((substr($target_item, 0, 1) == '.') || is_dir("$path/$item/uploaded/$target_item"))
                        continue;
                    $count++;

                }
            }
            $count_result[$item]=$count;

        }
    }
}

var_dump($count_result);


text:
Q: Function call, where are parentheses I have following code snippet:
def now = System.currentTimeMillis

When I want to invoke the now function in REPL, just
now

why not
now()

and shows the error
<console>:9: error: Long does not take parameters
              now( )


text:
Q: Select random sample by ID`s I have a dataframe with 811777 rows and 133 different worker IDs. My dataframe looks like this:
  PERS_ID           NEU_DATUM
 1      22 2022-03-01 00:00:00
 2      22 2022-03-01 00:00:00
 3      22 2022-03-01 00:00:00
 4      22 2022-03-01 00:00:00
 5      22 2022-03-01 00:00:00
 6      22 2022-03-01 00:00:00
 7      22 2022-03-01 00:00:00
 8      22 2022-03-01 00:00:00
 9      22 2022-03-01 00:00:00
10      22 2022-03-01 00:00:00

In the first 10 rows u can only see one worker with the ID "22", but like I said above my df has 133 different worker IDs. I want to take 50 random worker IDs and create a new df. But I don´t want one row for one ID. Instead I want every row that has that worker ID. So basically my new df should consist of 50 random worker IDs and I want every row of these workers. I already tried with the sample code but I failed :(. Thanks in advance!

A: If your data are df, you can do the following:
df[df$PERS_ID %in% sample(unique(df$PERS_ID), 50),]

or with data.table
library(data.table)
setDT(df)[PERS_ID %in% sample(unique(PERS_ID),50)]

or with dplyr:
library(dplyr)
df %>% filter(PERS_ID %in% sample(unique(PERS_ID),50))

You can also do this using a join approach; one such approach using dplyr is shown below:
inner_join(
  df,
  df %>% distinct(PERS_ID) %>% slice_sample(n=50)
)


text:
Q: Ubuntu 20.10 System Security services are failing Good morning,
$ systemctl --failed:
  UNIT                                                  LOAD   ACTIVE SUB    DESCRIPTION
● fwupd-refresh.service                                 loaded failed failed Refresh fwupd metadata and update motd
● snap.canonical-livepatch.canonical-livepatchd.service loaded failed failed Service for snap application canonical-livepatch.canonical-livepatchd
● sssd.service                                          loaded failed failed System Security Services Daemon

$ sudo systemctl status fwupd-refresh.service:
● fwupd-refresh.service - Refresh fwupd metadata and update motd
     Active: failed (Result: exit-code) since Tue 2020-12-15 15:06:26 EET; 28min ago
       Docs: man:fwupdmgr(1)
   Main PID: 5120 (code=exited, status=1/FAILURE)
Dec 15 15:05:24 {NAME} systemd[1]: Starting Refresh fwupd metadata and update motd...
Dec 15 15:05:25 {NAME} fwupdmgr[5120]: Updating lvfs
Dec 15 15:06:26 {NAME} systemd[1]: fwupd-refresh.service: Main process exited, code=exited, status=1/FAILURE
Dec 15 15:06:26 {NAME} systemd[1]: fwupd-refresh.service: Failed with result 'exit-code'.
Dec 15 15:06:26 {NAME} systemd[1]: Failed to start Refresh fwupd metadata and update motd.

$ sudo systemctl status snap.canonical-livepatch.canonical-livepatchd.service:
● snap.canonical-livepatch.canonical-livepatchd.service - Service for snap application canonical-livepatch.canonical-livepatchd
     Loaded: loaded (/etc/systemd/system/snap.canonical-livepatch.canonical-livepatchd.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Tue 2020-12-15 14:25:29 EET; 1h 12min ago
   Main PID: 2170 (code=exited, status=1/FAILURE)
Dec 15 14:25:29 {NAME} systemd[1]: snap.canonical-livepatch.canonical-livepatchd.service: Scheduled restart job, restart counter is at 6.
Dec 15 14:25:29 {NAME} systemd[1]: Stopped Service for snap application canonical-livepatch.canonical-livepatchd.
Dec 15 14:25:29 {NAME} systemd[1]: snap.canonical-livepatch.canonical-livepatchd.service: Start request repeated too quickly.
Dec 15 14:25:29 {NAME} systemd[1]: snap.canonical-livepatch.canonical-livepatchd.service: Failed with result 'exit-code'.
Dec 15 14:25:29 {NAME} systemd[1]: Failed to start Service for snap application canonical-livepatch.canonical-livepatchd.

$ sudo systemctl status sssd.service:
● sssd.service - System Security Services Daemon
     Loaded: loaded (/lib/systemd/system/sssd.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Tue 2020-12-15 14:25:21 EET; 1h 13min ago
   Main PID: 1760 (code=exited, status=4)
Dec 15 14:25:21 {NAME} systemd[1]: sssd.service: Scheduled restart job, restart counter is at 6.
Dec 15 14:25:21 {NAME} systemd[1]: Stopped System Security Services Daemon.
Dec 15 14:25:21 {NAME} systemd[1]: sssd.service: Start request repeated too quickly.
Dec 15 14:25:21 {NAME} systemd[1]: sssd.service: Failed with result 'exit-code'.
Dec 15 14:25:21 {NAME} systemd[1]: Failed to start System Security Services Daemon.

EDIT: just found the following answer for sssd since I am using HDD not SSD... and Yes, I know 20.10 isn't LTS so I can't enjoy the livepatch but did the service fail for this reason?


text:
Q: Why is the square wave signal so distorted at the output of a push-pull pair? I have this example circuit on my workbench:

simulate this circuit – Schematic created using CircuitLab
If I remove the RLOAD=1K resistor, then the output signal gets distorted.
Yellow is Node1 and blue is node2. With R load:

Without R load:

It is not easy to read from the picture but the lower part of the square signal starts at 600mV (one junction) and slowly goes down to about 50mV. Here is it zoomed:

The same thing happens at node1 too, but I'm less concerned about that. I wonder why there is distortion when there is no load?

A: Think about what the load resistor is doing. Without that resistor, how are you going to put base current into either transistor and turn Q2 and Q3 on properly. With the resistor, Q2 can be effectively turned on and that same resistor acts as a decent pull-down when Q3 is supposedly being activated. Without proper base biasing you won't have a decent push pull stage. Try using a 10 kohm in parallel with collector/emitter on each transistor to see what happens. Or, alternatively try biasing the bases as per how a class AB stage operates.


text:
Q: Psycopg2 is passing parameters to SQL queries - Is anyone able to tell me what is wrong with this sql statement? I get the following error:
psycopg2.errors.SyntaxError

psycopg2.errors.SyntaxError: syntax error at or near "%"
LINE 1: ... pt, gss.shapes g WHERE st_contains(geom,pos) AND %(postcode...
                                                             ^

When I run the following on pgAdmin:
Select DISTINCT gss, description, postcode
FROM postcodelatlng pt, gss.shapes g
WHERE st_contains(geom,pos)
AND %(postcode)s~* '(\y(?:[A-PR-UWYZ](?:[A-HK-Y]?\d{1,2}|\d[A-HJKMNP-Y]|[A-HK-Y]\d[ABEHMNPRV-Y]))(?:\s*\d[ABD-HJLNP-UW-Z]{2})\y)' limit 50

A: I think you're not using the correct syntax for passing parameters in psycopg2. The correct syntax (in Python) is something like
cur.execute("SELECT * from mytable WHERE mycolumn = %s", (myvalue,))

OR
cur.execute("""SELECT * from mytable
              WHERE mycolumn = %(data)s""", {'data':myvalue})

The second one is called %(name)s placeholder. name has to be a dictionary key, not a variable. So I think your code has to become something like
postcodevar = input('Please enter postcode: ')
cur.execute("""SELECT DISTINCT gss, description, postcode
                 FROM postcodelatlng pt, gss.shapes g
                WHERE st_contains(geom,pos)
                  AND %(postcode)s~* '(\y(?:[A-PR-UWYZ](?:[A-HK-]?\d{1,2}|d[A-HJKMNP-Y]|[A-HK-Y]\d[ABEHMNPRV-Y]))(?:\s*\d[ABD-HJLNP-UW-]{2})\y)'
                LIMIT 50""", {'postcode': postcodevar})


text:
Q: Neo4j merge nodes by relationship I have big dataset of persons data and found a lot of duplicates by an algorithm.
I marked these duplicates in Neo4j with a relationship.
Example:
(p:Person)-[:similar]->(d:Person)
For testing purpose I created virtual nodes by combining all nodes marked with the similar-relationship.
CALL algo.unionFind.stream('Person', 'similar', {})
YIELD nodeId, setId
WITH setId AS idd, collect(algo.getNodeById(nodeId)) AS nodis
WHERE size(nodis) > 1
CALL apoc.nodes.collapse(nodis,{properties:'combine'}) YIELD from, rel
RETURN idd, from, rel

Here I found the problem, that only two nodes were compared and stored in the result data.
Example:
ID: 5, Peter Smith
ID: 4635, Peter Smit
ID: 4635, Peter Smit
ID: 765, Peter Smith
ID: 5, Peter Smith
ID: 765, Peter Smith
I want to refactor the graph and merge the duplicates (a forrest) into one node. But only one node is merged. How can I merge all forrests, that exist due to the relationship 'similar'?
UPDATE:
I found a semi solution. All similar persons were merged by the following code. All properties were combined as a list. Seems fine to me, except, that the Ids are in a list now, too - but this isn't the topic of the question.
CALL algo.unionFind.stream('Person', 'similar', {})
YIELD nodeId,setId
WITH setId AS idd, collect(algo.getNodeById(nodeId)) AS nodis
CALL apoc.refactor.mergeNodes(nodis, {properties:'combine', mergeRels: true}) YIELD node
RETURN node

A: How about using constraints unique?
I also faced same problems with MERGE.
example)
CREATE CONSTRAINT ON ( book:Book) ASSERT book.isbn IS UNIQUE


text:
Q: Multiplayer Minecraft on Xbox 360 So I am trying to play multiplayer split screen offline (local play). I have the TV set up with the HDMI cable and everything, and my TV is 1080 and up, so everything resolution wise is supported. Then i open a world and start. But when I go to press start on the other controller, the normal "Press Start" thing doesnt come up, instead nothing comes up. Help?

A: Is your second controller synced to your Xbox 360? If this controller is not synced the console will not take inputs from it and the "Start" button cannot be used to load a second player into the game.
Refer to this guide on how to Sync your Xbox 360 controller
Alternatively, you may have reached the maximum amount of players on your Minecraft world. On Xbox 360 there is an 8 player limit on a Minecraft multiplayer world. If you attempt to exceed this by adding a 9th player via split-screen you may be prevented from having them join.
If that doesn't work try restarting your game or console.

A: *

*Make sure all controllers are on and logged in.

*If this is not the problem, try pressing start a few times anyway, it doesn't always show up.


text:
Q: Estimating $\beta_o$ and $\beta_1$ with Weighted Least Squares with Logit link I showed that $\hat\beta_0$ and $\hat\beta_1$ must satisfy:
$$\sum w_i\hat\beta_0+\sum w_ix_i\hat\beta_1=\sum w_iy_i$$
and
$$\sum w_ix_i\hat\beta_0+\sum w_ix_i^2\hat\beta_1=\sum w_i x_i y_i$$
I need to fit a model where $r_i/n_i$ is the proportion dead at dose $d_i$. Let $x_i=\log d_i$,$1/w_i=\operatorname{Var}(Y_i)$ and $$p_i=\frac{r_i+1/2}{n_i+1}$$
I also showed that $\operatorname{logit}(p_i)$ has expectation $\operatorname{logit}(\theta_i)=\beta_0+\beta_1x_i$ and variance $\frac{1}{n\theta_i(1-\theta_i)}$
Approximated variance of $w_i=np_i(1-p_i)$

Now I need to estimate $\hat\beta_0$ and $\hat\beta_1$

My attempt:
What are the fitted values : $y_i$? They are $\operatorname{logit}(p_i)$, the observed proportions. Now I need to fit a least square line with axis $\operatorname{logit}(p_i)$ against $x_i$.
Rearranging the estimates I have:
$$\hat\beta_0=\frac{\sum w_iy_i-\sum w_ix_i\hat\beta_1}{\sum w_i}$$ and
$$\hat\beta_1=\frac{\sum w_i x_i y_i-\sum w_ix_i\hat\beta_0}{\sum w_ix_i^2}$$
Now I don't know how to proceed, do I need to put summs inside summs or is there an easy way?
What will the plotted line be? Is it the expected proportion of deaths $Y$ given some dose best supported by our data?
EDIT:I know it's a horrible expression, but is it valid?
Can I simply say:
$$\hat\beta_1=\frac{\sum w_i x_i y_i-n\frac{\sum w_iy_i-\sum w_ix_i\hat\beta_1}{\sum w_i}\sum w_ix_i}{\sum w_ix_i^2}$$
Simplifying:
$$\hat\beta_1-n\frac{\sum w_ix_i \sum w_ix_i\hat\beta_1}{\sum w_i\sum w_ix_i^2} =\frac{\sum w_i x_i y_i-n\frac{\sum w_iy_i}{\sum w_i}\sum w_ix_i}{\sum w_ix_i^2}$$
And again:
$$\hat\beta_1(1-n\frac{\sum w_ix_i \sum w_ix_i}{\sum w_i\sum w_ix_i^2}=\frac{\sum w_i x_i y_i-n\frac{\sum w_iy_i}{\sum w_i}\sum w_ix_i}{\sum w_ix_i^2}$$

A: If $Y = X\beta+\epsilon,$ and $var(Y_i)=1/w_i$ and $cov(Y_i, Y_j)=0$, then $cov(Y)=\sigma^2 \times diag(1/w_1,...,1/w_n)$, as such the "correction" $V^{-1/2}$ matrix should be of the form $V^{-1/2}=diag(\sqrt{w_i},...,\sqrt{w_i})$ because now
$$
cov(V^{-1/2}Y)=V^{-1/2}cov(Y)V^{-1/2}=\sigma^2 I.
$$
Therefore, the WLS will be
$$
\beta_{WLS} = (X'V^{-1}X)^{-1}X'V^{-1}y,
$$
where $V^{-1} =diag(w_1,...,w_n)$ and $X$ is the usual design matrix of a form $X=[\mathbb{\vec{1}}, \mathbb{\vec{x}}]$. After some algebra you should get
$$
\beta_{WLS} =
\begin{pmatrix}
\sum w_i & \sum x_iwi\\
\sum x_iw_i & \sum x_i^2w_i
\end{pmatrix}
\begin{pmatrix}
\sum w_iy_i\\
\sum x_iw_iy_i
\end{pmatrix}.
$$
I guess you can compare it to your final result to reassure the calculations.


text:
Q: Column Spacing/Padding I am trying to get my column padding closer together however I have padding set to 0 and theres still a gab in between. I want to make it so the columns are close to eachother no matter what screen sizer and theres 2 items per row. Doesnt even show the words of second row

HOW I WORK

Research

Understand the problem, empathize with the person. Explore the competitive landscape.
                        Identify strategic opportunities. Define design goals/requirements.

Design

Combine effective interfaces, smart interactions, and consistent visual language into
                         a captivating design that resonates with the target audience.

Build

Map design to code. Smooth constraints. Solve edge cases. Move that button 3 pixels to the left. Fill
                        the gap between functional and delightful.

Refine

Test prototypes with real people against actual problems. Combine insights with gut intuition and experience.
                        Iterate and improve in pursuit of perfection.

https://jsfiddle.net/kdb4raLx/1/

A: It could be due to your ptext seems that is a culprit


text:
Q: Downloading Image from CSV file I am trying to download all the images in a CSV file to my computer. Unfortunately, it seems that because the first row contains a header instead of a link, it doesn't work. Could you please help me fix my mistake?
   import csv
    import requests
with open('abc.csv') as csvfile:
    csvrows = csv.reader(csvfile, delimiter=',', quotechar='"')
    for row in csvrows:
        filename = row[1]
        url = row[2]
        print(url)
        result = requests.get(url, stream=True)
        if result.status_code == 200:
            image = result.raw.read()
            open(filename,"wb").write(image)

Below is my abc.csv file:
    identifier                             link           likes_count   company
0   2292512316069378197 https://www.instagram.com/p/B_Qo84ihfiV 9608    Nike
1   2292462538514040606 https://www.instagram.com/p/B_QdohlBQce 9462    Nike
2   2292418655784545069 https://www.instagram.com/p/B_QTp8mhCst 22033   Nike
3   2292372137723669561 https://www.instagram.com/p/B_QJFBSBaw5 14112   Nike
4   2292334760619881771 https://www.instagram.com/p/B_QAlHJBzUr 5974    Nike

... ... ... ... ...


text:
Q: PyTest for tables in Python I am new to Python, and I am trying to write a test function for print_table function. The test fails, and I cannot figure out why. Can anyone please help me?
Here is the error:

AssertionError: assert '\x1b(0lqqqqq...qqqqqqj\x1b(B' == '┌──────────┬...──────────┘\n'

script.py
from terminaltables import SingleTable

TABLE_DATA = (
('Platform', 'Years', 'Notes'),
('Mk5', '2007-2009', 'The Golf Mk5 Variant was\nintroduced in 2007.'),
('MKVI', '2009-2013', 'Might actually be Mk5.'),
)

def print_table(TABLE_DATA):
  table_instance = SingleTable(TABLE_DATA)
  table_instance.justify_columns[2] = 'right'
  return table_instance.table

test_printer.py
from script import print_table

def test_table():
  data = [
     ('Platform', 'Years', 'Notes'),
     ('Mk5', '2007-2009', 'The Golf Mk5 Variant was\nintroduced in 2007.'),
     ('MKVI', '2009-2013', 'Might actually be Mk5.'),
    ]

    assert  print_table(data)== "\n".join([
    "┌──────────┬───────────┬──────────────────────────┐",
    "│ Platform │ Years     │                    Notes │",
    "├──────────┼───────────┼──────────────────────────┤",
    "│ Mk5      │ 2007-2009 │ The Golf Mk5 Variant was │",
    "│          │           │      introduced in 2007. │",
    "│ MKVI     │ 2009-2013 │   Might actually be Mk5. │",
    "└──────────┴───────────┴──────────────────────────┘"
   ])

A: The characters being compared are not actually the same, unfortunately. For simplicity, consider the first character:
from script import print_table

def test_table():
    data = [
     ('Platform', 'Years', 'Notes'),
     ('Mk5', '2007-2009', 'The Golf Mk5 Variant was\nintroduced in 2007.'),
     ('MKVI', '2009-2013', 'Might actually be Mk5.'),
    ]

    test = print_table(data)

    expected = "\n".join([
            "┌──────────┬───────────┬──────────────────────────┐",
            "│ Platform │ Years     │                    Notes │",
            "├──────────┼───────────┼──────────────────────────┤",
            "│ Mk5      │ 2007-2009 │ The Golf Mk5 Variant was │",
            "│          │           │      introduced in 2007. │",
            "│ MKVI     │ 2009-2013 │   Might actually be Mk5. │",
            "└──────────┴───────────┴──────────────────────────┘"
           ])

    assert test[0] == expected[0]

This will give you:
>       assert test[0] == expected[0]
E       AssertionError: assert '\x1b' == '┌'
E         - ┌
E         +

test_printer.py:23: AssertionError

A: Python does not automatically recognize when you have an 'Enter' character between strings. You need to specify "\n" string. Also, when you break a single line of code into multiple lines, as you have done here, you need to specify a line continuation character '' at the end of the line.
Try with this revised function definition:
def test_table():
data = [ \
 ('Platform', 'Years', 'Notes'), \
 ('Mk5', '2007-2009', 'The Golf Mk5 Variant was\nintroduced in 2007.'), \
 ('MKVI', '2009-2013', 'Might actually be Mk5.'), \
]

assert  print_table(data)== "\n".join([
"┌──────────┬───────────┬──────────────────────────┐\n", \
"│ Platform │ Years     │                    Notes │\n", \
"├──────────┼───────────┼──────────────────────────┤\n", \
"│ Mk5      │ 2007-2009 │ The Golf Mk5 Variant was │\n", \
"│          │           │      introduced in 2007. │\n", \
"│ MKVI     │ 2009-2013 │   Might actually be Mk5. │\n", \
"└──────────┴───────────┴──────────────────────────┘\n"  \

])


text:
Q: Zalenium idleTimeout property use? Does Zalenium idleTimeout property means that the container would be alive for the configured timeout period.
If I set capabilities.setCapability("idleTimeout",120);
Does this mean, that Zalenium would identify the container as 'Zalenium Test Completed' after 120 secs.
So, if my testcase is a lengthy one which spans beyond 120 secs, does Zalenium allow the testcase to proceed further or will it shutdown the container.
This is what I observed while executing lengthy testcases using Zalenium.
Can somebody please help me with a response to this query?

A: idleTimeout is the length of time a session can stay alive without receiving new commands. It is not related to the total length of the test.


text:
Q: hiding Tabbar during navigation My main screen has got AppBar and BottomNavigationBar. if I navigate to screen 2 BottomNavigationBar is staying. It is perfect for me.
But I would like to remove the Tabbar for screen 2. Because the content of Screen 2 is irrelevant with the TabbarMenu.
I am going to screen 2 from screen 1 return Page2 like this:
Widget showPage(int selectedPage) {
    if (selectedPage == 0) {
      return const NewsView(id: '1');
    } else if (selectedPage == 1) {
      return const Settings();

any help?


text:
Q: Groovy rest client without libraries with basic authentication Hello I need to connect to an url using a basic authentication with Groovy, I would prefer to achieve this without using any libraries, because in our project we have scan for vulnerabilities and some times we faced problems when we include a new library. I was following the next examples:
 def connection = new URL( "https://jsonplaceholder.typicode.com/posts")
        .openConnection() as HttpURLConnection

    // set some headers
    connection.setRequestProperty( 'User-Agent', 'groovy-2.4.4' )
    connection.setRequestProperty( 'Accept', 'application/json' )

    // get the response code - automatically sends the request
    println connection.responseCode + ": " + connection.inputStream.text

It worked but in my case I need to connect with a basic authentication (username and password). I haven't seen examples related.
Any ideas?
Thanks!

A: https://en.wikipedia.org/wiki/Basic_access_authentication
In basic HTTP authentication, a request contains a header field in the form of
Authorization: Basic <credentials>

where <credentials> is the Base64 encoding of ID and password joined by a single colon :.
in groovy it could look like this:
def user = ...
def pass = ...
def auth = "${user}:${pass}".bytes.encodeBase64()
connection.setRequestProperty("Authorization", "Basic ${auth}")


text:
Q: Magento 2 hacked with script in  hacked I can't seem to locate how this script is getting into the head section of my site but it's stealing credit cards. I've grepped the entire codebase and searched the entire database for "seooptimization" and found nothing so it must be added via createElement somewhere? What's interesting is it's added in the middle of all my theme js files. Can anyone help me track this down and figure out how to avoid it getting into the head of my site because I've chased it around for months now. I've removed it from the cms_block in the database, from miscellaneous scripts in the admin and they just keep finding new ways to put it on the site, now I can't even track it down to get it off. Here's what it looks like.
<script src="https://mage-seooptimization.com/events" id="magento-init"></script>

EDIT: So I finally was able to remove this. I found it in the database in one of my footer blocks in the cms_block table. It was disguised as follows:
<script>var meta_tags = ["0604104A124B2257060A0F021D1605114537","4B030D1849001802451A57514D014C164C0604181E040D59124A5D50", "19034A475057444D120B0405190E5E090D090002101F0B4C1A", "11110A04001B1C5E0C0C0E040E36164D1131192B50591E140B", "0245065705191A05080704154D0F1117420B5C12571317070B15", "15200E0F0C1317044D4519020410001145435A1757030016", "3111161808140C04004A4D12041A5749", "570D161E1105435F4A0F0B06135403000D051102101D0C180B151F161E4B01050C591C06000C1E1251504B", "114B110F15370D04170B0814021C58420B0E465A5E1D04050F0F0216", "5D0C0C031551504B014C0204171D5E04121A04181D33", "180C0E0E4917504B07100F001D044B"];</script>

Maybe someone can comment on how that could possibly end up being a script in the head section of the site?
Also, this doesn't solve how it got there in the first place. Are there any known methods to inject code into the database for Magento 2.2.6 that may need patched? As far as I know I have all available patches applied.
List of enabled modules:
Aitoc_DimensionalShipping | EkoUK_ImageCleaner | Experius_WysiwygDownloads | FishPig_WordPress | FishPig_WordPress_RelatedProducts | MagePal_GuestToCustomer | MagePsycho_Customshipping | Amasty_Base | Amazon_Core | Amazon_Login | Amazon_Payment | FME_Faqs | Bold_OrderComment | Klarna_Core | Klarna_Ordermanagement | Magefan_LoginAsCustomer | Amasty_CronScheduleList | FME_Prodfaqs | Amasty_GiftCard | Klarna_Kp | Ebizmarts_MailChimp | Dotdigitalgroup_Email | Mageplaza_Core | Mageplaza_Smtp | Magiccart_Alothemes | Magiccart_Magicmenu | Magiccart_Magicproduct | Magiccart_Magicslider | Magiccart_Shopbrand | Magiccart_Testimonial | Mirasvit_Core | Mirasvit_Misspell | Mirasvit_Report | Mirasvit_Search | Mirasvit_SearchAutocomplete | Mirasvit_SearchLanding | Mirasvit_SearchMysql | Mirasvit_SearchReport | Mirasvit_SearchSphinx | Mirasvit_SearchUltimate | ShipWorks_Module | Temando_Shipping | VNS_Custom | Vertex_Tax | WeltPixel_Backend | WeltPixel_Maxmind |

A: *

*First of all scan your website with the available tools like

*

*SiteCheck

*MageReport

*UnmaskParasites

*Foregenix

*Github Magento Malware Scanner

*MageScan

*VirusTotal

then you will get some idea on malware and security issues for your website.

*Please ask your hosting provider for a detail report on Website security.

*You can check Magneto file and folder permission as well from your end and male it proper by running the following commands:
find . -type f -exec chmod 644 {} \;             // 644 permission for files
find . -type d -exec chmod 755 {} \;             // 755 permission for directory
find ./var -type d -exec chmod 777 {} \;         // 777 permission for var folder
find ./pub/media -type d -exec chmod 777 {} \;
find ./pub/static -type d -exec chmod 777 {} \;
chmod 777 ./app/etc
chmod 644 ./app/etc/*.xml

Hope this will help you and please share an update after this activity so I can guide you next step.

A: *

*check your site in clean browser (not the one you usually use) in case browser extension adds the script to the page

*modify root index.php to "echo 123" to check if injecting script relates to Magento.

*check on Luma or Base theme to know if need to blame your custom theme

*if theme is not the cause disable all 3-rd party modules and check

php bin/magento module:status | grep -v Magento | grep -v List | grep -v None | grep -v -e '^$'| xargs php bin/magento module:disable

*go over all .htaccess files in project and look for suspicion file injecting

*if theme/3-rd party modules not the cause the issue is probably hidden somewhere in Magento core files

A: facing the same thing and I have about 70% of the same modules as you!!!
Did you ever find out which module led to the vulnerability?

A: I have encountered a same issue. It was injecting a fake payment section in the checkout page. This time the link was different though. I was able to remove the code using the header block editor in the admin. But I'm kind of sure, it will happen again. Anyways going to update the whole thing. And put a paid firewall service. If anybody finds a solution to this, it'd be very helpful. Thanks.


text:
Q: Computer hangs on Sleep. Need help reading dmp file My computer is hanging when it tries to enter sleep mode. The screen will turn off but the computer continues to run indefinitely. I have tried debugging it myself but it has exceeded my abilities. I used windows verifier to create a dmp file but I do not know what is important once opened in WinDbg. I appreciate any help in determining the problem and/or solution.
Microsoft (R) Windows Debugger Version 6.3.9600.17336 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.

Loading Dump File [C:\Windows\Minidump\080215-17253-01.dmp]
Mini Kernel Dump File: Only registers and stack trace are available

************* Symbol Path validation summary **************
Response                         Time (ms)     Location
Deferred                                       SRV*C:\SymCache*http://msdl.microsoft.com/download/symbols
Symbol search path is: SRV*C:\SymCache*http://msdl.microsoft.com/download/symbols
Executable search path is:
Windows 7 Kernel Version 7601 (Service Pack 1) MP (4 procs) Free x64
Product: WinNt, suite: TerminalServer SingleUserTS Personal
Built by: 7601.18869.amd64fre.win7sp1_gdr.150525-0603
Machine Name:
Kernel base = 0xfffff800`02e55000 PsLoadedModuleList = 0xfffff800`0309c730
Debug session time: Sun Aug  2 11:53:55.001 2015 (UTC - 4:00)
System Uptime: 0 days 0:00:29.296
Loading Kernel Symbols
...............................................................
................................................................
.........
Loading User Symbols
Loading unloaded module list
....
*******************************************************************************
*                                                                             *
*                        Bugcheck Analysis                                    *
*                                                                             *
*******************************************************************************

Use !analyze -v to get detailed debugging information.

BugCheck D3, {fffff8800102d2b9, 2, 0, fffff80002ef3c22}

Probably caused by : ntkrnlmp.exe ( nt!RtlDispatchException+122 )

Followup: MachineOwner
---------

2: kd> !analyze -v
*******************************************************************************
*                                                                             *
*                        Bugcheck Analysis                                    *
*                                                                             *
*******************************************************************************

DRIVER_PORTION_MUST_BE_NONPAGED (d3)
When possible, the guilty driver's name (Unicode string) is printed on
the bugcheck screen and saved in KiBugCheckDriver.
An attempt was made to access a pageable (or completely invalid) address at an
interrupt request level (IRQL) that is too high.  This is usually
caused by drivers marking code or data as pageable when it should be
marked nonpaged.
If kernel debugger is available get stack backtrace.
Arguments:
Arg1: fffff8800102d2b9, memory referenced
Arg2: 0000000000000002, IRQL
Arg3: 0000000000000000, value 0 = read operation, 1 = write operation
Arg4: fffff80002ef3c22, address which referenced memory

Debugging Details:
------------------

READ_ADDRESS: GetPointerFromAddress: unable to read from fffff80003106100
GetUlongFromAddress: unable to read from fffff800031061c0
 fffff8800102d2b9 Nonpaged pool

CURRENT_IRQL:  2

FAULTING_IP:
nt!RtlDispatchException+122
fffff800`02ef3c22 410fb60c24      movzx   ecx,byte ptr [r12]

CUSTOMER_CRASH_COUNT:  1

DEFAULT_BUCKET_ID:  VERIFIER_ENABLED_VISTA_MINIDUMP

BUGCHECK_STR:  0xD3

PROCESS_NAME:  WRSA.exe

ANALYSIS_VERSION: 6.3.9600.17336 (debuggers(dbg).150226-1500) amd64fre

TRAP_FRAME:  fffff88002a0bbd0 -- (.trap 0xfffff88002a0bbd0)
NOTE: The trap frame does not contain all registers.
Some register values may be zeroed or incorrect.
rax=fffff8800102a1dc rbx=0000000000000000 rcx=fffff8800102d2d0
rdx=fffff8800102d0d2 rsi=0000000000000000 rdi=0000000000000000
rip=fffff80002ef3c22 rsp=fffff88002a0bd60 rbp=fffff88002a0cc18
 r8=000000000000017d  r9=000000000000016d r10=fffff88002a0d410
r11=fffff88002a0bda8 r12=0000000000000000 r13=0000000000000000
r14=0000000000000000 r15=0000000000000000
iopl=0         nv up ei pl zr na po nc
nt!RtlDispatchException+0x122:
fffff800`02ef3c22 410fb60c24      movzx   ecx,byte ptr [r12] ds:00000000`00000000=??
Resetting default scope

LAST_CONTROL_TRANSFER:  from fffff80002ec8e69 to fffff80002ec98c0

STACK_TEXT:
fffff880`02a0ba88 fffff800`02ec8e69 : 00000000`0000000a fffff880`0102d2b9 00000000`00000002 00000000`00000000 : nt!KeBugCheckEx
fffff880`02a0ba90 fffff800`02ec7ae0 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`000001e7 : nt!KiBugCheckDispatch+0x69
fffff880`02a0bbd0 fffff800`02ef3c22 : fffff880`0102d2b9 fffff880`02a0bda8 fffff880`02a0cc18 fffff880`0100b000 : nt!KiPageFault+0x260
fffff880`02a0bd60 fffff800`02f04e81 : fffff880`02a0cc18 fffff880`02a0c470 fffff880`00000000 fffff880`0104a090 : nt!RtlDispatchException+0x122
fffff880`02a0c440 00000000`00000000 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : nt!KiDispatchException+0x135

STACK_COMMAND:  kb

FOLLOWUP_IP:
nt!RtlDispatchException+122
fffff800`02ef3c22 410fb60c24      movzx   ecx,byte ptr [r12]

SYMBOL_STACK_INDEX:  3

SYMBOL_NAME:  nt!RtlDispatchException+122

FOLLOWUP_NAME:  MachineOwner

MODULE_NAME: nt

IMAGE_NAME:  ntkrnlmp.exe

DEBUG_FLR_IMAGE_TIMESTAMP:  556356e8

IMAGE_VERSION:  6.1.7601.18869

FAILURE_BUCKET_ID:  X64_0xD3_VRF_nt!RtlDispatchException+122

BUCKET_ID:  X64_0xD3_VRF_nt!RtlDispatchException+122

ANALYSIS_SOURCE:  KM

FAILURE_ID_HASH_STRING:  km:x64_0xd3_vrf_nt!rtldispatchexception+122

FAILURE_ID_HASH:  {a7462664-d56e-ca97-7a53-f31727fb43aa}

Followup: MachineOwner
---------

UPDATE:
I have uninstalled webroot. Running verifier /standard /all no longer causes a BSOD and dmp file but the issue with the sleep function remains. Any help on next steps is appreciated.
UPDATE 2:
The command powercfg -a produces the following
C:\windows\system32>powercfg -a
The following sleep states are available on this system: Standby ( S3 ) Hibernat
e Hybrid Sleep
The following sleep states are not available on this system:
Standby (S1)
        The system firmware does not support this standby state.
Standby (S2)
        The system firmware does not support this standby state.

Update 3:
Couldn't seem to get sleep to initiate in safe mode.
Output of powercfg -energy: https://drive.google.com/file/d/0B5cnrhUem96xNjZWM3pMZ25oZDA/view?usp=sharing

A: Give deleting the hibernation file a go.
http://helpdeskgeek.com/windows-7/windows-7-delete-hibernation-file-hiberfil-sys/

*

*Run CMD as Administrator

*powercfg -h now

*Reboot

*Ensure hiberfil.sys is deleted in C:\
You may need to ensure this setting is unchecked in View > Folder View of Windows Explorer to visually see the hiberfil.sys file.

*Re-enable hibernation (in CMD running as Administrator): powercfg –h on

*Reboot and retest

A: I have experienced these sleep to resume issues typically with Network & WiFi cards on various laptops I have had over the decades.
More than likely, driver issues that could be bypassed in 2 ways:

*

*Find a driver - upgrade or downgrade - that works without sleep issues

*Switch / Turn off device e.g. Wireless connection before going to sleep and turn back on when resuming. This worked for me on many laptops from Compaq, HP, Dell, IBM & Lenovo Thinkpads.

Without going to deep into specifics of each device, device cards & buses being used and specific driver versions, this will not be easy/ direct to solve.
Specifics:
If you are using Vista drivers, as seen in the dump, then please upgrade drivers to Win 7/8 or downgrade to XP. The most horrible driver & WiFi experiences I had on my Thinkpad's were with Vista, and thankfully I could up to 7 or down to XP.

A: I have experienced the same problem myself.
The steps I suggest you are:

*

*Uninstall/Update all the drivers (Display/USB/network in particular)

*Reset power management to default

*Reinstall the operating system

Unfortunately, Step 3 was the resolution for me - however i have encountered a lot of users which step 1 solved the issue for them (It even can be a VPN or Virtualbox Network adapter in some cases)
I am sure however it is a software fault and not any hardware error/Failure.

A: Most critical part of awaking a computer are driver procedures for returning the hardware in the same state as before sleeping.
May be you one of your drivers is responsible for the crash? Try updating your drivers. You could use some driver collection program - for example Driver Pack Solution - http://drp.su/


text:
Q: Can't install ghc on ubuntu 12.04 I'm just trying to install ghc on my computer. I typed
sudo apt-get install ghc

into the terminal. I then was asked did I want to install, I said yes. Then I was asked did I want to install unverified files. I said yes. Then I got a bunch of error 404's and finally an error:
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

I tried installing it via the Software Center and I got a pop up saying:

This requires installing packages from unauthenticated sources.

I clicked OK and it just stopped installing.
Can anyone help me just simply install ghc?
After running sudo apt-get update I get this:

When I type sudo apt-get install ghc I get this:

A: Try installing the packages on this list: http://packages.ubuntu.com/precise/haskell-platform
sudo apt-get install ghc alex cabal-install happy libghc-cgi-dev libghc-fgl-dev libghc-glut-dev libghc-haskell-src-dev libghc-html-dev libghc-http-dev libghc-hunit-dev libghc-mtl-dev libghc-network-dev libghc-opengl-dev libghc-parallel-dev libghc-parsec3-dev  libghc-quickcheck2-dev libghc-regex-base-dev libghc-regex-compat-dev  libghc-regex-posix-dev libghc-stm-dev libghc-syb-dev  libghc-text-dev  libghc-transformers-dev  libghc-xhtml-dev libghc-zlib-dev

Hope this helps!


text:
Q: Form inputs and button do not perfectly align I have a sign up form which i want to center in the middle. However, my input fields and button do not perfectly align. They do have the same size. The button is 5px wider however i also tried this with exact the same widths and the problem still occurs. Could somebody please explain to me why this happens? I also wonder why the submit button is always smaller in width even when it does have the same value? The website can be found at www.http://public-journalism.com/pages/sign_up.php
This is my html code:

    <form name="signup" method="post" action='/scripts/loginscript.php'>
        Sign up

        <input placeholder="Username" type='text' name='username' id='username'  maxlength="50" />

        <input placeholder="Email" type='text' name='email' id='email'  maxlength="50" />

        <input placeholder="Re-enter email" type='text' name='email' id='email'  maxlength="50" />

        <input placeholder="Password" type='password' name='password' id='password' maxlength="50" />

        <input placeholder="Re-enter password" type='password' name='password' id='password' maxlength="50" />

        <input type='submit' id="public_journalism_button" name='signup' value='Sign me up!'/>

By signing up, you agree to our terms of use, privacy policy, and cookie policy.

    </form>

This is my css code:
#pjsignup_container {
    padding: 10px 0px 10px 0px;
}

#pjsignup_container input {
    width: 220px;
    height: 20px;
    margin-top: 10px;
    padding-left: 5px;
}

#pjsignup_container input[type=submit] {
    width: 225px;
    height: 30px;
    color: white;
    background-color: #0072C6;
    border: 0px;
    border-radius: 5px;
    font-weight: bold;
    cursor: pointer;
}

A:

        <form name="signup" method="post" action='/scripts/loginscript.php'>
            Sign up

            <input placeholder="Username" type='text' name='username' id='username'  maxlength="50" />

            <input placeholder="Email" type='text' name='email' id='email'  maxlength="50" />

            <input placeholder="Re-enter email" type='text' name='email' id='email'  maxlength="50" />

            <input placeholder="Password" type='password' name='password' id='password' maxlength="50" />

            <input placeholder="Re-enter password" type='password' name='password' id='password' maxlength="50" />

            <input type='submit' id="public_journalism_button" name='signup' value='Sign me up!'/>

By signing up, you agree to our terms of use, privacy policy, and cookie policy.

        </form>

here i use only center tag to align it in middle

A: the br seem to be causing the misalignment. Removing them in the inspector aligned the inputs properly. Give your inputs margin: 10px auto 0; instead of margin-top: 10px;
 Also, your input seems to be box-sizing:border-box; by it's behavior, and the inputs seem to be content-box. Size your submit to width 229px to match the other inputs, or otherwise.

A: You just need to add width and margin at wrapper element (#pjsignup_container ).
code example
#pjsignup_container {
    width: 220px;
    margin: 0 auto;
    padding: 10px 0px 10px 0px;
}

Because
margin: 0 auto;
/* is equal to(=) */
margin: 0 calc(50% - width/2);

Example
#eg {
 width: 500px;
 margin: 0 auto; /* or */ margin: 0 calc(50% - 500px/2);
}

Nice a have day. Good Luck


text:
Q: Add two columns for sum of money by year Below is my query that groups my customers together, and sums their total money spent over the last two years. Works like a charm. However I need a little more which goes over my sql knowledge.
Is there any way to select three more columns and populate it with the money they spent for each of those years (2010, 2011, 2012)?
SELECT  SUM(price) AS money_spent_total, co.customer_id, cu.first_name, cu.last_name, cu.email_primary, cu.phone_primary, co.date_paid
FROM customer_order   AS co
INNER  JOIN customer AS cu ON (cu.customer_id = co.customer_id)
WHERE  cu.customer_id != 32518 AND co.date_paid > "2010-1-1" AND co.date_paid < "2013-1-1"
GROUP BY co.customer_id

A: You need to GROUP BY YEAR(date_paid) in addition to customer_id. You should also not be selecting any columns which are not in your GROUP BY. In addition, you can use the BETWEEN operator instead of > and < for your date range.
SELECT Year(co.date_paid),
       co.customer_id,
       Sum(price) AS money_spent_total
FROM   customer_order AS co
       INNER JOIN customer AS cu
               ON ( cu.customer_id = co.customer_id )
WHERE  cu.customer_id != 32518
       AND co.date_paid BETWEEN '2010-01-01' AND '2013-01-01'
GROUP  BY Year(co.date_paid),
          co.customer_id

To get the columns in your original SELECT, you would do something like (not tested):
SELECT a.date_year_paid,
       a.customer_id,
       a.money_spent_total,
       cu.first_name,
       cu.last_name,
       cu.email_primary,
       cu.phone_primary
FROM   (SELECT Year(co.date_paid) AS date_year_paid,
               co.customer_id,
               Sum(price)         AS money_spent_total
        FROM   customer_order AS co
               INNER JOIN customer AS cu
                       ON ( cu.customer_id = co.customer_id )
        WHERE  cu.customer_id != 32518
               AND co.date_paid BETWEEN '2010-01-01' AND '2013-01-01'
        GROUP  BY Year(co.date_paid),
                  co.customer_id) a
       LEFT JOIN customer cu
              ON cu.customer_id = a.customer_id

If you were doing the INNER JOIN just for customer info, then it can be dropped.
  SELECT a.customer_id,
       a.date_year_paid,
       a.money_spent_total,
       cu.first_name,
       cu.last_name,
       cu.email_primary,
       cu.phone_primary
  FROM (SELECT customer_id, YEAR(date_paid) AS date_year_paid, SUM(price) AS money_spent_total
        FROM customer_order
        GROUP BY customer_id, YEAR(date_paid)) a
       LEFT JOIN customer cu
              ON cu.customer_id = a.customer_id

Lastly, if you want to group the years into columns:
SELECT a.customer_id,
       a.y2010 AS '2010_money_paid',
       a.y2011 AS '2011_money_paid',
       a.y2012 AS '2012_money_paid',
       cu.first_name,
       cu.last_name,
       cu.email_primary,
       cu.phone_primary
FROM   (SELECT customer_id,
               Sum(CASE
                     WHEN Year(date_paid) = 2010 THEN price
                     ELSE 0
                   end) AS 'y2010',
               Sum(CASE
                     WHEN Year(date_paid) = 2011 THEN price
                     ELSE 0
                   end) AS 'y2011',
               Sum(CASE
                     WHEN Year(date_paid) = 2012 THEN price
                     ELSE 0
                   end) AS 'y2012'
        FROM   customer_order
        GROUP  BY customer_id) a
       LEFT JOIN customer cu
              ON cu.customer_id = a.customer_id

Result
| CUSTOMER_ID | 2010_MONEY_PAID | 2011_MONEY_PAID | 2012_MONEY_PAID | FIRST_NAME | LAST_NAME | EMAIL_PRIMARY | PHONE_PRIMARY |
------------------------------------------------------------------------------------------------------------------------------
|           1 |            9000 |            3000 |            2000 |        Bob |     Smith | bob@smith.com |    1112223333 |
|           2 |            4000 |            5000 |            1000 |        Tom |     Jones | tom@jones.com |    2223334444 |
See the demo


text:
Q: how Querying Dijango date save on JSONField i save multi date in json filed.
example:
row 1 : [ "2022-10-26", "2022-11-10" , "2022-11-16", , "2022-11-17"]
row 2 : [ "2022-09-26", "2022-09-10" , "2022-09-16"]
row 3 : [ "2022-12-16" ]

How i can filter date bigger than 2022-10-01?
**
in the example i must get row 1 & 3


text:
Q: KDB: how to compare strings? I have a column of type C. How do I compare the value to the previous value in the same column? I did col1 like prev col1 but it returns a Correction hint: length error. I also created another column newCol: prev col1 but still cannot perform the comparison. I also tried with = and no luck. How can I do this?
a sample data:
col1
Paris
London
London
New York
Singapore
Ha Noi

A: Could you use the prior keyword?
q)t
col1
-----------
"Paris"
"London"
"London"
"Ney York"
"Singapore"
"Ha Noi"
q)select (~) prior col1 from t
col1
----
0
0
1
0
0
0

When comparing strings, if they are the same length it will check that each character in each slot of the array is the same, and return a list of booleans to tell you where the strings are the same. If the strings are two different lengths, you will get a length error. If you want to test if two strings are the exact same thing, you can use ~, which will work regardless of the length of the string and give you a single boolean telling you if they are the same.

A: Use each prior:https://code.kx.com/q/ref/maps/#each-prior
With match: https://code.kx.com/q/basics/comparison/#match
    q)tab:([]col1:("Paris";"London";"London";"New York"))
    q)select col1,compare:(~':)col1 from tab
    col1       compare
    ------------------
    "Paris"    0
    "London"   0
    "London"   1
    "New York" 0

A: You should use like' instead of like, because you are comparing not to single value, but to list.
update comparison: col1 like' prev col1 from
  ([]col1:("Paris";"London";"London";"New York";"Singapore";"Ha Noi"))

A: Although this is essentially the same as Matthews and jomahony's answers, the differ keyword can arguably make it easier to read/understand:
q)select not differ col1 from ([]col1:("Paris";"London";"London";"New York"))
col1
----
0
0
1
0


text:
Q: como descargar un archivo usando webbrowser? alguien podría orientarme con esto, quiero descargar un archivo de una pagina web sin mostrar  usando el control webbrowser, sin que se muestre cuadro de dialogo de descarga, que se descargue automáticamente. El elemento que quiero descargar tiene el siguiente código:

cabe mencionar que el url no es el mismo, se autogenera uno diferente en cada sesión dentro de la pagina

A: Puedes agregar el atributo download en la etiqueta , seteando el nombre y extensión con una lógica del lado servidor o cliente:
EEE

En este enlace puedes validar cuáles navegadores soportan este atributo.