text:
Q: C++ Suppress Automatic Initialization and Destruction How does one suppress the automatic initialization and destruction of a type?  While it is wonderful that T buffer[100] automatically initializes all the elements of buffer, and destroys them when they fall out of scope, this is not the behavior I want.
#include <iostream>

static int created   = 0,
           destroyed = 0;

struct S
{
    S()
    {
        ++created;
    }
    ~S()
    {
        ++destroyed;
    }
};

template <typename T, size_t KCount>
class fixed_vector
{
private:
    T m_buffer[KCount];
public:
    fixed_vector()
    {
        // some way to suppress the automatic initialization of m_buffer
    }

    ~fixed_vector()
    {
        // some way to suppress the automatic destruction of m_buffer
    }
};

int main()
{
    {
        fixed_vector<S, 100> arr;
    }

    std::cout << "Created:\t"   << created   << std::endl;
    std::cout << "Destroyed:\t" << destroyed << std::endl;
    return 0;
}

The output of this program is:
Created:    100
Destroyed:  100

I would like it to be:
Created:    0
Destroyed:  0

My only idea is to make m_buffer some trivially constructed and destructed type like char and then rely on operator[] to wrap the pointer math for me, although this seems like a horribly hacked solution.  Another solution would be to use malloc and free, but that gives a level of indirection that I do not want.

The reason why I want this is because I am making a container and I do not want to pay for the initialization overhead of things that I will not use.  For example, if my main function was:
int main()
{
    {
        std::vector<S> vec;
        vec.reserve(50);
    }

    std::cout << "Created:\t"   << created   << std::endl;
    std::cout << "Destroyed:\t" << destroyed << std::endl;
    return 0;
}

The output would be correct:
Created:    0
Destroyed:  0

A: You may want to look into boost::optional
template <typename> struct tovoid { typedef void type; };

template <typename T, size_t KCount, typename = void>
struct ArrayStorage {
  typedef T type;
  static T &get(T &t) { return t; }
};

template <typename T, size_t KCount>
struct ArrayStorage<T, KCount, typename tovoid<int T::*>::type> {
  typedef boost::optional<T> type;
  static T &get(boost::optional<T> &t) {
    if(!t) t = boost::in_place();
    return *t;
  }
};

template <typename T, size_t KCount>
class Array
{
public:
    T &operator[](std::ptrdiff_t i) {
      return ArrayStorage<T, KCount>::get(m_buffer_[i]);
    }

    T const &operator[](std::ptrdiff_t i) const {
      return ArrayStorage<T, KCount>::get(m_buffer_[i]);
    }

    mutable typename ArrayStorage<T, KCount>::type m_buffer_[KCount];
};

A specialization is done for class type that wraps them into an optional, thus calling the constructor/destructor lazily. For non-class types, we don't need that wrapping. Not wrapping them means we can treat &a[0] as a contiguous memory area and pass that address to C functions that want an array. boost::in_place will create the class types in-place, without using a temporary T or its copy constructor.
Not using inheritance or private members allow the class to stay an aggregate, allowing a convenient form of initialization
// only two strings are constructed
Array<std::string, 10> array = { a, b };

A: You can create the array as array of chars and then use placement new to create the elements when needed.
template <typename T, size_t KCount>
class Array
{
private:
    char m_buffer[KCount*sizeof(T)]; // TODO make sure it's aligned correctly

    T operator[](int i) {
        return reinterpret_cast<T&>(m_buffer[i*sizeof(T)]);
    }

After re-reading your question it seems that you want a sparse array, this sometimes goes by the name of map ;o) (of course the performance characteristics are different...)
template <typename T, size_t KCount>
class SparseArray {
    std::map<size_t, T> m_map;
public:
    T& operator[](size_t i) {
        if (i > KCount)
            throw "out of bounds";
        return m_map[i];
    }

A: This code:
#include <iostream>
#include <vector>
using namespace std;

int created = 0, destroyed = 0;

struct S
{
    S()
    {
        ++created;
    }
    S(const S & s ) {
        ++created;
    }
    ~S()
    {
        ++destroyed;
    }
};

int main()
{
    {
        std::vector<S> vec;
        vec.reserve(50);
    }

    std::cout << "Created:\t"   << created   << std::endl;
    std::cout << "Destroyed:\t" << destroyed << std::endl;
    return 0;
}

has exactly the output you want - I'm not sure what your question is.

A: If you want to be like vector, you should do something like this:
template <typename T>
class my_vector
{
    T* ptr; // this is your "array"
    // ...
    public:

    void reserve(size_t n)
    {
        // allocate memory without initializing, you could as well use malloc() here
        ptr = ::operator new (n*sizeof(T));
    }

    ~my_vector()
    {
        ::operator delete(ptr); // and this is how you free your memory
    }

    void set_element(size_t at, const T& element = T())
    {
        // initializes single element
        new (&ptr[at]) T(element); // placement new, copies the passed element at the specified position in the array
    }

    void destroy_element(size_t at)
    {
        ptr[at].~T(); // explicitly call destructor
    }
};

This code is obviously for demonstration only, I have omitted my_vector's copy-constructor  and any tracking on what's created and what not (calling destructor on a location you haven't called constructor for is probably undefined behavior). Also, STL's vector allocations and deallocations are abstracted away through the use of allocators (the second template argument of vector).
Hope that helps

A: You can have a look at the way it's done with the STL containers, but I doubt you can spare yourself mallocs and frees


text:
Q: Selenium Faker class - Error Can not make static reference to non static field Cucumber I am using Faker class to create random values in Selenium Webdriver automation. Below is the class for your reference.
public class NewUserFormAction {

    Faker faker = new Faker();
    public  String name = faker.name().firstName();
    public  String Surname = faker.name().lastName();

    public static void Execute(WebDriver driver,List<HashMap<String,String>> map) throws Exception{

        WebDriverWait wait = new WebDriverWait(driver,10);
        wait.until(ExpectedConditions.elementToBeClickable(NewUserFormPage.gender));
        NewUserFormPage.gender.click();
        NewUserFormPage.customer_firstname.sendKeys(name);
        NewUserFormPage.customer_lastname.sendKeys(Surname);

    }
}

when I am executing this code I am getting exception at compilation at below steps with error can not make static method reference to non static data member.
NewUserFormPage.customer_firstname.sendKeys(name);
NewUserFormPage.customer_lastname.sendKeys(Surname);

Here I understand the faker instance is create on public class which is non static and it is being called in Execute method which is static. Can you please help me how to solve this issue ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: is we need to pay and return to site successfully to get paypal order confirmation email we are not getting order confirmation email if customer placed an order through paypal.but we get invoice and shipment mails.
we set Sale : Payment Action in paypal configuration.
so once we create the order, along with the order email [its not going to customer] i want to send invoice mail also to customer. i think this extension will send invoice only once order status become complete.
if we use SMTP extension will it work for us ?
is there any thing else we need to do ?
Edit
also I want to know is Email will send only if we pay money and succesfully return to site ? If we just click on "place order" & redirect to paypal page, will it not send email ?
2016-06-13T20:15:10+00:00 ERR (3):
exception 'Mage_Paypal_UnavailableException' with message 'Empty response.' in /home/site/public_html/app/code/core/Mage/Paypal/Model/Ipn.php:166
Stack trace:
#0 /home/site/public_html/app/code/core/Mage/Paypal/Model/Ipn.php(116): Mage_Paypal_Model_Ipn->_postBack(Object(Varien_Http_Adapter_Curl))
#1 /home/site/public_html/app/code/core/Mage/Paypal/controllers/IpnController.php(43): Mage_Paypal_Model_Ipn->processIpnRequest(Array, Object(Varien_Http_Adapter_Curl))
#2 /home/site/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Paypal_IpnController->indexAction()
#3 /home/site/public_html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch('index')
#4 /home/site/public_html/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#5 /home/site/public_html/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#6 /home/site/public_html/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#7 /home/site/public_html/index.php(87): Mage::run('', 'store')
#8 {main}

A: Concepts

we are not getting order confirmation email if customer placed an order through paypal.but we get invoice and shipment mails.

This clarifies one thing: that your email sending mechanism (likely the Magento cron) is working correctly in general.

if we use SMTP extension will it work for us ?

Whether you implement this extension or not, it will not affect whether your PayPal order emails work. This module is designed to sit in the background and take the regular email send jobs from the core Magento mail module and do its own thing with them. You will not notice a difference in regular Magento use from installing it, other than an email log table in Magento admin which contains a history of your sent emails.
If you have installed this extension, you could use that email log in Magento admin to check what has been sent. You can access it via System -> Tools -> SMTP Pro - Email Log.

also I want to know is Email will send only if we pay money and succesfully return to site ? If we just click on "place order" & redirect to paypal page, will it not send email ?

Emails are sent when certain status changes occur on various models in Magento. Order emails are sent when an order reaches the processing status, which means it has been invoiced and paid (payment method has been charged [capture() method]). Invoice emails are sent when the order's invoice is created (normally/often when the order is created as well). Shipment emails are created when a shipment is created for an order, etc...
Yes - the email will send only if you've completed the PayPal transaction and successfully returned to your Magento site (and Magento has successfully registered that payment against the order and saved it).
If you just click on "place order" & redirect to PayPal page, it will not trigger any emails to be sent. Your order doesn't exist at this point, it is simply a quote waiting to be converted to an order when the customer returns from PayPal.
The code
If you take a look at Mage_Paypal_Model_Express_Checkout::place() as an example, you will see the following conditions apply to when Magento will send (queue) a new order email. This method is triggered when customers return from PayPal (the returnAction in Mage_Paypal_Controller_Express_Abstract sends them here via ->placeOrderAction() then $this->_checkout->place()):
# File: app/code/core/Mage/Paypal/Model/Express/Checkout.php
switch ($order->getState()) {
    // even after placement paypal can disallow to authorize/capture, but will wait until bank transfers money
    case Mage_Sales_Model_Order::STATE_PENDING_PAYMENT:
        // TODO
        break;
    // regular placement, when everything is ok
    case Mage_Sales_Model_Order::STATE_PROCESSING:
    case Mage_Sales_Model_Order::STATE_COMPLETE:
    case Mage_Sales_Model_Order::STATE_PAYMENT_REVIEW:
        $order->queueNewOrderEmail();
        break;
}

Essentially the email will be sent (queued) if the new order's state is either "processing", "complete" or "payment_review" - have you checked the affected PayPal orders to see what their status is? You say you can ship them, so I assume that they're "processing".
The one exception as you can see above is when the state of the new order is "pending payment". The comment from the Magento developers explains it, but it can happen in a delayed payment situation. I would suggest that this is not very common.
Of course, that switch statement is specific and doesn't contain a default case (side note: this breaks the Zend style guidelines, but so does a lot of the core Magento code!). This means that if the order state is not any of the ones mentioned, the order will also not be sent (queued).

Where to from here?
I'd suggest you do the following:

*

*Get a PayPal sandbox account set up in your development environment so you can test it yourself!

*Inspect the status of new PayPal orders as they come in. Look at the status of the orders. Look at the history of the order to see if anything seems out of the ordinary. Try changing the email on one of the orders to yours and triggering the order email to be re-sent manually from the order view screen in Magento admin (this will eliminate the email template itself as an issue)

*Enable PayPal logging, and inspect the API logs as the requests are made (best done in a development environment, assuming you can reproduce it)

Notes
The comments/suggestions I've made above assume that you don't have any third-party or custom made modules getting in the way of any of the orders or payments processes in Magento. If you do, you should mention them!
Good luck, hope this helps!

A: Form Magento1.9 Order mail send via cron job .
But You can overcome using this simple free Extension, install this extension they will give you option make e-mail in queue or not
https://www.magentocommerce.com/magento-connect/smtp-pro-email-free-custom-smtp-email.html
For Paypal Mail, complete your transaction after that you will get the mail

A: You might need to disable SSL verification,
under the
System > Configuration > Payment methods > Paypal > Advanced settings > Enable SSL verification

A: I hope your cron working properly as magento sends  confirmation mails on cron job. see this http://www.aschroder.com/2015/01/sending-emails-by-queue-in-magento-1-9-1/ and check if your emails being stored in core_email_queue and core_email_queue_recipients.

A: The real problem was some unaffected files. as some files of sites was attacked by hackers, our hosting team blocked some ports [80 or some other ports ] , after we deletd those those files, hosting team unblocked those ports , than emails are going like anything.....

A: You should check your paypal configuration on your paypal account https://developer.paypal.com/webapps/developer/docs/classic/products/instant-payment-notification/
https://lastdropofink.co.uk/tools/magento/magento-paypal-ipn/

A: Here is the Latest Solution
Please try and le me know- check my blog
http://www.anupchaudhary.com/2016/06/solved-paypal-automated-order.html
OR
You need to add some code in
app/design/frontend/base/default/template/checkout/success.phtml
    <?php
    $order = Mage::getModel('sales/order');
    $customer = Mage::getSingleton('customer/session')->getCustomer();
    $incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
    $order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
    $countryCode = $order->getShippingAddress()->getCountry();
    if($countryCode!='IN')
    {
               if($order['status']=='payment_complete')
               {
                                     try
                                    {
                                        $order->sendNewOrderEmail();
                                    }
                                    catch (Exception $ex)
                                    {
                                        echo "Email Not Sent...";
                                    }
                            $customer = Mage::getSingleton('customer/session')->getCustomer();
                            $email = $customer->getEmail();//End Email Sending
               }
   }?>

A: I had the same problem and it was caused by magento core bug.
In my exception.log file I had the following error:
main.CRITICAL: Notice: Array to string conversion in /home/mywebsite/public_html/var/view_preprocessed/pub/static/vendor/magento/module-payment/view/frontend/templates/info/default.phtml on line 1

If you want to fix it, create your own version of file vendor/magento/module-payment/view/frontend/templates/info/default.pthml in your theme and change line:
<?= $block->escapeHtml($label) ?>

to:

    <?php
    $x = $block->getValueAsArray($value, true);
    if(is_array($x)){
        //print_r($x);
        foreach($x as $y){
            echo $y;
        }
    }else{
        echo $x;
    }
    ?>

It's a very basic fix but it worked on my case.


text:
Q: well defined $F(u)=\int_I \psi udx$ and it's Gateaux derivative is $DF(u)=\psi(u)$ Let $1\le p <\infty$, $\psi\in C^1(\mathbb{R})$ such that $\psi (0)=0$ and $|\psi '(y)|\le C|y|^{p-1}$ for all $y\in\mathbb{R}$ and for a constant $C>0$.
Prove that $F:L^p(I)\to \mathbb{R}$ defined by $F(u)=\int_I \psi udx$ is welldefined and it's Gateaux derivative is $DF(u)=\psi(u)$.
Well defined: $|\int_I \psi udx|\le \int_I| \psi u|dx$. And now, how to continue? $\psi$ don't has to be bounded or in $L^p(I)$. I stuck with estimate $\psi$.
For the second part let $u,v\in L^p(I)$, then $\frac{F(u +hv)-F(v)}{h}=\int_I \frac{\psi (u+hv)}{h}dx$. I can't derive $u$.. How to continue?

A: As $\phi \in C^1$, you have that $\phi(y)-\phi(0) = (y-0) \phi'(c)$ with $c \in [0,y]$
This imply that
$$| \phi(y) | = |y| |\phi'(c)| \leq |y|C |c|^{p-1} \leq C|y|^p$$
The majoration follow directly from this.
For the Gateau derivative,
$$ \frac{\phi(u+hv) - \phi(u)}{h} = \phi'(u).v + \epsilon(h)$$
So
$$\frac{F(u+hv)-F(u)}{h} = \int_I \phi'(u(x))v(x) + \epsilon(h)(x) dx$$
So this will give us that the Gâteau derivative is the functionnal
$$Df(u)(v) = \langle \phi'(u), v \rangle = \int_I \phi'(u(x)) v(x) dx $$


text:
Q: Instanceof - using classes to simulate system access I am trying to simulate a system access portal using classes and methods. I want to be able to ask the user for their username using input(), check if that input is an object of class User and if so, check if the password is correct for the username. When I use instance of it is returning false. How can I modify this to work?
class User():

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def change_pw(self, new_password):
        self.password = new_password

jshannon = User("jshannon","AbC!23")
print(jshannon.username)
print(jshannon.password)

jshannon.change_pw("(i*u&y1")
print(jshannon.password)

input_user = input("What is your username? ")

print(isinstance(input_user, User))

A: User inputs are strings. Always. Period. So you can not "check if that input is an object of class User" - it will never be.
The solution here is to maintain a collection of User instances, and use the input string to search for a matching user.
class UsersCollection(object):
    def __init__(self):
        # we store users in a dict, with user.usernale as key
        self._users = {}

    def add(self, user):
        if user.username in self._users:
            raise ValueError("username '{}' already in used".format(user.username))
        self._users[user.username] = user

    def get(self, username):
        return self._users.get(username)

users = UsersCollection()
users.add(User("jshannon","AbC!23"))

input_user = input("What is your username? ").strip()

userfound = users.get(input_user)
if userfound:
   # you can do something with your user
else:
   print("sorry, we don't know you")

Note that this is only suitable as a toy project of course.

A: If you are using Python 3.x (which I'm going to assume), input returns a string so isinstance(input_user, User) will always be False.
You will need to keep track of all User objects created and search for the object with the inputted name.
There are several different ways to do that. I'm going to assume that usernames are unique so I will use them in a shared set:
class User:
    users = set()

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.users.add(username)

    def change_pw(self, new_password):
        self.password = new_password

jshannon = User("jshannon", "AbC!23")
print(jshannon.username)
print(jshannon.password)

jshannon.change_pw("(i*u&y1")
print(jshannon.password)

input_user = input("What is your username? ")

print(input_user in User.users)
# will output True if input_user is jshannon, otherwise False

Note that this is just an example, and it is not bullet-proof nor the best design (one may argue if the users set even belongs to the User class Hint: probably not). If an object's username changes after the initialization the set will not be updated and you may get wrong results. This particular problem can be solved by changing self.username to a property but I suppose that is out of scope of this Q&A.

A: I am not sure if this is what you want to do but you cant try this
add a list to your class list_of_usernames = []
and then in __init__() append username to the list_of_usernames and at the end
print(input_user in User.list_of_usernames)

so your code will look like this
class User():
list_of_usernames = []
def __init__(self, username, password):
    self.username = username
    self.password = password
    self.list_of_usernames.append(username)
def change_pw(self, new_password):
    self.password = new_password

jshannon = User("jshannon","AbC!23")
print(jshannon.username)
print(jshannon.password)

jshannon.change_pw("(i*u&y1")
print(jshannon.password)

input_user = input("What is your username? ")

print(input_user in User.list_of_usernames)


text:
Q: Building a tflite model for multi class classification I have read multiple codelabs in which Google classifies images belonging to one class. What if I need to use 2 or more classes. For example, if I want to classify whether an image contains a fruit or a vegetable, and then classify which type of fruit or vegetable it is.

A: You can easily train a Convolutional Neural Network ( CNN ) using TensorFlow ( specifically using Keras ). There are tons of examples on the internet. See here and here.
Next, we convert the Keras saved model ( .h5 file ) to a .tflite file using tf.lite.TFLiteConverter,
import tensorflow as tf

converter = tf.lite.TFLiteConverter.from_keras_model_file("keras_model.h5")
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

See here.
Now, in Android, we take a Bitmap image and convert it to a float[][][][],
private float[][][][] convertImageToFloatArray ( Bitmap image ) {
   float[][][][] imageArray = new   float[1][modelInputDim][modelInputDim][1] ;
   for ( int x = 0 ; x < modelInputDim ; x ++ ) {
       for ( int y = 0 ; y < modelInputDim ; y ++ ) {
           float R = ( float )Color.red( image.getPixel( x , y ) );
           float G = ( float )Color.green( image.getPixel( x , y ) );
           float B = ( float )Color.blue( image.getPixel( x , y ) );
           double grayscalePixel = (( 0.3 * R ) + ( 0.59 * G ) + ( 0.11 * B )) / 255;
           imageArray[0][x][y][0] = (float)grayscalePixel ;
       }
   }
   return imageArray ;
}

Where modelInputDim is the model's input size for the image. The above snippet converts the RGB image to a grayscale image.
Now, we perform the final inference,
private int modelInputDim = 28 ;
private int outputDim = 3 ;

private float[] performInference(Bitmap frame , RectF cropImageRectF ) {
   Bitmap croppedBitmap = getCroppedBitmap( frame , cropImageRectF ) ;
   Bitmap croppedFrame = resizeBitmap( croppedBitmap );
   float[][][][] imageArray = convertImageToFloatArray( croppedFrame ) ;
   float[][] outputArray = new float[1][outputDim] ;
   interpreter.run( imageArray , outputArray ) ;
   return outputArray[0] ;
}

I have prepared a collection of Android apps which utilize TFLite models in Android. See here.


text:
Q: how to create a google sign in popup on the Python Flask website I would like to create a google sign-in popup similar to https://www.reddit.com/. on the right side of this page, you can see "Sign in to Reddit with Google", I want this similar on my website.

A: *

*See documentation for Sign-in with Google

*If you want to give users the ability to sign-in with other providers e.g. Apple, Twitter, etc, then you should checkout Firebase from Google. The documentation for their sign-in can be found here


text:
Q: How to render a long code listing in multiple pages with the package minted? I'm using the package minted for formatting code in my paper. The package minted provides a "listing" environment, which treats the code inside it as a float. It works very well under most circumstances. But, how to embed a long listing of code which can span two or more pages using minted? Its listing environment does not work well for this situation.
I'd also like to use \caption and \label below the minted code listing. And I'd like to index the listings in my ToC.
Any help will be highly appreciated!
-Nicole

A: As example for the first part, a breakable tcb listing box using minted (tcb code somewhat adapted from another answer on this site about quoting; javascript code is from this page):

There are three or four ways of dealing with the perennial problem of wrapping long lines: here, some (manual) line-wrapping and indentation removal has been done to the first code block, as illustration.
MWE
\documentclass[
    12pt,
    openright,
    twoside,
    a4paper,
    english,
    draft
]{memoir}
\usepackage{microtype}
\usepackage{minted}
%\usepackage{geometry}
\usepackage{tcolorbox}

\usepackage{tikz}
\usepackage{tkz-euclide}
\tcbuselibrary{minted,skins,breakable,xparse}
\usetikzlibrary{positioning}

\definecolor{corAzulTema}{RGB}{0,66,137}
\definecolor{corFundoCaixas}{RGB}{245,245,245}

\tcbset{
    listing engine=minted,
    minted options={fontsize=\small,linenos,numbersep=3mm,breaklines,escapeinside=@@},
    colback=corFundoCaixas,
    colframe=corAzulTema!40,
    fonttitle=\bfseries,
    listing only,
    left=7mm,
    enhanced,
    breakable,
    drop fuzzy shadow,
    before skip=\baselineskip,
    grow to left by=13mm,grow to right by=15mm,
    overlay={\begin{tcbclipinterior}\fill[corAzulTema!40](frame.south west)rectangle([xshift=7mm]frame.north west);\end{tcbclipinterior}}
}

\newtcbinputlisting{\javaScriptCode}[3][]{%
    listing file={#3},
    title=\texttt{#2},
    colframe=corAzulTema,
    minted language=javascript
}

\DeclareTotalTCBox{\inlineJavaScriptCode}{ s v }{
    reset,
    listing only,
    on line,
    enhanced,
    nobeforeafter,
    tcbox raise base,
    boxrule=0.7pt,
    top=1mm,
    bottom=0mm,
    right=1mm,
    left=1mm,
    boxsep=0.5pt,
    before upper={\vphantom{dlg}},
    colback=corFundoCaixas,
    colframe=corAzulTema,
    drop fuzzy shadow,
        minted options={escapeinside=@@},
%       text=\ttfamily,
    arc=3pt}
{\mintinline{javascript}{#2}}%

\begin{document}

\begin{enumerate}
    \item apostrophe/single quotes: \inlineJavaScriptCode{'string'}
    \item double quotes:  \inlineJavaScriptCode{"string"}
    \item grave: \inlineJavaScriptCode{`string`}
    \item line \inlineJavaScriptCode{let s1 = 'string';    // apostrophe/single quotes}
\end{enumerate}

\javaScriptCode{title}{strings2.js}

\end{document}

js file:
 StackExchange.ready(function () {

      StackExchange.using("postValidation", function () {
        StackExchange.postValidation.initOnBlurAndSubmit( $('#post-form'), 2, 'answer');
                });

      StackExchange.question.init({canOpenBounty:true,votesCast:[], canViewVoteCounts:true, totalCommentCount:2, shownCommentCount:2, enableTables:true, questionId:642048});

       styleCode();

          StackExchange.realtime.subscribeToQuestion('85', '642048');
          StackExchange.using("gps", function () { StackExchange.gps.trackOutboundClicks('#content', '.js-post-body'); });

            });

 StackExchange.ready(function () {

                StackExchange.using("postValidation", function () {
                    StackExchange.postValidation.initOnBlurAndSubmit($('#post-form'), 2, 'answer');
                });

                StackExchange.question.init({canOpenBounty:true,votesCast:[],canViewVoteCounts:true,totalCommentCount:2,shownCommentCount:2,enableTables:true,questionId:642048});

                styleCode();

                    StackExchange.realtime.subscribeToQuestion('85', '642048');
                    StackExchange.using("gps", function () { StackExchange.gps.trackOutboundClicks('#content', '.js-post-body'); });

            });

 StackExchange.ready(function () {

                StackExchange.using("postValidation", function () {
                    StackExchange.postValidation.initOnBlurAndSubmit($('#post-form'), 2, 'answer');
                });

                StackExchange.question.init({canOpenBounty:true,votesCast:[],canViewVoteCounts:true,totalCommentCount:2,shownCommentCount:2,enableTables:true,questionId:642048});

                styleCode();

                    StackExchange.realtime.subscribeToQuestion('85', '642048');
                    StackExchange.using("gps", function () { StackExchange.gps.trackOutboundClicks('#content', '.js-post-body'); });

            });

 StackExchange.ready(function () {

                StackExchange.using("postValidation", function () {
                    StackExchange.postValidation.initOnBlurAndSubmit($('#post-form'), 2, 'answer');
                });

                StackExchange.question.init({canOpenBounty:true,votesCast:[],canViewVoteCounts:true,totalCommentCount:2,shownCommentCount:2,enableTables:true,questionId:642048});

                styleCode();

                    StackExchange.realtime.subscribeToQuestion('85', '642048');
                    StackExchange.using("gps", function () { StackExchange.gps.trackOutboundClicks('#content', '.js-post-body'); });

            });

 StackExchange.ready(function () {

                StackExchange.using("postValidation", function () {
                    StackExchange.postValidation.initOnBlurAndSubmit($('#post-form'), 2, 'answer');
                });

                StackExchange.question.init({canOpenBounty:true,votesCast:[],canViewVoteCounts:true,totalCommentCount:2,shownCommentCount:2,enableTables:true,questionId:642048});

                styleCode();

                    StackExchange.realtime.subscribeToQuestion('85', '642048');
                    StackExchange.using("gps", function () { StackExchange.gps.trackOutboundClicks('#content', '.js-post-body'); });

            });

A: Thanks to comment from @TeXnician , I have solved this problem with the package caption.
In preamble:
\usepackage[chapter, newfloat]{minted} % Code listings, with syntax highlighting
\usepackage[font=small]{caption}

\newenvironment{code}{\captionsetup{type=listing}}{}
\SetupFloatingEnvironment{listing}{name=Code}

%   Code list in content index
\renewcommand{\listoflistings}{
  \cleardoublepage
  \addcontentsline{toc}{chapter}{List of Code}
  \listof{listing}{List of Code}
}

\setminted{
    frame=lines,
    framesep=2mm,
    bgcolor=Snow1,
    fontsize=\small,
    linenos,
    breaklines
}

In chapter or section:
\begin{code}
    \begin{minted}{yaml}
# long long YAML code
# long long YAML code
...

    \end{minted}
    \captionof{listing}{A very long YAML snippet}
    \label{lst:longYamlSnippet}
\end{code}


text:
Q: Interpretation of Pearson r results - multiple choice test results I have previously asked this question but should have provided more detail on the question.
I have been presented with multiple choice test results relating to intelligence and overall job performance test scores.
I have been asked to test significance and strength of the link between scores on the first test and subsequent job performance scores.
I first checked for assumptions for correlation and decided that a Pearson r was most appropriate.
Results show r(25) = +0.33, p = 0.11 , which means a moderately strong correlation but not significant.
I am also required to relate the results to the test author's claims that the test user is able to make excellent predictions about the future job
performance of the test taker. It has been designed to be sensitive to differences in intelligence within a graduate population and the test is free from adverse impact and has superb test-retest reliability.
Am I correct in thinking that the results of a Pearson r would not allow me to relate to the test user's claims as it would not be permissible to comment on any causality between the variables and that I should only report the results from the test stating a correlation and non significance?
Also are there any further tests I should conduct as a result of there being non-significance please?

A: With that small a sample size it is not possible to provide a firm answer about the strength of the link. You could compute a confidence interval and you probably will conclude that both a strong link and even a slight negative link are consistent with the data. As far as significance is concerned, it looks like you computed that correctly.
As far as the quality of predictions, r is only an indirect measure of that because it is also sensitive to the variance of X and slope. Better would be the standard error of the estimate or perhaps the average absolute error of prediction.
P. S. This is probably not the answer your instructor is looking for.


text:
Q: logistic regression vs. bayesian approach I am working with birds dataset to determine success or failure of these introduced species and the effect of response variables on such. A sample from the final dataset i work with below:
dput(birds[1:20,])
structure(list(status = c(1L, 1L, 1L, 0L, 0L, 1L, 0L, 1L, 0L,
0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 1L), length = c(1520L,
1250L, 870L, 720L, 820L, 770L, 50L, 570L, 580L, 480L, 470L, 450L,
435L, 275L, 256L, 230L, 330L, 330L, 300L, 180L), mass = c(9600,
5000, 3360, 2517, 3170, 4390, 1930, 1020, 910, 590, 539, 940,
684, 230, 162, 170, 501, 439, 386, 95), range = c(1.21, 0.56,
0.07, 1.1, 3.45, 2.96, 0.01, 9.01, 7.9, 4.33, 1.04, 2.17, 4.81,
0.31, 0.24, 0.77, 2.23, 0.22, 2.4, 0.69), migr = c(1L, 1L, 1L,
3L, 3L, 2L, 1L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L,
2L), insect = c(12L, 0L, 0L, 12L, 0L, 0L, 0L, 6L, 6L, 0L, 12L,
12L, 12L, 3L, 3L, 3L, 3L, 3L, 3L, 12L), diet = c(2L, 1L, 1L,
2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L,
2L)), .Names = c("status", "length", "mass", "range", "migr",
"insect", "diet"), row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 22L
), class = "data.frame")

My question is: How do i decide which link function to use ?. I have run all possible logit models:
  # logistic regression with binary response
  frec.logit <- glm(status ~ ., data=birds, family=binomial())
  frec.probit <- glm(status ~ ., data=birds, family=binomial("probit"))
  frec.cauchit <- glm(status ~ ., data=birds, family=binomial("cauchit"))
  frec.cll <- glm(status ~ ., data=birds, family=binomial("cloglog"))

  # bayesian
  bay.mod1 <- MCMClogit(status ~ . , family = binomial, data = birds)

  # comparison
  anova(frec.logit, frec.probit, frec.cauchit, frec.cll, bay.mod1)

Here I run into couple of problems.

*

*when running the clog log binomial, I get an error :
Warning message:
glm.fit: fitted probabilities numerically 0 or 1 occurred
However, I still get an output. Later on in the anova comparison there are only 4 models, I assume the clog log model has not been included. I am aware that the complementary log log model is used for survival times and is not appropriate here?
> anova(frec.logit, frec.probit, frec.cauchit, frec.cll, bay.mod1)
Analysis of Deviance Table

Model 1: status ~ length + mass + range + migr + insect + diet
Model 2: status ~ length + mass + range + migr + insect + diet
Model 3: status ~ length + mass + range + migr + insect + diet
Model 4: status ~ length + mass + range + migr + insect + diet
  Resid. Df Resid. Dev Df Deviance
1        65     79.973
2        65     79.811  0  0.16261
3        65     80.582  0 -0.77075
4        65     80.802  0 -0.22064

Can I draw conclusions about the best link function based on this model such as: The deviance is lowest for model 3, corresponding to the cauchit model, therefore this will be used for upcoming variable selection, model adecuacy and prediction.
I have also noticed that some of estimated parameters differ using the frequestist approach from those obtained with bayesian approach (they do not lie withing the baysian CI) - even the sign is different. I thought both approaches should yield the same results?


text:
Q: Get full ImageData after Panning the image inside Cavnas I have a situation where I need to get the full ImageData inside the canvas even after panning the image.
Thanks in Advance
Example in the fiddle: https://jsfiddle.net/z46cvm9h/
<canvas id="canvas"></canvas>
<button onclick="showImage()">
Show panned Image
</button>
<img id="image" src='' />

var context     = canvas.getContext("2d");
canvas.width    = 400;
canvas.height   = 300;

var global = {
scale : 1,
offset    : {
 x : 0,
 y : 0,
},
};
var pan = {
start : {
 x : null,
 y : null,
},
offset : {
 x : 0,
 y : 0,
},
};

function draw() {
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);

context.translate(pan.offset.x, pan.offset.y);

context.beginPath();
context.rect(50, 50, 100, 100);
context.fillStyle = 'skyblue';
context.fill();

context.beginPath();
context.arc(350, 250, 50, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();

}

draw();

canvas.addEventListener("mousedown", startPan);
canvas.addEventListener("mouseleave", endPan);
canvas.addEventListener("mouseup", endPan);

function startPan(e) {
canvas.addEventListener("mousemove", trackMouse);
canvas.addEventListener("mousemove", draw);
pan.start.x = e.clientX;
pan.start.y = e.clientY;
}

function endPan(e) {
canvas.removeEventListener("mousemove", trackMouse);
pan.start.x = null;
pan.start.y = null;
global.offset.x = pan.offset.x;
global.offset.y = pan.offset.y;
}

function trackMouse(e) {
var offsetX    = e.clientX - pan.start.x;
var offsetY    = e.clientY - pan.start.y;
pan.offset.x = global.offset.x + offsetX;
pan.offset.y = global.offset.y + offsetY;
}

function showImage(){
document.getElementById('image').src = canvas.toDataURL();
}

PS: JSFiddle is for demonstration, I can't put the exact scenario into JSFiddle. In the application, I pan the image and then use the mouse to draw something on the canvas using the mousedown and mousemove events. On the mouseup event, I need to have the ImageData with the full image I drew, but when using getImageData, I am only getting the image appearing on the canvas. The panned image is cropped to the canvas size.

A: As @Blindman67 suggested, you can make a second canvas.
Create an object to store the furthest away points in your image.
const imagePadding = {
  top: 0,
  right: 0,
  bottom: 0,
  left: 0
}

top shall be the highest point of the drawing, right shall be the point furthest to the right, and so on. For demonstration purposes, the padding is set equal to how far you have panned in each direction. You will want to set it equal to the shapes/points of the drawing that are furthest in each direction (up, right, down, and left--those are the directions I am talking about).
function panImage(e) {
  pan.x += e.movementX
  pan.y += e.movementY
  drawPreview()

  imagePadding.top = Math.max(imagePadding.top, pan.y)
  imagePadding.left = Math.max(imagePadding.left, pan.x)
  imagePadding.bottom = Math.max(imagePadding.bottom, -pan.y)
  imagePadding.right = Math.max(imagePadding.right, -pan.x)
}

To draw the full image, you can make a function like this:
function drawFinalImage() {
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  const pannedImage = document.getElementById('image')

  canvas.width = previewCanvas.width + imagePadding.left + imagePadding.right
  canvas.height = previewCanvas.height + imagePadding.top + imagePadding.bottom

  ctx.translate(imagePadding.left, imagePadding.top)
  drawShapes(ctx)

  pannedImage.src = canvas.toDataURL()
}

See the JSFiddle for a demo as well as how you can implement the code. Let me know if there is anything I should explain better.
You can use JSFiddle Console to adjust the padding. Type imagePadding.top = 200, press enter, and click the canvas to update the final image.


text:
Q: How to run Slenium+Java+Cucumber without ide Hello there are tests written on Java + cucumber
The structure is as follows:
https://i.imgur.com/moLVY6L.png
The main question is how to run this tests not from the IDE, say from the console or even wrap it all in jar file
The problems encountered are that you need the main class to create a jar,
It seems as there is a certain java cucumber.api.cli.Main - but how to use it I do not understand. Either way, there's probably a way to run this just from the command line. Please tell us how to do it?

A: You can download Maven with following terminal script :
$brew install maven

After brew installation, you need to go to the project directory which includes pom.xml file in terminal :
$cd /path/of/your/project

And finally you can run following command to run your tests :
$mvn clean test

A: You can try the below on command prompt.
java -cp "E:\Workspace\CucumberProj\Jars*;E:\Workspace\CucumberProj\bin" cucumber.api.cli.Main --glue stepDefination E:\Workspace\CucumberProj\Feature\Login_Test.feature


text:
Q: How do I change the colors in the hardstatus line in GNU Screen? I've got the following in my screenrc:
hardstatus on
hardstatus alwayslastline
hardstatus string "%{.bW}%-w%{.rW}%n %t%{-}%+w %=%{..G} %H %{..Y} %m/%d %C%a "

Which is great, but I'd love to be able to change the colors of the text in the hardstatus line.

A: info screen "String Escapes"

Here's my .screenrc for reference.


text:
Q: Add an attribute using xmllint I want to add an attribute to the tag, using xmllint.
Can I do this is through xmllint?

A: Xmllint in not made to edit XML, so I think the answer is "no, you can't".
To edit XML, you can use XMLStarlet, the syntax to add an attribute into existing XML document is:
xmlstarlet ed -L -i xpath -t attr -n name -v value file


text:
Q: JACOB and 64bit JVM-does it work? We have been working fine using JACOB to produce PDFs using a 32 bit JVM for many years without a problem, using Jacob.jar and Jacob.dll.
We now need to upgrade to 64 bit JVM for various reasons. I have downloaded the latest Jacob.jar and dll for 64 bit and installed and added to the path, but when I run, I get:
com.jacob.com.ComFailException: Can't co-create object
at com.jacob.com.Dispatch.createInstanceNative(Native Method)
at com.jacob.com.Dispatch.<init>(Dispatch.java:160)
at com.jacob.activeX.ActiveXComponent.<init>(ActiveXComponent.java:54)
at ...

I am working with jre 1.8.0_131, the manifest for the Jacob.jar is:-
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.9.2
Created-By: 1.7.0_79-b15 (Oracle Corporation)
Built-By: joe
Name: com.jacob
Specification-Title: JACOB : Java COM Bridge
Specification-Vendor: http://jacob-project.sourceforge.net
Implementation-Title: JACOB : Java COM Bridge Java libraries
Implementation-Version: 1.18 build 01 on 05-August-2015 05:01:11
Trusted-Library: true
Application-Name: Java-Windows Bridge
Permissions: all-permissions
Codebase: *

and the Jacob dll is Jacob-1.18-x64.dll
Has anybody out there had success with JACOB with a 64 bit JVM. Specifically for producing PDFs?
Any advice would be helpful as I have been battling this for some time!
Other stack overflow threads that I read:-
Can't co-create object
Many Thanks

A: I got it working with java 1.8 and Jacob-1.19-x64.dll like so:

*

*copy the dll into:

*

*C:\Windows\SysWOW64\

*C:\Program Files\Java\jdk1.8.0_141\lib

*C:\Program Files\Java\jdk1.8.0_141\bin

*Add in the registry the entry DllSurrogate in the key HKCRWow6432NodeAppID{E2779C61-F87E-4038-98A0-1D9E71334706} without a value.

*Create a new key in HKLMSoftwareClassesAppID with the GUID {E2779C61-F87E-4038-98A0-1D9E71334706} without any values.

Source:

*

*the information here about copying the files was not sufficient:
https://github.com/PoojaGugu/SAP-GuiClient-Automation

*https://erpinnews.com/how-to-make-sap-rot-wrapper-library-available-in-a-64-bit-environment


text:
Q: For loop first in a dataframe then in a list - AttributeError Dataframe:
UTC_date    maand   jaar    Eventtype       Eventtype1  Eventtype2   Eventtype3 Headline    Reportdescript  Narrative   content
1   2017-01-02  1   2017    Birdstrike      Operational Operations   Wildlife   Bird hit    Aircraft reports bird hit
3   2017-01-06  1   2017    Near Birdstrike Operational Operations   Wildlife   birdstrike  NaN Possible birdstrike
6   2017-01-10  1   2017    Birdstrike      Operational Operations   Wildlife   bat hit

Desired Dataframe:
UTC_date    maand   jaar    Eventtype       Eventtype1  Eventtype2   Eventtype3 Headline    Reportdescript  Narrative   content  sort
1   2017-01-02  1   2017    Birdstrike      Operational Operations   Wildlife   Bird hit    Aircraft reports bird hit            bird
3   2017-01-06  1   2017    Near Birdstrike Operational Operations   Wildlife   birdstrike  NaN Possible birdstrike              bird
6   2017-01-10  1   2017    Birdstrike      Operational Operations   Wildlife   bat hit                                          bat

List = ['bird', 'rabit', 'rat', 'bat']

I want to check if one of the List values above is present in specific columns of a df, if a value is present I want it to be returned in a new column called sort, so I wrote the following code
for row in df.iloc[:,3:10]:
    for i in list:
        if row.str.contains(i):
            df['sort'] == i
return df

But I get an error. What am I doing wrong?
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-60-86295bce6dba> in <module>
      1 for row in df.iloc[:,3:10]:
      2     for i in birds:
----> 3         if row.str.contains(i):
      4             df['soort'] == i
      5 return df

AttributeError: 'str' object has no attribute 'str'

Dataframe info:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3 entries, 1 to 6
Data columns (total 11 columns):
Column          Non-Null Count  Dtype

0   UTC_date        3 non-null      datetime64[ns]
1   maand           3 non-null      int64
2   jaar            3 non-null      int64
3   Eventtype       3 non-null      object
4   Eventtype1      3 non-null      object
5   Eventtype2      3 non-null      object
6   Eventtype3      3 non-null      object
7   Headline        3 non-null      object
8   Reportdescript  0 non-null      object
9   Narrative       3 non-null      object
10  content         3 non-null      object
dtypes: datetime64ns, int64(2), object(9)
memory usage: 312.0+ bytes


text:
Q: Dataframe join tables & groupby not giving the expected output I am trying to get a table where it shows the pilot who has the fastest lap in each track. My result gives the fastest lap made by each pilot in the circuit, so for example in the example given it shows the fastest lap by pilot, but not the fastest record lap ever in the circuit.
I am going to provide what I have done so far and the result obtained.
#READ CSV FROM URL
results_df = pd.read_csv('data/results.csv')
races_df = pd.read_csv('data/races.csv')
drivers_df = pd.read_csv('data/drivers.csv')

fastest_lap = pd.merge(results_df, races_df, on='raceId', how='inner')

# Delete lap time that is \N
fastest_lap = fastest_lap[fastest_lap["fastestLapTime"] != '\\N']

driver_lap_time_by_circuit = pd.merge(fastest_lap, drivers_df, on="driverId", how="inner")

driver_lap_time_by_circuit = driver_lap_time_by_circuit[["circuitId","forename","fastestLapTime","name"]]

fastest_lap_by_circuit = driver_lap_time_by_circuit.sort_values("fastestLapTime",axis=1).groupby("circuitId")["name","forename","fastestLapTime"].first()

print(fastest_lap_by_circuit)

Output

circuitId
name
forename
fastestLapTime

1
Australian Grand Prix
Adrian
1:28.687

1:28.943

1:30.710

1:31.526

Expected output

circuitId
name
forename
fastestLapTime

1
Australian Grand Prix
Adrian
1:28.687

2
Singapore GP
Hamilton
1:43.045

3
Italian GP
Alonso
1:23.324

4
Monaco
Alonso
1:05.526

A: Try first sorting by the fastest lap and the groupby circuit id and taking the first record -
driver_lap_time_by_circuit.sort_values("fastestLapTime",axis=1).groupby("circuitId").first()["name","forename","fastestLapTime"]


text:
Q: Creating polygon around set of points without blank polygon spaces in between in PostGIS I want to create a polygon around a set of points which should exactly just contain the set of points without leaving any blank spaces in between.
Below is the best output I am getting after using ST_ConcaveHull.
a) With Allow holes set as false

b) With Allow holes set as true

As it is clearly visible in these 2 images that the created polygon has a lot of extra blank spaces. Is there any other PostGIS methods or any other way to get a polygon which will exactly contain points without these spaces?
Below is rough drawing on what I am trying to achieve or the desired output.

The MultiPoint Geometry used for this example - SRID-4326
MULTIPOINT(-1.14550839539633 51.349096419770646,-1.145447973240274 51.349051277340756,-1.14539178158296 51.34901358753763,-1.145343972821787 51.348966971200916,-1.145222612554494 51.349086340628475,-1.145157578005767 51.34911251714186,-1.14507017869585 51.3491477407498,-1.144943675904492 51.3472537660354,-1.144919242528779 51.34915120646431,-1.144878766526116 51.347202046136196,-1.144720187793824 51.34919118904576,-1.144683165018423 51.346991976730955,-1.144662816831716 51.34921421827459,-1.144526992373702 51.34878690461452,-1.144511741772054 51.34704541674788,-1.144464001783175 51.349010131013635,-1.144463501471217 51.34706399459523,-1.144462051819252 51.346980230620765,-1.144460629006732 51.34759708434879,-1.144430717433369 51.348946872495574,-1.144407717835232 51.34700119043971,-1.144391229150454 51.34935570032344,-1.144374115025737 51.34873994555251,-1.144345781203042 51.34845885537696,-1.144299396595842 51.34939150931823,-1.144272215351986 51.34875997516049,-1.144261651462714 51.349143941800165,-1.144242439732235 51.348479762737675,-1.144223666010186 51.34944318084656,-1.144204558317098 51.3470437065884,-1.144167633428061 51.34873771316475,-1.144152571210615 51.347527573398935,-1.144141712519119 51.34847072053944,-1.14413633973979 51.349112471129885,-1.144108474521806 51.35017369504347,-1.144103184442185 51.347078576385016,-1.144040226084474 51.34913286337735,-1.144035299266902 51.34757852596799,-1.144005636147613 51.35023993803115,-1.143996516408931 51.34951084077941,-1.143957158865123 51.34890294944334,-1.143954277891866 51.349310975521924,-1.143951438587779 51.34916528445699,-1.143937334954572 51.35028259656979,-1.143933831555771 51.347645383994944,-1.143929055792627 51.348841987254595,-1.1439159198155 51.34713213364151,-1.143905710885557 51.34877237092709,-1.143903619019044 51.348460901443396,-1.143873752414366 51.34840175577038,-1.143855162513264 51.34833608505633,-1.143834166620764 51.34913746980413,-1.143831665603008 51.347921217152695,-1.1437386163883 51.347207992022845,-1.143721895513458 51.3506672984304,-1.143709076021083 51.34772871312751,-1.143638268900347 51.34801845182888,-1.143626620547187 51.34760470907805,-1.143617282882746 51.35047588536541,-1.143579231728186 51.350362250751814,-1.143563280478384 51.35030490535053,-1.143545558884141 51.34991975765717,-1.143535204773802 51.350204299721526,-1.143530209915138 51.347857197663394,-1.143517809327692 51.350141176489956,-1.143506129471963 51.34980096338131,-1.143485899433675 51.350038314777194,-1.143394303155614 51.347345880576825,-1.143295372529182 51.34744404329489,-1.143264875275143 51.34769429442993,-1.143106460590058 51.35076156625117,-1.142970200189679 51.350791619425785,-1.142924537875887 51.350401910608916,-1.142907192056859 51.34931716267006,-1.142898636729378 51.34753763178483,-1.142888221970861 51.35033873241286,-1.142842488795257 51.35028673011974,-1.1428235249613 51.35022626601221,-1.142795322377737 51.350177198463456,-1.142780832026207 51.34757712035511,-1.142770980956128 51.35084010415572,-1.142645351098051 51.3501301555084,-1.14263558073759 51.350067603580875,-1.142612047211917 51.347611647063275,-1.142587435393211 51.35002289482325,-1.14257620485503 51.34996324710596,-1.142522307438992 51.347642185668114,-1.142501663746491 51.34991814449924,-1.142472008375048 51.34986558613821,-1.14244049033591 51.34980705717423,-1.142326478702596 51.34773046006081,-1.142219331615346 51.34779928464388,-1.14211714231714 51.34951893650008,-1.142037325384087 51.34782610162637,-1.141727772841377 51.35055457549599,-1.141407654397489 51.3499700552294,-1.141386689760339 51.3498798174562)

A: By using the native QGIS Concave hull (alpha shapes) with a Threshold of 0,43 I get a result close of your expectation (but in a more "pointy" shape)

You may try different threshold for a more or less fitted hull, you may also use some buffer to get a more rounded shape afterward
(This is not a postgis answer but as you tag QGIS this is probably acceptable)

A: Just to add some performance; if you want an MST over a point set, use this:
WITH RECURSIVE
    graph AS (
        SELECT  dmp.path[1] AS id,
                dmp.geom
        FROM    ST_Dump('MULTIPOINT(-1.14550839539633 51.349096419770646,-1.145447973240274 51.349051277340756,-1.14539178158296 51.34901358753763,-1.145343972821787 51.348966971200916,-1.145222612554494 51.349086340628475,-1.145157578005767 51.34911251714186,-1.14507017869585 51.3491477407498,-1.144943675904492 51.3472537660354,-1.144919242528779 51.34915120646431,-1.144878766526116 51.347202046136196,-1.144720187793824 51.34919118904576,-1.144683165018423 51.346991976730955,-1.144662816831716 51.34921421827459,-1.144526992373702 51.34878690461452,-1.144511741772054 51.34704541674788,-1.144464001783175 51.349010131013635,-1.144463501471217 51.34706399459523,-1.144462051819252 51.346980230620765,-1.144460629006732 51.34759708434879,-1.144430717433369 51.348946872495574,-1.144407717835232 51.34700119043971,-1.144391229150454 51.34935570032344,-1.144374115025737 51.34873994555251,-1.144345781203042 51.34845885537696,-1.144299396595842 51.34939150931823,-1.144272215351986 51.34875997516049,-1.144261651462714 51.349143941800165,-1.144242439732235 51.348479762737675,-1.144223666010186 51.34944318084656,-1.144204558317098 51.3470437065884,-1.144167633428061 51.34873771316475,-1.144152571210615 51.347527573398935,-1.144141712519119 51.34847072053944,-1.14413633973979 51.349112471129885,-1.144108474521806 51.35017369504347,-1.144103184442185 51.347078576385016,-1.144040226084474 51.34913286337735,-1.144035299266902 51.34757852596799,-1.144005636147613 51.35023993803115,-1.143996516408931 51.34951084077941,-1.143957158865123 51.34890294944334,-1.143954277891866 51.349310975521924,-1.143951438587779 51.34916528445699,-1.143937334954572 51.35028259656979,-1.143933831555771 51.347645383994944,-1.143929055792627 51.348841987254595,-1.1439159198155 51.34713213364151,-1.143905710885557 51.34877237092709,-1.143903619019044 51.348460901443396,-1.143873752414366 51.34840175577038,-1.143855162513264 51.34833608505633,-1.143834166620764 51.34913746980413,-1.143831665603008 51.347921217152695,-1.1437386163883 51.347207992022845,-1.143721895513458 51.3506672984304,-1.143709076021083 51.34772871312751,-1.143638268900347 51.34801845182888,-1.143626620547187 51.34760470907805,-1.143617282882746 51.35047588536541,-1.143579231728186 51.350362250751814,-1.143563280478384 51.35030490535053,-1.143545558884141 51.34991975765717,-1.143535204773802 51.350204299721526,-1.143530209915138 51.347857197663394,-1.143517809327692 51.350141176489956,-1.143506129471963 51.34980096338131,-1.143485899433675 51.350038314777194,-1.143394303155614 51.347345880576825,-1.143295372529182 51.34744404329489,-1.143264875275143 51.34769429442993,-1.143106460590058 51.35076156625117,-1.142970200189679 51.350791619425785,-1.142924537875887 51.350401910608916,-1.142907192056859 51.34931716267006,-1.142898636729378 51.34753763178483,-1.142888221970861 51.35033873241286,-1.142842488795257 51.35028673011974,-1.1428235249613 51.35022626601221,-1.142795322377737 51.350177198463456,-1.142780832026207 51.34757712035511,-1.142770980956128 51.35084010415572,-1.142645351098051 51.3501301555084,-1.14263558073759 51.350067603580875,-1.142612047211917 51.347611647063275,-1.142587435393211 51.35002289482325,-1.14257620485503 51.34996324710596,-1.142522307438992 51.347642185668114,-1.142501663746491 51.34991814449924,-1.142472008375048 51.34986558613821,-1.14244049033591 51.34980705717423,-1.142326478702596 51.34773046006081,-1.142219331615346 51.34779928464388,-1.14211714231714 51.34951893650008,-1.142037325384087 51.34782610162637,-1.141727772841377 51.35055457549599,-1.141407654397489 51.3499700552294,-1.141386689760339 51.3498798174562)'::GEOMETRY) AS dmp
    ),
    tree AS (
        SELECT g.geom::GEOMETRY AS vtcs,
               NULL::GEOMETRY AS segment,
               ARRAY[g.id] AS ids
        FROM   graph AS g
        WHERE  id = 1
        UNION ALL
        SELECT ST_Union(t.vtcs, v.geom),
               ST_ShortestLine(t.vtcs, v.geom),
               t.ids || v.id
        FROM   tree AS t
        CROSS JOIN LATERAL (
            SELECT g.id, g.geom
            FROM   graph AS g
            WHERE  NOT g.id = ANY(t.ids)
            ORDER BY
                   t.vtcs <-> g.geom
            LIMIT  1
        ) AS v
    )
SELECT segment
FROM   tree
WHERE  segment IS NOT NULL
;

Should be much faster.

A: I was able to get the desired result using Minimum Spanning Tree as @Bera had suggested. I looked into it and followed the steps mentioned in the already answered question in the link
Finding the minimum spanning tree (MST)
Then added a buffer to that spanning tree to get the desired polygon.
Below is the output polygon.

Below is the PostGIS query I used after creating the types and functions specified in this github link https://gist.github.com/andrewxhill/13de0618d31893cdc4c5 :
WITH cte2 As (
 WITH cte AS (
   Select row_number() OVER () as id,
         (ST_DumpPoints(ST_SetSRID('MULTIPOINT(-1.14550839539633 51.349096419770646,-1.145447973240274 51.349051277340756,-1.14539178158296 51.34901358753763,-1.145343972821787 51.348966971200916,-1.145222612554494 51.349086340628475,-1.145157578005767 51.34911251714186,-1.14507017869585 51.3491477407498,-1.144943675904492 51.3472537660354,-1.144919242528779 51.34915120646431,-1.144878766526116 51.347202046136196,-1.144720187793824 51.34919118904576,-1.144683165018423 51.346991976730955,-1.144662816831716 51.34921421827459,-1.144526992373702 51.34878690461452,-1.144511741772054 51.34704541674788,-1.144464001783175 51.349010131013635,-1.144463501471217 51.34706399459523,-1.144462051819252 51.346980230620765,-1.144460629006732 51.34759708434879,-1.144430717433369 51.348946872495574,-1.144407717835232 51.34700119043971,-1.144391229150454 51.34935570032344,-1.144374115025737 51.34873994555251,-1.144345781203042 51.34845885537696,-1.144299396595842 51.34939150931823,-1.144272215351986 51.34875997516049,-1.144261651462714 51.349143941800165,-1.144242439732235 51.348479762737675,-1.144223666010186 51.34944318084656,-1.144204558317098 51.3470437065884,-1.144167633428061 51.34873771316475,-1.144152571210615 51.347527573398935,-1.144141712519119 51.34847072053944,-1.14413633973979 51.349112471129885,-1.144108474521806 51.35017369504347,-1.144103184442185 51.347078576385016,-1.144040226084474 51.34913286337735,-1.144035299266902 51.34757852596799,-1.144005636147613 51.35023993803115,-1.143996516408931 51.34951084077941,-1.143957158865123 51.34890294944334,-1.143954277891866 51.349310975521924,-1.143951438587779 51.34916528445699,-1.143937334954572 51.35028259656979,-1.143933831555771 51.347645383994944,-1.143929055792627 51.348841987254595,-1.1439159198155 51.34713213364151,-1.143905710885557 51.34877237092709,-1.143903619019044 51.348460901443396,-1.143873752414366 51.34840175577038,-1.143855162513264 51.34833608505633,-1.143834166620764 51.34913746980413,-1.143831665603008 51.347921217152695,-1.1437386163883 51.347207992022845,-1.143721895513458 51.3506672984304,-1.143709076021083 51.34772871312751,-1.143638268900347 51.34801845182888,-1.143626620547187 51.34760470907805,-1.143617282882746 51.35047588536541,-1.143579231728186 51.350362250751814,-1.143563280478384 51.35030490535053,-1.143545558884141 51.34991975765717,-1.143535204773802 51.350204299721526,-1.143530209915138 51.347857197663394,-1.143517809327692 51.350141176489956,-1.143506129471963 51.34980096338131,-1.143485899433675 51.350038314777194,-1.143394303155614 51.347345880576825,-1.143295372529182 51.34744404329489,-1.143264875275143 51.34769429442993,-1.143106460590058 51.35076156625117,-1.142970200189679 51.350791619425785,-1.142924537875887 51.350401910608916,-1.142907192056859 51.34931716267006,-1.142898636729378 51.34753763178483,-1.142888221970861 51.35033873241286,-1.142842488795257 51.35028673011974,-1.1428235249613 51.35022626601221,-1.142795322377737 51.350177198463456,-1.142780832026207 51.34757712035511,-1.142770980956128 51.35084010415572,-1.142645351098051 51.3501301555084,-1.14263558073759 51.350067603580875,-1.142612047211917 51.347611647063275,-1.142587435393211 51.35002289482325,-1.14257620485503 51.34996324710596,-1.142522307438992 51.347642185668114,-1.142501663746491 51.34991814449924,-1.142472008375048 51.34986558613821,-1.14244049033591 51.34980705717423,-1.142326478702596 51.34773046006081,-1.142219331615346 51.34779928464388,-1.14211714231714 51.34951893650008,-1.142037325384087 51.34782610162637,-1.141727772841377 51.35055457549599,-1.141407654397489 51.3499700552294,-1.141386689760339 51.3498798174562)'::geometry,4326))
         ).geom as geom
 )
 SELECT (minimum_spanning_tree_calc(
           minimum_spanning_tree(geom ,  id::text ORDER BY id ASC) )).the_geom as geom
 FROM cte )
select st_buffer(st_union(geom),0.0002)
from cte2;

I really hope this helps someone. :)


text:
Q: custom date format to mysql in php From a custom utility class, I get the format of a date variable in the following format: d-m-Y. My plan is to use Date('Y-m-d', strtotime($myCustomDate)) but I'm not sure that PHP will return me the right date every time. How can I be sure that my approach is safe?
How can I know that 02-03-2013 will not be transformed as mysql equivalent of 03 February 2013, when I need 02 March 2013.
How do you deal with this problem?

A: The safest way (other than using timestamps, which is a whole different story), would be to use the YYYY-MM-DD format, since there can not be the inverse ( ie YYYY-DD-MM is not defined), and MySQL understands it well.
You can then use PHP to convert it to any other desired format.

A: If the format is always d-m-Y, then you can use a preg_split function to break the date into its component parts and then reformat it using date
<?PHP
  $date = "3-13-2013";
  $date_parts = preg_split("/-/",$date);
  $newDate = Date("Y-m-d",mktime(0, 0, 0, $date_parts[0], $date_parts[1], $date_parts[2]));
?>

This will result in $newDate having the value 2013-03-13.


text:
Q: Collapsing a List to a double[][] I have a variable of type List<double[][]>
An example of what would be in the list is as follows (with each new line being a list element):
{ {1.0,0.0,0.0}, {0.0,0.0,0.0} }
{ {0.0,0.0,0.0}, {1.0,0.0,0.0}, {0.0,1.0,0.0} }

The outcome I need to achieve is a double[][] with all the elements from the list as such (using the same values as above):
{ {1.0,0.0,0.0}, {0.0,0.0,0.0}, {0.0,0.0,0.0}, {1.0,0.0,0.0}, {0.0,1.0,0.0} }

The size of the inner most array will always be the same. However, the outter array varies in size.
I'd really appreciate some help on this one, I seem to think the solution is easy but I just can't come up with it!

A: This is what the Streaming API's flatMap is for:
List<double[][]> list = Arrays.asList(
        new double[][]{{1.0, 0.0, 0.0}, {0.0, 0.0, 0.0}},
        new double[][]{{0.0, 0.0, 0.0}, {1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}});

double[][] result = list.stream()
        .flatMap(Arrays::stream)
        .toArray(double[][]::new);

Produces { {1.0,0.0,0.0}, {0.0,0.0,0.0}, {0.0,0.0,0.0}, {1.0,0.0,0.0}, {0.0,1.0,0.0} }

A: List<double[][]> list;

//calculate the length of the array (sum of the length of all double[][]s in the list)
int resultLen = 0;
for(double[][] d : list)
    resultLen += d.length;

double[][] result = new double[resultLen][];

//copy all double[]s that are in the list (wrapped into double[][]s)
//into the new double[][]
int index = 0;
for(double[][] d : list)
    for(double[] a : d)
        result[index++] = a;

return result;


text:
Q: java.util.date Format Conversion The problem here is that i have the following code:
String newPattern = "yyyy-MM-dd HH:mm:ss.SSS";
SimpleDateFormat formatterDB = new SimpleDateFormat(newPattern);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

String nDate1 = rs.getString("FromDate");
String nDate2 = rs.getString("ToDate");
Date newDate1 = formatterDB.parse(nDate1);
Date newDate2 = formatterDB.parse(nDate2);

Date sd = formatter.parse("2013-08-22");
Date ed = formatter.parse("2013-08-24");
Date exd = formatter.parse("2013-08-23");

The first condition to be verified is that exd lies between [sd,ed] and if true then exd should also lie between [newDate1,newDate2] and if this is true then other elements from the dB will be fetched.
Please not that the source of both dates are different, one date is from the dB having a different format entirely whereas the other date is being given as a String input and they need to be compared, so they have got different format.
To make it more clear, here is an example:

I gave input for exd as 2013-08-23 the input for sd and ed is given
  the newDate1 is 2013-08-28(in dB format) and newDate2 is 2013-09-01(in
  dB Format) Still it accepts the input exd and fetches the other
  column.

** I have snipped the relevant code, for any issues, drop in a comment. Any Help is appreciated. Thanks in Advance!

A: You must use the java inbuilt date functionality.
Here is a small example :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2009-12-31");
Date date2 = sdf.parse("2010-01-31");

if(date1.compareTo(date2)>0){
    System.out.println("Date1 is after Date2");
}else if(date1.compareTo(date2)<0){
    System.out.println("Date1 is before Date2");
}else if(date1.compareTo(date2)==0){
    System.out.println("Date1 is equal to Date2");
}else{
    System.out.println("How to get here?");
}

Edit : Example with respect to user's question
exd is not between newDate1 and newDate2 !!
public class DateCompare {

public static void main(String args[]) throws ParseException
{
    String newPattern = "yyyy-MM-dd HH:mm:ss.SSS";
    SimpleDateFormat formatterDB = new SimpleDateFormat(newPattern);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    String nDate1 = "2013-08-29 11:11:11.000";
    String nDate2 = "2013-09-01 11:11:11.000";
    Date newDate1 = formatterDB.parse(nDate1);
    Date newDate2 = formatterDB.parse(nDate2);

    Date sd = formatter.parse("2013-08-22");
    Date ed = formatter.parse("2013-08-24");
    Date exd = formatter.parse("2013-08-23");

    //Comparing exd to sd and ed
    if(sd.compareTo(exd) * exd.compareTo(ed) > 0)
    {
        //comparing exd to newDate1 and newDate2
        if(newDate1.compareTo(exd) * exd.compareTo(newDate2) > 0)
        {
            System.out.println("Success : Now you can fetch data from DB !");
        }
        else
        {
            System.out.println("Oops ! Can't fetch data !");
        }
    }
  }
}

Please note that in this scenario, if the dates in different formats are compared, if the dates are same, they won't return 0, because of the time factor ! The time will also be compared and dates in yyyy-MM-dd format have HH:mm:ss.SSS all as 00:00:00.000

A: Here is one way of dealing with the problem ....
int flag=0;
  if(exd.compareTo(sd)>0 )
       if(exd.compareTo(ed)<0){
             System.out.println(exd+" Lies between"+ sd +"and"+ ed);
             flag=1;
       }
  /*convert from newPattern to "yyyy-MM-dd"*/
  SimpleDateFormat formatterDB = new SimpleDateFormat(newPattern);
  Date temp = formatterDB.parse(nDate1);
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  String temp1 = formatter.format(temp);
  Date newDate1 = formatter.parse(temp1);
  if(flag==1)
     if(exd.compareTo(newDate1)>0)
         if(exd.compareTo(newDate2)<0){
               /* your code to fetch other item from DB*/
         }

A: Short Answer
These two answers of mine have both the concepts and example code you need to neatly solve your problem:

*

*Parsing strings into date-time objects

*Using Interval objects to compare spans of time
Date versus Date-Time
You have some date-only values and some date-time values. You need to make a decision as to what a date-only value means in relationship to the date-time.
One possibility is that a date-only is considered to be the first moment of the day, such as 2014-01-02 00:00:00. Note that the time of first moment is usually 00:00:00, but not necessarily because Daylight Saving Time (DST) or other anomalies could move the time. For example, 01:00:00. Joda-Time will automatically adjust the time to first moment of day when parsing a date-only string into a date-time. But be aware that you can also call withTimeAtStartOfDay (ignore the "midnight"-related classes/methods as they are virtually deprecated by the creators).
Another possibility is that a date-only should be represented as a span of time, from first moment of the day to the first moment of the next day.
Half-Open
Note that I am referring to the "Half-Open" approach where the beginning is inclusive and the ending is exclusive. Half-open generally works best for spans of time.
For more discussion and examples of Half-Open time spans, see this answer and this answer of mine.
Parse First, Process Second
Get your date strings and date-time strings all parsed into date-time objects first. Once you have some reasonable objects in hand, then move on to your comparisons and business logic.
Joda-Time
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them.
Instead use either the open-source library Joda-Time or the new java.time package in Java 8.
Joda-Time offers three classes to handle a span of time: Period, Duration, and Interval. They include very handy methods of comparison, including contains, abuts, overlap, and gap.
Search StackOverflow
Search for "joda interval" to find other examples.

A: If you're just comparing two dates, where one has precision down to time, you should just truncate the time so both just represent Date.
Using Apache commons:
DateUtils.truncate(dateYouWantToTruncate, Calendar.Date);

Because your formatter is using ISO-8601 (year first, then month, then day), you can use the formatter you created to convert both dates to Strings and compare the strings.
formatter.format(sd).compareTo(formatter.format(newDate1));

You can also use the Calendar class.  It's fairly verbose, but would work.


text:
Q: Repo sync Android source on Ubuntu20.04 failed with "ERROR:root:code for hash md5 was not found." when I do repo sync android source code from server, it failed and outpu the following error message:
$ repo sync -c
ERROR:root:code for hash md5 was not found.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type md5
ERROR:root:code for hash sha1 was not found.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha1
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha512
ERROR:root:code for hash md5 was not found.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type md5
ERROR:root:code for hash sha1 was not found.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha1
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha512

The python version in using is 2.7.5
:~$ python -V
Python 2.7.5
python path:
:~$ whereis python
python: /usr/bin/python3.8 /usr/bin/python3.8-config /usr/bin/python /usr/bin/python2.7 /usr/lib/python3.8 /usr/lib/python3.9 /usr/lib/python2.7 /etc/python3.8 /etc/python2.7 /usr/local/bin/python /usr/local/bin/python2.7-config /usr/local/bin/python2.7 /usr/local/lib/python3.8 /usr/local/lib/python2.7 /usr/include/python3.8 /usr/share/python
And anybody know the reason of this error?
Thanks a lot to share your idea.
Thanks.


text: Q: Mixing Objective-C and Swift in static library I have a project with static library which use only swift, but now I need to add some objective c classes. How to do it correctly? I tried to add bridging header and library compiles without errors, but when I try to use library in another project I get error "Failed to import bridging header 'path/to/my/header/libName-Bridging-Header.h'". Why do I get this error? Should I also somehow use same header in project along with library? Can I do it without bridging header ?


text:
Q: If $P(P(x))=Q(x)^2$, then $P(x)=R(x)^2$? Let $P$ and $Q$ are polynomials from $\mathbb{R}[x]$. Suppose that $P(P(x))=Q(x)^2$. Does it mean that for any such $P(x)$ exists some $R(x)\in \mathbb{R}[x]$ such that $P(x)=R(x)^2$?

A: Yes, $P(x)$ must be a square.  Suppose we have a counterexample $(P(x), Q(x))$, and let $d$ be the degree of $P(x)$.  Then $P(P(x))$ has degree $d^2$, so in order for it to be a square $d$ must be even.  Write $d = 2n$ and $P(x) = a_{2n} x^{2n} + a_{2n-1} x^{2n-1} + \cdots + a_1 x + a_0$.  The leading coefficient $a_{2n}$ is nonzero, and if it were negative then so would be the leading coefficient of $P(P(x))$; thus $a_{2n} > 0$.
We will now construct an approximate square root $R(x) = b_n x^n + \cdots + b_0$ of $P(x)$.  Set $b_n = \sqrt{a_{2n}}$.  Then by repeatedly completing the square, we can find real numbers
\begin{align*}
b_{n-1} & = \frac{a_{2n}}{2b_n}, \\
b_{n-2} & = \frac{a_{2n-2} - b_{n-1}^2}{2b_n}, \\
& \dots \\
b_0 & = \frac{a_n - 2b_1 b_{n-1} - 2b_2 b_{n-2} - \cdots}{2b_n}
\end{align*}
such that $R(x)^2$ agrees with $P(x)$ in degrees $n$ and above; that is, the polynomial $S(x) := P(x) - R(x)^2$ has degree less than $n$.  But then we have
$$
Q(x)^2 = P(P(x)) = R(P(x))^2 + S(P(x)),
$$
where $S(P(x))$ has degree $< 2n^2$ and $Q(x)^2$ and $R(P(x))^2$ both have degree $d^2 = 4n^2$.  These are too close together to be distinct squares, so we must have $Q(x) = R(P(x))$.  Then $S(P(x)) = 0$, so $S(x) = 0$, and thus $P(x)$ is indeed equal to $R(x)^2$.

A: More generally, the following argument shows that if $K$ is a field of characteristic $0$ and $P\in K[x]$ is such that $P\circ P$ is an $\ell$th power for some prime $\ell$, then $P$ is an $\ell$th power.
Suppose $P$ has degree $n$, and has roots $a_1,\dots,a_m$, with multiplicity $d_0,d_1,\dots,d_m$ in an algebraic closure of $K$ (so $\sum d_i=n$).  Let the roots of $P-a_i$ be $b_{i1},\dots,b_{ik_i}$ with multiplicity $e_{i1},\dots,e_{ik_i}$.  Then the $b_{ij}$ are the roots of $P\circ P$, with multiplcity $d_ie_{ij}$.  If $P\circ P$ is an $\ell$th power, then all of these multiplicities must be divisible by $\ell$.  Also, $P$ is an $\ell$th power iff each $d_i$ is divisible by $\ell$ and the leading coefficient $a$ of $P$ is an $\ell$th power.  Note though that the leading coefficient of $P\circ P$ is $a^{n+1}$, so if $P\circ P$ is an $\ell$th power then $a$ is automatically an $\ell$th power (since $a^{n+1}$ is an $\ell$th power and $n$ must be divisible by $\ell$).  So it suffices to show that each $d_i$ is divisible by $\ell$.
Now observe that if $b$ is a root of $P-a$ with multiplicity $d>1$, then $b$ is a root of $P'$ with multiplicity $d-1$.  In particular, this means the sum of all these multiplicities $d-1$ over distinct values of $b$ and all values of $a$ is equal to $n-1$.
Let us now assume that $0$ is not a root of $P$, which implies the values $a_1,\dots,a_m,b_{11},\dots,b_{mk_m}$ are all distinct.  We thus have $$n-1\geq\sum_i (d_i-1)+\sum_i\sum_j (e_{ij}-1)=n-m+\sum_i(n-k_i).\qquad(*)$$  Now since each multiplicity $d_ie_{ij}$ is divisible by $\ell$, for each $i$ either $d_i$ is divisible by $\ell$ or $e_{ij}$ is divisible by $\ell$ for all $j$.  In particular, if $d_i$ is not divisible by $\ell$, then $k_i\leq n/\ell$, so $(*)$ above immediately implies that there is at most one $i$ such that $d_i$ is not divisible by $\ell$.  If exactly one such $d_i$ exists, though, then $m< n/\ell + 1$ (since all other $d_i$ are at least $\ell$), and so $(n-m)+(n-k_i)$ will be greater than $2(\ell-1)n/\ell - 1\geq n-1$, contradicting $(*)$.
It remains to consider the case where $0$ is a root of $P$; let us say $a_1=0$ and $b_{11}=0$.  The only difference in this case is that since $a_1$ and $b_{11}$ are the same we must count them only once when considering the roots of $P'$, and so we must omit the term $e_{11}-1$ in the right side of the sum in inequality $(*)$ above.  Note, though, that $d_1$ must be divisible by $\ell$ since $d_1e_{11}=d_1^2$ is divisible by $\ell$.  The same argument as above then shows that there cannot be any $d_i$ for $i\neq 1$ which is not divisible by $\ell$, and so every $d_i$ is divisible by $\ell$.


text:
Q: How to write code for copy data if condition is met code is copying data after every 5 seconds but i want it to copy only if bu8<>0 and if condition is not met then do nothing.
Here is the code
Sub UpdateData()
    If Hour(Time) >= 3 And Minute(Time) >= 1 Then
        Application.OnTime Now + TimeValue("0:0:5"), "UpdateData", False
    Else
        Application.OnTime Now + TimeValue("0:0:5"), "UpdateData"
    CopyData
    End If
End Sub
Sub CopyData()
    Dim sht1 As Worksheet
    Dim sht2 As Worksheet
    Dim cRng As Range
    Dim dCol As Long
    Set sht1 = ThisWorkbook.Sheets("Sheet1")
    Set sht2 = ThisWorkbook.Sheets("Sheet2")
    Set cRng = sht1.Range("Bu1:bu8")
        dCol = sht2.Cells(2, Columns.Count).End(xlToLeft).Column + 1
        sht2.Range(Cells(2, dCol).Address, Cells(8, dCol + 1).Address) = cRng.Value
End Sub

A: You can do something like this:
Sub CopyData()
    Dim sht1 As Worksheet
    Dim sht2 As Worksheet
    Dim cRng As Range, c As Range
    Dim dCol As Long
    Set sht1 = ThisWorkbook.Sheets("Sheet1")
    Set c = sht1.Range("BU8")

    If c.Value <> 0 and Len(c.Value)>0 Then
        Set sht2 = ThisWorkbook.Sheets("Sheet2")
        Set cRng = sht1.Range("Bu1:bu8")
        sht2.Cells(2, Columns.Count).End(xlToLeft) _
                .Offset(0, 1).Resize(8 ,1).value = cRng.Value

    End If
End Sub


text:
Q: How to get correct automatic continuation lines in F90 mode in Emacs? Assume I am writing some (free-format) Fortran Code in F90 mode, how do I get correct automatic continuation lines when typing and how do I get correctly continued lines when using fill-paragraph?
A code example:
subroutine procedure_with_many_arguments(argument1, argument2, argument3, argument4, argument5, argument6, argument7)

real ::  argument1, argument2, argument3, argument4, argument5, argument6, argument7

end subroutine

1. When typing this code with auto-fill-mode, I get the continuation character &on both lines and also some strange fixed-format-like indentation (ommiting the second and third statements here):
subroutine procedure_with_many_arguments(argument1, argument2, argument3,&
     & argument4, argument5, argument6, argument7)

2. When using fill-paragraph on already existing, too wide code, I get neither any continuation character &, nor any indentation:
subroutine procedure_with_many_arguments(argument1, argument2, argument3,
argument4, argument5, argument6, argument7)

real :: argument1, argument2, argument3, argument4, argument5, argument6,
argument7

end subroutine

Expected result:
subroutine procedure_with_many_arguments(argument1, argument2, &
  argument4, argument5, argument6, argument7)

real :: argument1, argument2, argument3, argument4, argument5, &
  argument6, argument7)

end subroutine

A: Answering my on question here:
1. To get rid of the leading ampersand, add the following lines to your .emacs file:
(setq f90-mode-hook
  '(lambda () (setq f90-beginning-ampersand nil)))

2. To break too wide lines of already existing code, use f90-fill-region instead of fill-paragraph.
Note that thef90-fill-region command crashes Emacs when used on comment lines (versions 24.5.1 and 25.3.1 tested) and the fill-paragraphcommand does nothing on them. There seems to be no fill-command suitable for both code, and comment lines.
Update: The maintainer of the free form Fortran major modef90.el just pushed an update to GitHub that adds a function f90-fill-paragraph. This command works both on comment lines and code.


text:
Q: sleekxmpp 'error reading from xml stream' connected <--> disconnected loop I am on the develop branch.
I modified EchoBot just a little bit, below is the changed/added code, otherwise I took the rest from the example included with the source:
self.add_event_handler("session_start", self.start)
self.add_event_handler("changed_status", self.change)
...

def start(self, event):
    self.send_presence(pshow='xa' , ppriority="0")
    self.get_roster()

def change(self, event):
    #This is django stuff, essentially what I am trying to do is log info from changed_status events
    c = Change(jid = event['from'], timestamp = timezone.now(), new_availability = event['type'], new_priority = event['priority'])
    c.save()
I was having trouble getting this to start period for a while, then after a reboot it worked for about an hour then seemingly out of nowhere the same error below occurred. What happens next is basically a loop of getting connected and then another XML stream error causing a disconnect etc...
ERROR    Error reading from XML stream.
DEBUG    reconnecting...
DEBUG    SEND (IMMED):
INFO     Waiting for  from server
DEBUG     ==== TRANSITION connected -> disconnected
DEBUG    connecting...
DEBUG    Waiting 1.84108932156 seconds before connecting.
DEBUG    Connecting to xx.xxx.xxx.xxx:xxxx
DEBUG     ==== TRANSITION disconnected -> connected
DEBUG    SEND (IMMED):
DEBUG    RECV: X-GOOGLE-TOKENX-OAUTH2
DEBUG    SEND (IMMED):
DEBUG    RECV:
DEBUG    Starting TLS
INFO     Negotiating TLS
INFO     Using SSL version: 3

After this error occurs if I try to run EchoBot from echo_client.py I get stuck at connecting to xx.xxx.xxx.xxx:xxxx.
If I run my version of EchoBot again it begins working properly, but I am worried that other error will occur again.
Possibly relevant:
  * Connecting to Google Talk
  * Also signed in to gmail through my browser
  * Also signed on to Google talk on my Android
My question is how to resolve this error, or what to do to catch it and handle it properly?


text:
Q: When finding $\sin\theta$ and $\cos\theta$ given $\tan\theta = \frac35$, shouldn't I get positive and negative answers?
Q: Find the exact value of $\cos\theta$ and $\sin\theta $ if $ \tan\theta=\frac{3}{5}$

To solve it I got told to draw the triangle and label the sides and then find cos and sin. The answer from the answer sheet gives both cos and sin as positive solutions. However, I thought that, since tan is positive in both the 1st and 3rd quadrants, then you could draw the triangle in those two quadrants. So,

Why don't you get plus-minus solutions for $\sin\theta$ and $\cos\theta$ ?

A: You are correct in that with only the information given in this problem, you could be in either the first or third quadrant and therefore you have two possibilities:

*

*$\sin\theta$ and $\cos\theta$ are both positive.

*$\sin\theta$ and $\cos\theta$ are both negative.

There are two explanations for what is happening.  Either there is (supposed to be) some understood assumption in class that you guys are only working in the first quadrant for now, or the answer sheet is wrong.

A: $$\dfrac{\sin\theta}{\cos\theta}=\dfrac35$$
$$\iff\dfrac{\sin\theta}3=\dfrac{\cos\theta}5=\pm\sqrt{\dfrac{\cos^2\theta+\sin^2\theta}{3^2+5^2}}=?$$

A: We have $\tan\theta=\frac{3}{5}$ so
$$\sin { \theta =\frac { 3 }{ \sqrt { 34 }  } ,\cos { \theta  } =\frac { 5 }{ \sqrt { 34 }  }  } $$


text:
Q: How to retrieve URL dynamically? I am using a webservice in my project. I am giving URL like this:
WebServicename.asmx/Methodname
Locally I used webservice in VBScript and it is running good. But when I deployed same code in a server the webservice is not running. So before that webservice I want to give full URL. So for that reason I want to get that URL dynamically and add before of my URL.

A: I am writing Vb script and I call webservice like this
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")
    Set oXMLDoc = CreateObject("MSXML2.DOMDocument")

    'Msgbox("Calling WebService To Approve Leave")

    strEnvelope ="varCarrierType="&varCarrierType &varCarrierID& "&Filename="&Filename& "&varC22Cnt="&varC22Cnt&"&varCurrentDateTime="&varCurrentDateTime&"&varTotalCommissionAmt="&varTotalCommissionAmt&"&vpath="&vpath

    oXMLHTTP.onreadystatechange = getRef("HandleStateChange")

    call oXMLHTTP.open("POST","/VBScriptService.asmx/InsertDBDetails",False)

    call oXMLHTTP.setRequestHeader("Content-Type","application/x-www-form-urlencoded")

    call oXMLHTTP.send(strEnvelope)
    MsgBox "COM File successfully generated from the Template given. Verify the output file in " & vpath,0, "Com File Generation"

    MsgBox "Page About to Refresh, Click ok to proceed", 0, "ComPage Refresh"
    Set wShell=CreateObject("WScript.Shell")
    wShell.SendKeys "{F5}"


text:
Q: Rails multiple registration paths with Devise I'm using devise in rails, and I'm trying to create a second registration path, the default registration path for users (which works perfectly), and a second registration path whereby a user registers and creates a project in a single action as a "Getting Started" action (Think Freelancer.com or any marketplace whereby non-users can register and create their first project in one action).
I've gone through so many threads but they all seem to want to replace the existing registration action. I want to keep the existing registration action and either add a getting_started_new and getting_started_create actions to the existing User::Registration controller, or create a new GettingStarted Controller with methods for new and create that would then allow the nested form (for a user and their new project).
My latest iteration looks something like this:
routes.rb
devise_for :users

resources :users do
  resources :projects
end

devise_scope :user do
  get "getting_started" =>'getting_started#new'
  post "getting_started" =>'getting_started#create'
end

getting_started_controller.rb
class GettingStartedController < Devise::RegistrationsController

def new
  @user = User.new
  @user.projects.build
end

def create
  @user = User.new(getting_started_params)
  redirect_to root, notice: "Done"
end

private
  def getting_started_params
    params.require(:user).permit(:first_name, :last_name, :phone, :password, :email, projects_attributes: [:user_id, :project_type_id, :name, :industry_id, :description, :budget_id, :project_status_id, feature_ids:[], addon_ids:[]])
  end

end

But when I try and actually submit the form, it loads the getaction from the new controller, and the post action from the devise registration controller.
Started GET "/getting_started" for ::1 at 2016-10-17 09:15:58 +0200
Processing by GettingStartedController#new as HTML
Rendering getting_started/new.html.erb within layouts/application
Project_type Load (0.5ms)  SELECT "project_types".* FROM "project_types"
Industry Load (1.1ms)  SELECT "industries".* FROM "industries" ORDER BY "industries"."name" ASC
Feature Load (0.5ms)  SELECT "features".* FROM "features" ORDER BY "features"."name" ASC
Addon Load (0.4ms)  SELECT "addons".* FROM "addons"
Budget Load (0.4ms)  SELECT "budgets".* FROM "budgets"
Rendered getting_started/new.html.erb within layouts/application (32.9ms)
Rendered layouts/_header.html.erb (1.9ms)
Rendered layouts/_footer.html.erb (0.7ms)
Completed 200 OK in 97ms (Views: 86.4ms | ActiveRecord: 2.9ms)

Started POST "/users" for ::1 at 2016-10-17 09:16:54 +0200
Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"hYrC/15zIF3DzPvhpFQH6LVS9H8XbhfHY1aRkgc2iX6Mdfvz33/O4p72XTpmY4X8E6B+dGfOmjZw7IoizvYwSA==", "user"=>{"first_name"=>"John", "last_name"=>"Smith", "phone"=>"0340239402309", "email"=>"test@example.com", "password"=>"[FILTERED]", "project"=>{"name"=>"This is a test", "description"=>"Tester Description", "feature_ids"=>[""], "addon_ids"=>[""]}}, "project"=>{"project_type_id"=>"4", "industry_id"=>"2", "budget_id"=>"1"}, "commit"=>"Create account"}
Unpermitted parameter: project
(0.1ms)  BEGIN
SQL (1.5ms)  INSERT INTO "users" ("email", "encrypted_password", "created_at", "updated_at", "first_name", "last_name", "phone") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["email", "test@example.com"], ["encrypted_password", "$2a$11$VEVjSrnc5Y5c8ofXvNmlMOHrS.v4tQuBoKMLdHaSOA2S6fiVIHfE."], ["created_at", 2016-10-17 07:16:55 UTC], ["updated_at", 2016-10-17 07:16:55 UTC], ["first_name", "John"], ["last_name", "Smith"], ["phone", "0340239402309"]]
 (139.1ms)  COMMIT
 (0.1ms)  BEGIN
 SQL (0.4ms)  UPDATE "users" SET "sign_in_count" = $1, "current_sign_in_at" = $2, "last_sign_in_at" = $3, "current_sign_in_ip" = $4, "last_sign_in_ip" = $5, "updated_at" = $6 WHERE "users"."id" = $7  [["sign_in_count", 1], ["current_sign_in_at", 2016-10-17 07:16:55 UTC], ["last_sign_in_at", 2016-10-17 07:16:55 UTC], ["current_sign_in_ip", "::1/128"], ["last_sign_in_ip", "::1/128"], ["updated_at", 2016-10-17 07:16:55 UTC], ["id", 17]]
 (0.3ms)  COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 319ms (ActiveRecord: 141.7ms)

I realise that devise does a whole bunch of other stuff besides simply recording the user data, so it may be better to rather move these actions to the Devise User::RegistrationController, and then tweak the accepted params. But how do you override Devise so that it doesn't auto use the devise create method the second you click the submit button, and would instead use a getting_started_create action?

A: First off getting started is a pretty horrible name for a controller since it is not a noun. You can't say a getting started. So lets change it to QuickstartsController.
Lets setup the routes for this resource:
Rails.application.routes.draw do

  # These are your "normal" devise routes
  devise_for :users

  # This is the mapping for the "quickstart" routes
  devise_for :quickstarts,
    class_name: 'User',
    only: [],
    controllers: { registrations: 'quickstarts' }

  # These are the actual routes for quickstarts
  devise_scope :quickstart do
    get   "/quickstarts/new", to: "quickstarts#new", as: :new_quickstart
    post  "/quickstarts",    to: "quickstarts#create", as: :quickstarts
  end
end

Whenever you are overriding a library controller it is important to take some time to study how the class you are superclassing actually works.
If you look at the Devise controllers almost all the actions have a line like:
yield resource if block_given?

Which lets you tap into the flow of the original implementation by calling super with a block:
class QuickstartsController < Devise::RegistrationsController

  # GET /quickstarts/new
  def new
    # This block is passed to the super class implementation:
    super do |resource|
      resource.projects.build
    end
  end

  # POST /quickstarts
  def create
    # You can pass a block here too if you want.
    super
  end

  private

  # This should redirect to the newly created project
  def after_sign_up_path_for(resource)
    polymorphic_path( resource.projects.last )
  end

  # This is the method Devise devise calls for the params.
  def sign_up_params
    # Don't write your params sanitiation on one line! Its not cool.
    params.require(:user)
          .permit(
              :first_name, :last_name, :phone, :password, :email,
              projects_attributes: [
                 :user_id, :project_type_id, :name,
                 :industry_id, :description, :budget_id,
                 :project_status_id,
                 feature_ids:[],
                 addon_ids:[]
              ]
          )
  end
end

But how do you override Devise so that it doesn't auto use the devise
  create method the second you click the submit button, and would
  instead use a getting_started_create action?

Point the form to the correct controller - by passing the url option to form_for.
app/views/quickstarts/new.html.erb:

Getting Started

<%= form_for( resource, as: :user, url: quickstarts_path ) do |f| %>
  <%= devise_error_messages! %>

    <%= f.label :email %>

    <%= f.email_field :email, autofocus: true %>

    <%= f.label :password %>
    <% if @minimum_password_length %>
    (<%= @minimum_password_length %> characters minimum)
    <% end %>

    <%= f.password_field :password, autocomplete: "off" %>

    <%= f.label :password_confirmation %>

    <%= f.password_field :password_confirmation, autocomplete: "off" %>

  <fieldset>
    <legend>Project</legend>
    <% f.fields_for :projects do |pf| %>
      <%# ... %>
    <% end %>
  </fieldset>

    <%= f.submit "Sign up" %>

<% end %>


text:
Q: I dont get responses when sending messages using PushSharp I send push notifications using PushSharp.
I call the method StopAllServices of PushService object to let it send the messages.
I assume that after PushService.StopAllServices finishes , I got the responses for all the Notification objecs.
Afterwards I kill the thread in which the PushService object is instanciated.
PushService = New PushService()
...
...
...

PushService.StopAllServices(True)
...
'the thread dies here

I noticed that sometimes I dont get responses in the callback functions.
Can it be that the method StopAllServices doesnt wait for all responses (from APNS/GCM) ?
I need to recieve responses for all Notification objects. How to achive that ?
I'll be glad for sugestions

A: From the Apple push Service (APNS) you won't get response for all the successfully delivered notifications and that is "by design".
Redth (the author of pushSharp) posted a detailed explanation of this : http://redth.info/the-problem-with-apples-push-notification-ser/
So you'll barely never get one response-per-notification-sent anyway, not useful to wait for all answers to stop the service.
And keep in mind that delivering the notification to the provider (android/apple/microsoft) doesn't guarantee you the effective device delivery of the notification anyway...