text:
Q: Binary Operads sample program Problem Statement :
Write a C++ program to evaluate postfix expressions. Your program should take postfix expression as an input, process it with the help of stack and display the result after performing required calculations.
Only following Binary operators are allowed for this program:
+, -, *, /, ^ [addition, subtraction, multiplication, division, exponentiation]
If some error occurs while processing postfix expression, your program should display a meaningful message, like:
Error: Division by zero not allowed
Error: Two operands required for __ operator
Error: Invalid postfix expression
Help me with it, My program is generating errors This is my try:
#include<iostream>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<string>

#define MAX_SIZE 20

using namespace std;
template<class T>
class Stack
{
private:
    T item[MAX_SIZE];
    int top;
public:
    Stack()
    {
        top = -1;
    }

    void push(T data)
    {
        if(!this->is_full())
            item[++top] = data;
        else
        {
            cout<<"Stack Error"<<endl;
            exit(10);
        }
    }
    T pop()
    {
        if(!this->is_empty())
            return item[top--];
        else
        {
            cout<<"Stack is Empty"<<endl;
            exit(11);
        }
    }

    int size()
    {
        return top+1;
    }

    bool is_empty()
    {
        if(top==-1)
            return true;
        else
            return false;
    }

    bool is_full()
    {
        if(top==MAX_SIZE-1)
            return true;
        else
            return false;
    }

    void display()
    {
        for(int i=0; i<this->size(); i++)
        {
            cout<<item[i]<<" ";
        }
        cout<<endl;
    }
    T return_top()
    {
        return item[top];
    }
};

class Convert
{
private:
    bool num_flag;
    bool tow_digit_flag;
public:
    Convert();
    string return_with_bracket(string infix);
    void to_Postfix(string infix,char postfix[]);
    bool prcd(char op1, char op2);
    int isOperand(char op);
    int isOperator(char op);
    bool return_flag()
    {
        return num_flag;
    }
};

Convert::Convert()
{
    this->num_flag = false;
    this->tow_digit_flag = false;
}
string Convert::return_with_bracket(string infix)
{
    return("(" + infix + ")");
}

bool Convert::prcd(char op1, char op2)
{
    if((op1=='+' || op1=='-' || op1=='*' || op1=='/') && op2=='(' )
        return true;
    if(op1=='+' && op2=='+')
        return true;
    if(op1=='-' && op2=='-')
        return false;
    if(op1=='-' && op2=='+')
        return false;
    if(op1=='+' && op2=='-')
        return false;
    if(op1=='/' && op2=='/')
        return false;
    if(op1=='/' && (op2=='-' || op2=='+'))
        return true;
    if(op1=='*' && (op2=='+' || op2=='-'))
        return true;
    if((op1 == '-' || op1 == '+') && (op2 =='*' || op2 == '/'))
        return false;
    if((op1=='$' || op1 == '+') && (op2 =='*' || op2 == '/' || op2=='-'))
        return true;
    if((op1 == '-' || op1 == '+' || op1 =='*' || op1 == '/')&& op2=='^')
        return false;
    if(op1 == '^' && ( op2 == '+' || op2 =='*' || op2 == '/' || op2=='-'))
        return false;
}

int Convert::isOperand(char op)
{
    return(op>= '0' && op <= '9');
}

int Convert::isOperator(char op)
{
    return(op=='+' || op=='-' || op == '/' || op=='*' || op=='^');
}

void Convert::to_Postfix(string infix, char postfix[])
{
    int position, outpos=0;
    char c;
    int count = 0;
    char temp;
    char stacktop ;
    Stack<char> stack;
    for(position = 0; (c = infix[position])!='\0'; position++)
    {
        if(this->isOperand)
        {
            postfix[outpos++] = c;
            this->num_flag = true;
            count++;
            if(count>=2)
            {
                this->tow_digit_flag = true;
            }
        }
        else if(this->isOperator©)
        {
            count = 0;
            if(isOperator(infix[position]) && isOperator(infix[position+1]))
            {
                cout<<"\aMissing argument in between "<<infix[position]<<" and "<<infix[position+1]
                    <<" in column "<< position+1<<endl;
                exit(9);
            }
            if(this->prcd(c, stacktop))
            {
                stacktop=stack.return_top();
                stack.push©;
                stacktop = c;
            }
            else
            {
                while(true)
                {
                    temp = stack.pop();
                    postfix[outpos++] =temp;
                    stacktop = stack.return_top();
                    if(prcd(c, stacktop) || stacktop=='(')
                        break;
                }
                stack.push©;
                stacktop = stack.return_top();
            }
        }
        else if(c=='(')
        {
            count = 0;
            stack.push©;
            stacktop = stack.return_top();
        }
        else if(c==')')
        {
            count = 0;
            while(1)
            {
                if(stack.size()==0)
                {
                    cout<<"Warning!! Number of ')' is greater than '('" <<endl;
                    exit(2);
                }
                temp = stack.pop();
                if(temp!='(')
                {
                    postfix[outpos++] = temp;
                }
                else
                {
                    break;
                }
            }
            stacktop =stack.return_top();
        }
        else
        {
            cout<<"Invalid input";
            exit(3);
        }
        if(infix[position]==')' && infix[position+1]=='(')
        {
            stack.push('*');
            stacktop = stack.return_top();
        }
    }
    if(stack.size()!=0)
    {
        cout<<"Warning!!Number of '(' is greater than ')'"<<endl;
        // exit(6);
    }
    if(!this->return_flag())
    {
        cout<<"You must Enter Numeric value for calculation"<<endl;
        cout<<"This program cannot perform operations on variables";
        exit(5);
    }
    if(this->tow_digit_flag)
    {
        cout<<"Sory! Althoug u may have entered right string"<<endl;
        cout<<"this program is only for single digit operation"<<endl;
        exit(8);
    }
    postfix[outpos] = '\0';
}

class Evaluate
{
public:
    double eval(char expr[], Convert &Wink;
                double oper(int symb, double op1, double op2);
};
double Evaluate::oper(int symb, double op1, double op2)
{
    switch(symb)
    {
    case '+':
        return (op1 + op2);
    case '-':
        return (op1 - op2);
    case '*':
        return (op1 * op2);
    case '/':
        return (op1 / op2);
    case '^':
        return (pow(op1, op2));
    }
}
double Evaluate::eval(char expr[],Convert &convert)
{
    int c, position;
    char temp1;
    int count = 0;
    double opnd1, opnd2, value;
    Stack<double> stack;
    for(position = 0; (c = expr[position])!='\0'; position++)
    {
        if(convert.isOperand©)
        {
            temp1 = double(c-'0');
            stack.push(temp1);
        }
        else
        {
            opnd2 = stack.pop();
            if(stack.size()==0)
            {
                cout<<"This program cannot process unary operation";
                exit(1);
            }
            opnd1 = stack.pop();
            value = oper(c, opnd1, opnd2);
            stack.push(value);
        }
    }
    if(stack.size()>=2)
    {
        cout<<"Sory! this program cannot calculate this"<<endl;
        cout<<"Enter +, *, /, - or ^ between bracket"<<endl;
        exit(4);
    }

    return (stack.pop());
}
int main()
{
    Convert convert;
    Evaluate evaluate;
    string bracketted_infix;
    char infix[50], postfix[50];
    char choice;
    while(1)
    {
        cout<<"Enter operation: ";
        cin>>infix;
        cout<<endl;
        cout<<"Entered operation: "<<infix<<endl;
        bracketted_infix = convert.return_with_bracket(infix);
        convert.to_Postfix(bracketted_infix, postfix);
        cout<<"Equivalent Postfix operation: "<<postfix<<endl;
        cout<<"RESULT: ";
        cout<<evaluate.eval(postfix, convert);
        cout<<"\nCalculate another operation?(y/n) ";
        cin>>choice;
        cout<<endl;
        if(choice=='n')
            break;
    }
    return 0;
}

A: To get it actually compiling you need to fix two syntax errors;
On line 154 you are calling a method with no parameter,
but the only declaration of this method takes 1 parameter.
if (this->isOperand) {

I believe you may have meant:
if (this->isOperand(c)) {

Also on line 255 you have a missing bracket before the semicolon:
double eval(char expr[], Convert &Wink;

When I actually ran your code it failed at runtime, with VS2010 giving an error "string subscript out of range".
If you're not already, I would recommend using a good IDE (such as Visual C++) when developing; the syntax colouring and support for dynamic debugging (i.e. breakpoints and watches) would be very helpful to debug a program like this.

A: Here is the final solution
#include<iostream>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<string>

#define MAX_SIZE 20

using namespace std;
template<class T>
class Stack
{
private:
    T item[MAX_SIZE];
    int top;
public:
    Stack()
    {
        top = -1;
    }

    void push(T data)
    {
        if(!this->is_full())
            item[++top] = data;
        else
        {
            cout<<"Stack Error"<<endl;
            exit(10);
        }
    }
    T pop()
    {
        if(!this->is_empty())
            return item[top--];
        else
        {
            cout<<"Stack is Empty"<<endl;
            exit(11);
        }
    }

    int size()
    {
        return top+1;
    }

    bool is_empty()
    {
        if(top==-1)
            return true;
        else
            return false;
    }

    bool is_full()
    {
        if(top==MAX_SIZE-1)
            return true;
        else
            return false;
    }

    void display()
    {
        for(int i=0; i<this->size(); i++)
        {
            cout<<item[i]<<" ";
        }
        cout<<endl;
    }
    T return_top()
    {
        return item[top];
    }
};

class Convert
{
private:
    bool num_flag;
    bool tow_digit_flag;
public:
    Convert();
    string return_with_bracket(string infix);
    void to_Postfix(string infix,char postfix[]);
    bool prcd(char op1, char op2);
    int isOperand(char op);
    int isOperator(char op);
    bool return_flag()
    {
        return num_flag;
    }
};

Convert::Convert()
{
    this->num_flag = false;
    this->tow_digit_flag = false;
}
string Convert::return_with_bracket(string infix)
{
    return("(" + infix + ")");
}

bool Convert::prcd(char op1, char op2)
{
    if((op1=='+' || op1=='-' || op1=='*' || op1=='/') && op2=='(' )
        return true;
    if(op1=='+' && op2=='+')
        return true;
    if(op1=='-' && op2=='-')
        return false;
    if(op1=='-' && op2=='+')
        return false;
    if(op1=='+' && op2=='-')
        return false;
    if(op1=='/' && op2=='/')
        return false;
    if(op1=='/' && (op2=='-' || op2=='+'))
        return true;
    if(op1=='*' && (op2=='+' || op2=='-'))
        return true;
    if((op1 == '-' || op1 == '+') && (op2 =='*' || op2 == '/'))
        return false;
    if((op1=='$' || op1 == '+') && (op2 =='*' || op2 == '/' || op2=='-'))
        return true;
    if((op1 == '-' || op1 == '+' || op1 =='*' || op1 == '/')&& op2=='^')
        return false;
    if(op1 == '^' && ( op2 == '+' || op2 =='*' || op2 == '/' || op2=='-'))
        return false;
}

int Convert::isOperand(char op)
{
    return(op>= '0' && op <= '9');
}

int Convert::isOperator(char op)
{
    return(op=='+' || op=='-' || op == '/' || op=='*' || op=='^');
}

void Convert::to_Postfix(string infix, char postfix[])
{
    int position, outpos=0;
    char c;
    int count = 0;
    char temp;
    char stacktop ;
    Stack<char> stack;
    for(position = 0; (c = infix[position])!='\0'; position++)
    {
     if (this->isOperand(c))

        {
            postfix[outpos++] = c;
            this->num_flag = true;
            count++;
            if(count>=2)
            {
                this->tow_digit_flag = true;
            }
        }
        else if(this->isOperator(c))
        {
            count = 0;
            if(isOperator(infix[position]) && isOperator(infix[position+1]))
            {
                cout<<"\aMissing argument in between "<<infix[position]<<" and "<<infix[position+1]
                    <<" in column "<< position+1<<endl;
                exit(9);
            }
            if(this->prcd(c, stacktop))
            {
                stacktop=stack.return_top();
                stack.push(c);
                stacktop = c;
            }
            else
            {
                while(true)
                {
                    temp = stack.pop();
                    postfix[outpos++] =temp;
                    stacktop = stack.return_top();
                    if(prcd(c, stacktop) || stacktop=='(')
                        break;
                }
                stack.push(c);
                stacktop = stack.return_top();
            }
        }
        else if(c=='(')
        {
            count = 0;
            stack.push(c);
            stacktop = stack.return_top();
        }
        else if(c==')')
        {
            count = 0;
            while(1)
            {
                if(stack.size()==0)
                {
                    cout<<"Warning!! Number of ')' is greater than '('" <<endl;
                    exit(2);
                }
                temp = stack.pop();
                if(temp!='(')
                {
                    postfix[outpos++] = temp;
                }
                else
                {
                    break;
                }
            }
            stacktop =stack.return_top();
        }
        else
        {
            cout<<"Invalid input";
            exit(3);
        }
        if(infix[position]==')' && infix[position+1]=='(')
        {
            stack.push('*');
            stacktop = stack.return_top();
        }
    }
    if(stack.size()!=0)
    {
        cout<<"Warning!!Number of '(' is greater than ')'"<<endl;
        // exit(6);
    }
    if(!this->return_flag())
    {
        cout<<"You must Enter Numeric value for calculation"<<endl;
        cout<<"This program cannot perform operations on variables";
        exit(5);
    }
    if(this->tow_digit_flag)
    {
        cout<<"Sory! Althoug u may have entered right string"<<endl;
        cout<<"this program is only for single digit operation"<<endl;
        exit(8);
    }
    postfix[outpos] = '\0';
}

class Evaluate
{
public:
    double eval(char expr[], Convert &Wink);
                double oper(int symb, double op1, double op2);
};
double Evaluate::oper(int symb, double op1, double op2)
{
    switch(symb)
    {
    case '+':
        return (op1 + op2);
    case '-':
        return (op1 - op2);
    case '*':
        return (op1 * op2);
    case '/':
        return (op1 / op2);
    case '^':
        return (pow(op1, op2));
    }
}
double Evaluate::eval(char expr[],Convert &convert)
{
    int c, position;
    char temp1;
    int count = 0;
    double opnd1, opnd2, value;
    Stack<double> stack;
    for(position = 0; (c = expr[position])!='\0'; position++)
    {
        if(convert.isOperand(c))
        {
            temp1 = char(c-'0');
            stack.push(temp1);
        }
        else
        {
            opnd2 = stack.pop();
            if(stack.size()==0)
            {
                cout<<"This program cannot process unary operation";
                exit(1);
            }
            opnd1 = stack.pop();
            value = oper(c, opnd1, opnd2);
            stack.push(value);
        }
    }
    if(stack.size()>=2)
    {
        cout<<"Sory! this program cannot calculate this"<<endl;
        cout<<"Enter +, *, /, - or ^ between bracket"<<endl;
        exit(4);
    }

    return (stack.pop());
}
int main()
{
    Convert convert;
    Evaluate evaluate;
    string bracketted_infix;
    char infix[50], postfix[50];
    char choice;
    while(1)
    {
        cout<<"Enter operation: ";
        cin>>infix;
        cout<<endl;
        cout<<"Entered operation: "<<infix<<endl;
        bracketted_infix = convert.return_with_bracket(infix);
        convert.to_Postfix(bracketted_infix, postfix);
        cout<<"Equivalent Postfix operation: "<<postfix<<endl;
        cout<<"RESULT: ";
        cout<<evaluate.eval(postfix, convert);
        cout<<"\nCalculate another operation?(y/n) ";
        cin>>choice;
        cout<<endl;
        if(choice=='n')
            break;
    }
    return 0;
}


text:
Q: Реализация удаления временных аккаунтов по истечению их срока действия Решил для интернет-магазина создавать временные аккаунты.
То есть можно зарегистрироваться и заходить в постоянный аккаунт с логином и паролем, указанными при регистрации, а можно просто класть в корзину товары, не регистрируясь.
Для этого у меня создается при первом посещении сайта Guid-строка, которая записывается в куки как UnauthenticatedID.
Можно было бы просто связать товар в корзине с этим Guid, но там идет привязка по (int)Id пользователя из таблицы Users, поэтому создаются эти самые аккаунты, чтобы не создавать новых колонок.
У аккаунтов, как и у самих куков, есть Expiration Date = 14 дней с момента регистрации. Отсюда вопрос: как мне лучше реализовать автоматическую ежедневную проверку на наличие истекших аккаунтов и их удаления?
Если непонятно объяснил, что я и подозреваю, могу что-то дополнить

A: почему просто не сделать продажу без регистрации?
но если обязательно нужно, то логика такая:

*

*создаем обычный аккаунт, но втихую, в любое из полей, например имя, пишем timestamp, в логин вписываем что-то типа tempUser

*при регистрации нового аккаунта в конец скрипта добавляем еще один запрос к БД - очистку таблицы исходя из timestamp+2 недели для всех пользователей tempUser, получается новый пользователь добавляется и одновременно устаревшие удаляются

A: Если вам нужно делать что-то по расписанию - лучше сделать отдельный job (консольку) и дергать ее извне по расписанию. Скорее всего ваш хостер поддерживает jobs (на Azure это webjobs, в k8s - cron jobs).
Если хостер джобы не поддерживает - и нужно обойтись только средствами asp.net core - попробуйте выполнять чистку через Quartz.NET. Не так надежно и предсказуемо, как отдельным job-ом, но лучше, чем ничего.

Совсем альтернативный вариант - не чистить вообще. Если на сайте не сверхпосещаемость - никаких проблем не будет. Даже наоборот, когда созреете делать аналитику по юзерам - у вас будут готовые данные :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Large data aggregations good in Business Layer(JAVA) or DatabaseLayer(Stored Procedures)? In our application we have very large data.
We would require to do aggregations and calculations for various conditions(based on what user select in UI).
1)Since the data is very large is it advised to do all the
    aggregations(business logic) in database(procedures) ?or
  2)Will there be a major impact if done in Business Layer after getting    data from DB?
     As  all the data will be converted to objects and then aggregation is done.

A: I suspect you should use the database to do most of the work, but you can use ad hoc queries driven by the business logic rather than stored procedures.

A: I'm assuming your app/web server and your database server are separated. You will want to minimize the amount of data that needs to cross the wire. Besides, data aggregation is something database engines are very good at so you should let them do what they do well. So I'd suggest you do the aggregation in your database.


text:
Q: jQuery help needed with hover Hey guys for some strange reason I can't get this to work...I just need a simple effect on hover where if the link is hovered upon, the padding-left changes to a certain pixels..
jQuery("nav li ul li").hover(function() {
     var padding = parseInt(jQuery(this).find("> a").css("paddingLeft");
         var new_padding = (padding + 5);
     jQuery(this).find("> a").stop(true,true).animate({ paddingLeft: new_padding},200);
     }, function() { jQuery(this).find("> a").animate({ paddingLeft: padding},200);}
);

So the above I am just trying to say move the padding left to 5 more than the original and move it back to original when mouse out. The above keeps moving to the right with padding and doesn't go back for some reason...I know I am missing something simple..
Thanks...

A: I would strong suggest you use += and -= animation capabilities in jQuery to add and remove a fixed amount from the padding.  That way you can do everything a lot simpler without actually fetching the value of the padding or having to keep track of anything in variables.  See http://api.jquery.com/animate/ for examples.  Using this will also solve the scoping problem you have with the new_padding variable because you won't need it any more.
Then, I don't think the find("> a") is necessarily doing what you want.  If you just want to find "a" tags that are children of the nav li ul li that is being hovered over, then you should just do find("a").  That will find descendants of all the matches selectors in the first call that are "a" tags.
I think you can use something like this:
jQuery("nav li ul li").hover(
     function() {
         jQuery(this).find("a").stop(true,true).animate({paddingLeft: "+=5"},200);
     },
     function() {
         jQuery(this).find("a").stop(true, true).animate({paddingLeft: "-=5"},200);
     }
);

You can see it work here in this demo of the code: http://jsfiddle.net/jfriend00/9YQaV/

A: Without running your code, I'm going to guess that the second function is throwing an error, and never getting executed.  You've defined padding as a local variable in the first function, but the second function doesn't know about it.  It looks for padding in its scope, doesn't find it, looks for it at the global scope, doesn't find it, and throws an exception.
Fire up Firebug in Firefox to see if I'm right...  If I am, you've got a couple options:

*

*Make padding a global.  You should be able to do this just by removing the var part of its declaration.  But globals are kinda sketchy, and they'll rely on the functions that rely on them being called in the expected order (in1 -> out1 -> in2 -> etc.), and while that's likely, it's not guaranteed.

*Reload the margin property from the element in each function.  This is what I'd do, even if it's a touch less efficient.

(Breaker line to force SO to format this...)
$("nav li ul li").hover(
    function() {$(this).find("> a").animate({ paddingLeft: load_padding() + 5}, 200);},
    function() {$(this).find("> a").animate({ paddingLeft: load_padding() - 5}, 200);}
)

Hope this helps!
PS:  Hopefully that code formats okay - this preview's butchering it...
PPS: It didn't, but I figured it out.

A: First of all, you're missing a closing parenthesis here:
var padding = parseInt(jQuery(this).find("> a").css("paddingLeft");

and you should always supply the radix argument to parseInt:
var padding = parseInt(jQuery(this).find("> a").css("paddingLeft"), 10);

Then you have a scope issue with padding. You're declaring padding in the first function argument to hover but trying to use it in both the first and second functions; the result is that the animate in the mouseout function does nothing because padding isn't defined in there.
If you put your var padding; outside the hover functions:
var padding;
jQuery("nav li ul li").hover( //...

You'll get better results.


text:
Q: What are the other defines relating to #define KB_UP 72 for c++? What are all of them? So I'm working to learn about how to get DIRECT keyboard input with c++. Right now i know how to use the getch() function and functions of that nature but I don't know how to define all the different keyboard inputs. These are the kind of ones I'm looking for.
#define KB_UP 72
#define KB_DOWN 80
#define KB_LEFT 75
#define KB_RIGHT 77
#define KB_ESCAPE 27
#define KB_ENTER 28
So ultimately what are the others, are there others? I'm working with c++ on code::blocks on windows.
Thanks in advance :)

A: Look at the windows API doc for the winapi function  GetAsyncKeyState() which has a link to a page listing the virtual key codes returned by this function.  The list includes the codes you mention in your q, but they are prefixed with VK_ rather than KB_.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms646293(v=vs.85).aspx

A: Sorry that this doesn't directly answer your question, but I've grown quite fond of this tutorial for keyboard input.
http://www.gamedev.net/blog/355/entry-2250186-designing-a-robust-input-handling-system-for-games/
You should take a look.

A:
This code will help to find KB_code value of every keyboard key

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    int KB_code=0;
    while(1)
    {

     if (kbhit())
      {
            KB_code = getch();
            cout<<"KB_code = "<<KB_code<<"\n";
}
    }
return(0);
}


text:
Q: How to construct a FileBean from a StripesRequestWrapper I can see the file attachment using the Eclipse debugger as shown here:

But I can't find the proper method(s) to extract the file information in my event handler. I have a list of panels on my page that each has a unique ID and a file chooser and the data is making it to the server but I cannot get at it other than seeing it in the debugger.
I originally just had an indexed list of them which did successfully get put in setFileAttachment() but then I cannot match the indexed files with the actual panel they came from.
Here is the stripes tag I am trying to capture the file from:
<stripes:file name="fileAttachment_${docRowBundle.emptyDocMap.documentid}" id="fileAttachment_${docRowBundle.emptyDocMap.documentid}" class="file hidden" size="35" />


text:
Q: convert  TO  C++, Win32 Is there some method to convert a vector to a vector in C++, win32?
I've got this string vector with numbers:
std::vector<std::string> DataNumbers;

I need to convert this vector string into  vector integer.

A: The C++ way of doing it is this:
vector<std::string> input = ...;
vector<int> output;

for (auto &s : input) {
    std::stringstream parser(s);
    int x = 0;

    parser >> x;

    output.push_back(x);
}

Without knowing what you want to do when the input fails, there's not much more to say here.

A: Try this:
   std::vector<std::string> DataNumbers;
    // Fill DataNumbers
    std::vector<int> intNumbers;
    for (int i=0; i<= 5; i++)
    {
     int num = atoi(DataNumbers.at(i).c_str());
     intNumbers.push_back(num);
    }

A: Given:
std::vector<std::string> DataNumbers;
// Fill DataNumbers
std::vector<int> Data;

You can use std::transform. Use a std::back_inserter to insert the values into the std::vector<int>. For the unary function, use a lambda expression that uses std::stoi to convert the strings to integers.
std::transform(DataNumbers.begin(), DataNumbers.end(), std::back_inserter(Data),
               [](const std::string& str) { return std::stoi(str); });

And here's a version without lambdas (using std::bind instead):
typedef int(*stoi_type)(const std::string&, std::size_t*, int);
std::transform(DataNumbers.begin(), DataNumbers.end(), std::back_inserter(Data),
               std::bind(static_cast<stoi_type>(&std::stoi),
                         std::placeholders::_1, nullptr, 10));

A: What about:
#include <algorithm>
#include <boost/lexical_cast.hpp>

template<typename C1, typename C2>
void castContainer(const C1& source, C2& destination)
{
    typedef typename C1::value_type source_type;
    typedef typename C2::value_type destination_type;
    destination.resize(source.size());
    std::transform(source.begin(), source.end(), destination.begin(), boost::lexical_cast<destination_type, source_type>);
}

It can convert vector<string> into vector<int>, and also other container<T1> into container2<T2>, e.g.: list -> list.
Full code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <boost/lexical_cast.hpp>

template<typename C1, typename C2>
void castContainer(const C1& source, C2& destination)
{
    typedef typename C1::value_type source_type;
    typedef typename C2::value_type destination_type;
    destination.resize(source.size());
    std::transform(source.begin(), source.end(), destination.begin(), boost::lexical_cast<destination_type, source_type>);
}

template<typename T, typename T2>
std::vector<T>& operator<<(std::vector<T>& v, T2 t)
{
    v.push_back(T(t));
    return v;
}

main(int argc, char *argv[])
{
    std::vector<std::string> v1;
    v1 << "11" << "22" << "33" << "44";
    std::cout << "vector<string>: ";
    std::copy(v1.begin(), v1.end(), std::ostream_iterator<std::string>(std::cout, ", "));
    std::cout << std::endl;

    std::vector<int> v2;
    castContainer(v1, v2);

    std::cout << "vector<int>: ";
    std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << std::endl;
}


text:
Q: Post cache substitution is not compatible with modules in the IIS integrated pipeline that modify the response buffers I got this error on one of my SharePoint sites.

A: I had to change this setting in my web.config
<urlCompression
 doDynamicCompression="true"
 doStaticCompression="true"
 dynamicCompressionBeforeCache="<this should be false>"/>

Set dynamicCompressionBeforeCache to false and it worked for me.
Thanks to this post:
http://www.sitefinity.com/devnet/forums/general-discussions-/post-cache-substitution-is-not-compatible-with-modules-in-the-iis-integrated-pipeline-that-modify-the-response-buffers

A: For me, disabling the output cache in the web.config worked, like so:
<system.web>
    <caching>
        <outputCache enableOutputCache="false"/>
    </caching>
</system.web>


text:
Q: Docker working on localhost but have an empty containers running list Yesterday I decided to learn docker and use it for a prestashop project so I created a docker-compose.yml my goal was to run a prestashop with a phpmyadmin and mysql all linked together.
Before leaving yesterday I didn't want to lose everything I had done so I ran a docker save and a docker commit, so I thought whenever I come back I can just run the save I made and run it without losing anything (like a snapshot).
Everything was working, containers were running and today when I try to run a docker ps -a I have an empty output. However my project is still working on localhost:8080 for prestashop and localhost:8081 for my phpmyadmin.
How could I find back the containers and also save them so I can use them on another computer?
docker-compose.yml :
version: "3.8"
 services:
  db:
    image: mysql:latest
    command: --default-authentication-plugin=mysql_native_password
    container_name: db
    restart: always
    volumes:
      - db-data:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=root
    networks:
      - dev

  phpmyadmin:
    image: phpmyadmin:latest
    container_name: phpmyadmin
    restart: always
    depends_on:
      - db
    ports:
      - 8081:80
    environment:
      PMA_HOST: db
    networks:
      - dev

  apache:
    build: php
    container_name: prestashop
    ports:
      - 8080:80
    volumes:
      - ./php/vhosts:/etc/apache2/sites-enabled
      - ./:/var/www/html
    restart: always
    networks:
      - dev

networks:
  dev:

volumes:
  db-data:

Dockerfile :
FROM php:7.4-apache

RUN echo "ServerName localhost" >> /etc/apache2/apache2.conf

RUN apt-get update \
    && apt-get install -y --no-install-recommends locales apt-utils git libicu-dev g++ libpng-dev libxml2-dev libzip-dev libonig-dev libxslt-dev;

RUN echo "en_US.UTF8 UTF8" > /etc/locale.gen && \
    echo "fr_FR.UTF-8 UTF-8" >> /etc/locale.gen && \
    locale-gen

RUN curl -sSk https://getcomposer.org/installer | php -- --disable-tls && \
    mv composer.phar /usr/local/bin/composer

RUN docker-php-ext-configure intl
RUN docker-php-ext-install pdo pdo_mysql gd opcache intl zip calendar dom mbstring zip gd xsl
RUN pecl install apcu && docker-php-ext-enable apcu
RUN a2enmod rewrite && service apache2 restart
RUN chown -R www-data:w

Output for docker images :
REPOSITORY          TAG          IMAGE ID       CREATED       SIZE
prestadock_apache   latest       740c640530f3   2 days ago    657MB
phpmyadmin          latest       f7fd780fedba   7 days ago    469MB
php                 7.4-apache   899ab23566b7   7 days ago    414MB
mysql               latest       c8562eaf9d81   10 days ago   546MB

Output for docker network ls
NETWORK ID     NAME             DRIVER    SCOPE
e03870bf5fec   bridge           bridge    local
63cfaacfbb2e   chronopiles      bridge    local
c23a0b85edb9   host             host      local
1ae1b68b12c0   none             null      local
1e8010db79e3   prestadock_dev   bridge    local
590b5e949037   prestashop       bridge    local

A: The easier approach is pushing your images to the docker hub and just copying yml file to another pc and run docker-compose up command. To achieve this you have to add imagename with your docker hub user name like this:
version: "3.8"
 services:
  db:
    image: mysql:latest
    command: --default-authentication-plugin=mysql_native_password
    container_name: db
    restart: always
    volumes:
      - db-data:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=root
    networks:
      - dev

  phpmyadmin:
    image: phpmyadmin:latest
    container_name: phpmyadmin
    restart: always
    depends_on:
      - db
    ports:
      - 8081:80
    environment:
      PMA_HOST: db
    networks:
      - dev

  apache:
    build: php
    image: benju1/prestashop
    container_name: prestashop
    ports:
      - 8080:80
    volumes:
      - ./php/vhosts:/etc/apache2/sites-enabled
      - ./:/var/www/html
    restart: always
    networks:
      - dev

networks:
  dev:

volumes:
  db-data:

To push the docker images to docker hub follow this command instruction by opening shell or commandline in the folder of docker-compose.yml file

*

*Type docker login and enter

*Enter your docker hub credentials to login

*type docker-compose build . and enter to build your images

*type docker-compose push and enter to push the images in your dockerhub

then copy your docker-compose.yml file in your other computer and just type
docker-compose up -d  to run your project.


text:
Q: Occasionally getting error: "The request was aborted: Could not create SSL/TLS secure channel." I have a problem with my .NET Windows Client Application. Occasionally, about 1 out of 100 web service calls, I get the error:

The request was aborted: Could not create SSL/TLS secure channel.

When does the error show?

*

*In Windows 7, but not in Windows 10

*When using Fiddler, the error does not occur.

I have tried the following

*

*Upgraded from .NET framework 4.5 to 4.8

*Tried different Security Protocol settings with ServicePointManager.SecurityProtocol. (The request was aborted: Could not create SSL/TLS secure channel)

*I have tried to uninstall windows security patches from this period to see if it has anything to do with those.

Now I'm running out of ideas and I can't find anyone else with a similar problem.
Please help me, I'm desperate. :)


text:
Q: Not able to setup MySQL root password using Ansible I can't setup MySQL root password using Ansible. I get the error:

[jumphost] (item=manikins1) => {"ansible_loop_var": "item", "changed": false, "item": "manikins1", "msg": "unable to connect to database, check login_user and login_password are correct or /root/.my.cnf has the credentials. Exception message: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods"}

  - name: Sets the root password
    mysql_user:
       login_user=root
       login_password="{{mysql_root_pass.stdout}}"
       user=root
       password="{{password}}"
       check_implicit_admin=yes
       host="{{item}}"
       priv="*.*:ALL,GRANT"
    with_items:
    - "{{ ansible_hostname }}"
    - 127.0.0.1
    - ::1
    - localhost

A: Although you did not give that information, the error message suggest you are using mysql 8 with sha256 or caching sha2 authentification.
Quoting notes on the official module documentation

Currently, there is only support for the mysql_native_password encrypted password hash module.

You have two options:

*

*Configure mysql 8 to use native passwords

*Don't use this module and modify the password by your own means (script, shell command)


text:
Q: How to solve org.apache.hadoop.io.LongWritable cannot be cast to org.apache.hadoop.io.Text I am trying to analyze a retail store data where i want to solve the breakdown of sales by city ,Here is my data
Date       Time   City        Product-Cat      Sale-Value Payment-Mode
2012-01-01 09:20  Fort Worth  Women's Clothing 153.57     Visa
2012-01-01 09:00  San Jose    Mens Clothing    214.05     Rupee
2012-01-01 09:00  San Diego   Music            76.43      Amex
2012-01-01 09:00  New York    Cameras           45.76     Visa

Now i want to calculate sales break down by product category across all the stores
Here is the Mapper and reducer and the main class
public class RetailDataAnalysis {

public static class RetailDataAnalysisMapper extends Mapper<Text,Text,Text,Text>{

   // when trying with LongWritable Key
    public void map(LongWritable key,Text Value,Context context) throws IOException, InterruptedException{

        String analyser [] = Value.toString().split(",");
        Text productCategory = new Text(analyser[3]);
        Text salesPrice = new Text(analyser[4]);
        context.write(productCategory, salesPrice);
    }

 // When trying with Text key

    public void map(Text key,Text Value,Context context) throws IOException, InterruptedException{

        String analyser [] = Value.toString().split(",");
        Text productCategory = new Text(analyser[3]);
        Text salesPrice = new Text(analyser[4]);
        context.write(productCategory, salesPrice);
    }

}

public static class RetailDataAnalysisReducer extends Reducer<Text,Text,Text,Text>{

    protected void reduce(Text key,Iterable<Text> values,Context context)throws IOException, InterruptedException{
        String csv ="";
        for(Text value:values){

            if(csv.length()>0){
                csv+= ",";
            }
            csv+=value.toString();
        }
        context.write(key, new Text(csv));
    }
}

public static void main(String[] args) throws Exception {
    Configuration conf =  new  Configuration();
    String [] otherArgs = new GenericOptionsParser(conf,args).getRemainingArgs();
    if(otherArgs.length<2){
        System.out.println("Usage Retail Data ");
        System.exit(2);
    }
    Job job= new Job(conf,"Retail Data Analysis");
    job.setJarByClass(RetailDataAnalysis.class);
    job.setMapperClass(RetailDataAnalysisMapper.class);
    job.setCombinerClass(RetailDataAnalysisReducer.class);
    job.setReducerClass(RetailDataAnalysisReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);

    for(int i=0;i<otherArgs.length-1;++i){
        FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
    }
    FileOutputFormat.setOutputPath(job, new Path(otherArgs[otherArgs.length-1]));
    System.exit(job.waitForCompletion(true)?0:1);
  }
}

And the exception i am getting is when using LongWritable Key,
   18/04/11 09:15:40 INFO mapreduce.Job: Task Id : attempt_1523355254827_0008_m_000000_2, Status : FAILED
  Error: java.io.IOException: Type mismatch in key from map: expected org.apache.hadoop.io.Text, received org.apache.hadoop.io.LongWritable
at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.collect(MapTask.java:1069)

Exception i am getting when trying to use Text key
   Error: java.io.IOException: Type mismatch in key from map: expected org.apache.hadoop.io.Text, received org.apache.hadoop.io.LongWritable
at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.collect(MapTask.java:1069)
at org.apache.hadoop.mapred.MapTask$NewOutputCollector.write(MapTask.java:712)
at org.apache.hadoop.mapreduce.task.TaskInputOutputContextImpl.write(TaskInputOutputContextImpl.java:89)
at org.apache.hadoop.mapreduce.lib.map.WrappedMapper$Context.write(WrappedMapper.java:112)
at org.apache.hadoop.mapreduce.Mapper.map(Mapper.java:124)

Please help me to solve this,i am very new to hadoop.

A: You may need different input format class. By default used is TextInputFormat which split the file line by line and gives line number as LongWritable and the line as Text.
You can specify the input format class this way:
job.setInputFormatClass(TextInputFormat.class);

In your case, if you do not need the key, just the values, you can use LongWritable as key:
public static class RetailDataAnalysisMapper extends Mapper<LongWritable, Text, Text, Text> {
    public void map(LongWritable key, Text Value, Context context) throws IOException, InterruptedException {
        //...
    }
}

Edit:
Here is whole code after modyfing to use LongWritable as key:
public class RetailDataAnalysis {

    public static class RetailDataAnalysisMapper extends Mapper<LongWritable, Text, Text, Text> {

        public void map(LongWritable key, Text Value, Context context) throws IOException, InterruptedException {
            String analyser[] = Value.toString().split(",");
            Text productCategory = new Text(analyser[3]);
            Text salesPrice = new Text(analyser[4]);
            context.write(productCategory, salesPrice);
        }
    }

    public static class RetailDataAnalysisReducer extends Reducer<Text, Text, Text, Text> {

        protected void reduce(Text key, Iterable<Text> values, Context context)
                throws IOException, InterruptedException {
            String csv = "";
            for (Text value : values) {
                if (csv.length() > 0) {
                    csv += ",";
                }
                csv += value.toString();
            }
            context.write(key, new Text(csv));
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        if (otherArgs.length < 2) {
            System.out.println("Usage Retail Data ");
            System.exit(2);
        }
        Job job = new Job(conf, "Retail Data Analysis");
        job.setJarByClass(RetailDataAnalysis.class);
        job.setMapperClass(RetailDataAnalysisMapper.class);
        job.setCombinerClass(RetailDataAnalysisReducer.class);
        job.setReducerClass(RetailDataAnalysisReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        for (int i = 0; i < otherArgs.length - 1; ++i) {
            FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
        }
        FileOutputFormat.setOutputPath(job, new Path(otherArgs[otherArgs.length - 1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}

Also if you are splitting the data by ,, your data should be a csv, like this:
2012-01-01 09:20,Fort Worth,Women's Clothing,153.57,Visa
2012-01-01 09:00,San Jose,Mens Clothing,214.05,Rupee
2012-01-01 09:00,San Diego,Music,76.43,Amex
2012-01-01 09:00,New York,Cameras,5.76,Visa

Not space separated as you specified it in your question.

A: When you read a file using Map Reduce, the file input format ( the default one ) reads an entire line and sends it to the mapper in the format of  , so the input to the mapper becomes :-
public static class RetailDataAnalysisMapper extends Mapper<LongWritable,Text,Text,Text>

In case you need to read as
public static class RetailDataAnalysisMapper extends Mapper<Text,Text,Text,Text>

you would need to change the file input format and use your custom file input format  along with the custom record reader.
Then you need to add the following line in the driver code.
job.setInputFormatClass("your custom input format".class);

Hadoop understands everything in the form of
so when you read a file, the offset becomes the LongWritable key and the value read becomes the value.
So you need to use the default signature of Mapper<LongWritable,Text, <anything>,<anything> >


text:
Q: Tic Tac Toe game app doesn`t work I want to make simple Tic Tac Toe.
Now I have this code.
Here I just click one button and it becoming X, and when I have 3 X in a line there comes a Toast displaying "Game over".
I haven't set Os yet.
public class MainActivity extends AppCompatActivity {
ImageButton[] imageButton = new ImageButton[8];
boolean[] isIt = new boolean[8];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageButton [0] = (ImageButton) findViewById(R.id.imageButton7) ;
    imageButton [1] = (ImageButton) findViewById(R.id.imageButton2) ;
    imageButton [2] = (ImageButton) findViewById(R.id.imageButton3) ;
    imageButton [3] = (ImageButton) findViewById(R.id.imageButton4) ;
    imageButton [4] = (ImageButton) findViewById(R.id.imageButton5) ;
    imageButton [5] = (ImageButton) findViewById(R.id.imageButton6) ;
    imageButton [6] = (ImageButton) findViewById(R.id.imageButton10) ;
    imageButton [7] = (ImageButton) findViewById(R.id.imageButton8) ;
    imageButton [8] = (ImageButton) findViewById(R.id.imageButton9) ;
    imageButton[0].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gunwo(0);
            checkIt();
        }
    });
    imageButton[1].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gunwo(1);
            checkIt();
        }
    });
    imageButton[2].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gunwo(2);
            checkIt();
        }
    });
    imageButton[3].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gunwo(3);
            checkIt();
        }
    });
    imageButton[4].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gunwo(4);
            checkIt();
        }
    });
    imageButton[5].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gunwo(5);
            checkIt();
        }
    });
    imageButton[6].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gunwo(6);
            checkIt();
        }
    });
    imageButton[7].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gunwo(7);
            checkIt();
        }
    });
    imageButton[8].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gunwo(8);
            checkIt();
        }
    });
}
public void gunwo(int y)
{
    if(!isIt[y])
    {
        isIt[y] = true;
        imageButton[y].setImageResource(R.drawable.trasfasd);
    }
}

public void checkIt()
{
    if (isIt[0] && isIt[1]&&isIt[2]){
        Toast.makeText(getApplicationContext(), "Game Over", Toast.LENGTH_LONG).show();
    }
    else if(isIt[3]&&isIt[4]&&isIt[5])
    {
        Toast.makeText(getApplicationContext(), "Game Over", Toast.LENGTH_LONG).show();
    }
    else if(isIt[6]&&isIt[7]&&isIt[8])
    {
        Toast.makeText(getApplicationContext(), "Game Over", Toast.LENGTH_LONG).show();
    }
    else if(isIt[0]&&isIt[3]&&isIt[6])
    {
        Toast.makeText(getApplicationContext(), "Game Over", Toast.LENGTH_LONG).show();
    }
    else if(isIt[1]&&isIt[4]&&isIt[7])
    {
        Toast.makeText(getApplicationContext(), "Game Over", Toast.LENGTH_LONG).show();
    }
    else if(isIt[2]&&isIt[5]&&isIt[8])
    {
        Toast.makeText(getApplicationContext(), "Game Over", Toast.LENGTH_LONG).show();
    }
    else if(isIt[6]&&isIt[4]&&isIt[2])
    {
        Toast.makeText(getApplicationContext(), "Game Over", Toast.LENGTH_LONG).show();
    }
    else if(isIt[0]&&isIt[4]&&isIt[8])
    {
        Toast.makeText(getApplicationContext(), "Game Over", Toast.LENGTH_LONG).show();
    }
}
}

Compiler does not find any bug, but when i open the app in emulator app doesn`t work.
Here is my LogCat:
09-24 14:56:27.899 2781-2781/com.holland.tictactoe E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: com.holland.tictactoe, PID: 2781
                                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.holland.tictactoe/com.holland.tictactoe.MainActivity}: java.lang.ArrayIndexOutOfBoundsException: length=8; index=8
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                     at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:154)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                  Caused by: java.lang.ArrayIndexOutOfBoundsException: length=8; index=8
                                                                     at com.holland.tictactoe.MainActivity.onCreate(MainActivity.java:28)
                                                                     at android.app.Activity.performCreate(Activity.java:6679)
                                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                     at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:154)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

.

A: Once you learn to read the logcat, you'll see
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=8; index=8
     at com.holland.tictactoe.MainActivity.onCreate(MainActivity.java:28)

It tells you all the information needed, really
Since arrays are zero indexed imageButton [8] is the ninth element of the array.
You only initialized with 8
ImageButton[] imageButton = new ImageButton[8];
boolean[] isIt = new boolean[8];

It's hard to create a 3x3 board with 8 pieces
Change those to [9], and you really should use a loop here
for (int i = 0; i < imageButton.length; i++) {
    final int position = i;
    imageButton[i].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gunwo(position);
            checkIt();
        }
    });
}


text:
Q: FirebaseRTC login fails I am trying to learn video conferencing app for which I am developing webRTC app using following link.
https://webrtc.org/getting-started/firebase-rtc-codelab
But I get stuck at the step 4. Install the Firebase Command Line Interface, for firebase login. It shows me error as follows in browser.

Oops!
  Firebase CLI Login Failed The Firebase CLI login request was
  rejected or an error occurred. Please run firebase login again or
  contact support if you continue to have difficulty logging in.

It generates authentication code also, but I paste it and then shows following error in terminal.

Error: Authentication Error: Your credentials are no longer valid.
  Please run firebase login --reauth
For CI servers and headless environments, generate a new token with
  firebase login:ci

Tried all the solutions, but no luck. FYI - I login with my google account.
firebase login --reauth, gives same error after pasting the authentication code.
firebase login:ci, gives same error after login with google account.
Can anyone help into this?

A: try
firebase logout forebase login


text:
Q: Random forest: balancing test set? I am trying to run a Random Forest Classifier on an imbalanced dataset (~1:4).
I am using the method from imblearn as follows:
from imblearn.ensemble import BalancedRandomForestClassifier

rf=BalancedRandomForestClassifier(n_estimators=1000,random_state=42,class_weight='balanced',sampling_strategy='not minority')
rf.fit(train_features,train_labels)
predictions=rf.predict(test_features)

The split in training and test set is performed within a cross-validation approach using RepeatedStratifiedKFold from scikit learn.
However, I wonder if the test set needs to be balanced as well in order to obtain sensible accuracy scores (sensitivity, specificity etc.). I hope you can help me with this.
Many thanks!

A: From the imblearn docs:

A balanced random forest randomly under-samples each bootstrap sample
  to balance it.

If you are okay with random undersampling as your balancing method, then the classifier is doing that for you "under the hood". In fact, that's the point of using imblearn in the first place, to handle class imbalance. If you were using a straight random forest, like the out-of-the-box version from sklearn, then I would be more concerned about dealing with class imbalance on the front end.


text:
Q: Java convert Spring Data Sort to Comparator I built a Spring Boot application that uses the Spring Data Sort class to sort the entities in my database.
However, for reasons of consistency, I'd also like to apply that sort mechanism to general lists or streams and therefore need to convert it to a Comparator.
I came up with a solution but I feel like there is a more elegant and/or type-safe way of doing it. Any advice?
import org.springframework.data.domain.Sort;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Comparator;
import java.util.Iterator;

public class ComparatorUtils {
    public static <T> Comparator<T> convert(Sort sort, Class<T> type) {
        final Iterator<Sort.Order> orderIterator = sort.iterator();
        final Sort.Order order = orderIterator.next();

        Comparator<T> comparator = convert(order, type);
        while (orderIterator.hasNext()) {
            comparator = comparator.thenComparing(convert(orderIterator.next(), type));
        }

        return comparator;
    }

    private static <T> Comparator<T> convert(Sort.Order order, Class<T> type) {
        Comparator<T> comparator = Comparator.comparing((T entity) -> {
            try {
                return (Comparable) new PropertyDescriptor(order.getProperty(), type).getReadMethod().invoke(entity);
            } catch (IllegalAccessException | InvocationTargetException | IntrospectionException e) {
                throw new RuntimeException(e);
            }
        });

        if (order.isDescending())
            return comparator.reversed();
        return comparator;
    }
}

A: *

*Use org.springframework.beans.BeanUtils.getPropertyDescriptor where the descriptors are cached (instead of new PropertyDescriptor).

*This solution doesn't handle sorting by deeper fields (eg. Person.Address.Street)

*Null values aren't correctly handled. Use Comparator.nullsFirst or nullsLast.


text:
Q: Django diferencia entre post mediante framework y curl como están?
Estoy haciendo una rest API muy sencilla. Para guardar algunos registros en una base de datos sqllite y sacar algunos parámetros.
Mi idea principal es que pueda almacenar información al enviar un post con un json. La información va a venir de la siguiente forma: {"data": [1, -2, 3.2, 7]}, por cada valor de la lista, tengo que generar un nuevo registro en mi DB.
Mi código por el momento es bastante sencillo... claramente luego voy a procesar la lista y almacenar los registros correspondientes.. por ahora se ve asi:
@api_view(['POST'])
def addRegister(request):

    print("Recibi ==> " , type(request), " ==> " , dict(request.data))

    rta = {"Response":"Guardado"}
    return Response(rta)

Mi gran duda surge de que cuando utilizo la opción que da django para realizar el post (ingreso al endpoint , selecciono la opción post y coloco MediaType= "application/json") y llenando el contenido con el diccionario de prueba : {"data": [1, -2, 3.2, 7]} todo va bien.
Recibi ==>  <class 'rest_framework.request.Request'>  ==>  {'data': [1, -2, 3.2, 7]}
[16/Feb/2022 14:44:57] "POST /add/ HTTP/1.1" 200 5631

Ahora cuando quiero utilizar curl pareciera no funcionar... estoy usando el siguiente comando (que entiendo es equivalente):
curl -X POST http://localhost:8000/add/ -H 'Content-Type:
application/json' -d '{"data": [1, -2, 3.2, 7]}'

Cuando envio este post.. retorna al cliente HTTP/1.1 200.. pero en la consola no me recibe los datos e imprime un error:
Recibi ==>  <class 'rest_framework.request.Request'>  ==>  {}
[16/Feb/2022 14:53:46] "POST /add/ HTTP/1.1" 200 23
[16/Feb/2022 14:53:46] code 400, message Bad request version ('7]}')
[16/Feb/2022 14:53:46] "{"data": [1, -2, 3.2, 7]}" 400 -

Sospecho que quizás este armando mal el curl, pero según vi en internet la data se coloca de esa forma. Que puede ser? Me falta algo en el código?
Desde ya muchas gracias a todos!

A: Lo probé de esta manera y me funciono bien
curl -X POST http://localhost:8000/add/ -d '{"data": [1, -2, 3.2, 7]}' -H "Content-Type: application/json"

Te recomiendo la aplicación Postman para que puedas probar tus endpoints.


text:
Q: queryMultiple columns in one single row mysql select employee,
log_type,
DATE_FORMAT(time,"%Y-%m-%d") as "attendance_date",
case when log_type = 'IN' then TIME_FORMAT(ch.time,"%H:%i:%s") end as check_in ,
case when log_type = 'OUT' then TIME_FORMAT(ch.time,"%H:%i:%s") end as check_out
from Employee_checkin ch
where DATE_FORMAT(time,"%Y-%m-%d") = '2023-02-14'

my result is :
HR-EMP-00001    IN  2023-02-14      09:24:24
HR-EMP-00001    OUT 2023-02-14      15:24:40


text:
Q: javascript one function triggering is triggering another unintended function In form validation, on blur, a data validation gets triggered. IN this form, I have 3 different onblur possible triggers. But if one triggers, I get two alert boxes, which means, two funcitons were triggered.
The form (html code):
<form id="processpayment" action="https://www.paypal.com/cgi-bin/webscr" method="post">

Nombre

<input id="nombre" class="requerido" type="text" name="nombre" value="" />

Forma de comunicación

Skype

Usuario de Skype

<input id="medio_id" class="requerido" type="text" name="medio_id" value="" />

Verifica usuario de Skype

<input id="confirm:medio_id" class="requerido" onblur="confirm_data(this.id);" type="text" name="confirm:medio_id" value="" />

<input id="warningpaypalverified" class="requerido" type="checkbox" name="warningpaypalverified" value="payment constraints acknowledged" />Pagos de tarjeta de crédito son procesados inmediatamente.

 En caso de que use su cuenta PayPal, es necesario ser verificado por PayPal con anterioridad.
Por que es esto necesario

<input type="hidden" name="notify_url" value="http://root.com/process/listener.php" /> <input type="hidden" name="locale.x" value="es_XC" /> <input class="alldata" type="hidden" name="custom" value="" /> <input type="hidden" name="cmd" value="_s-xclick" /> <input type="hidden" name="image_url" value="http://root.com/images/root_logo.png" /> <input type="hidden" name="hosted_button_id" value="THISANDTHAT" /> <input class="paypal" type="image" name="submit" src="https://www.paymentobjects.com/es_XC/i/btn/btn_buynowCC_LG.gif" alt="PayPal, la forma más segura y rápida de pagar en línea." />

</form>

I have following javascript code:
function clear_fields(fieldid, confirm_fieldid){
        document.getElementById(fieldid).value = "";
        if (typeof(confirm_fieldid) !== 'undefined'){ document.getElementById(confirm_fieldid).value = ""; }
        document.getElementById(fieldid).focus();
        return false;
    }

function validate_email(email_field_id){

        email = typeof(email_field_id) != 'undefined' ? document.getElementById(email_field_id) : function(){alert('Parameter error when calling Validate Email. Check your form'); return;}();

        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if( reg.test(email.value) == false ) {

            alert('El email que ingresaste no es correcto. Por favor, intenta nuevamente siguiendo este formato tucorreo@ejemplo.com');

            return clear_fields(email_field_id);

        } else { return true; }

    }

function confirm_email( confirm_email_field_id ){

        var confirmemail = typeof(confirm_email_field_id) != 'undefined' ? document.getElementById(confirm_email_field_id) : function(){alert('Parameter error when calling javascript function confirm_email(). Check your form, and make sure input field for confirm email calls the function confirm_email("confirm:email_id");'); return;}();

        var confirmemailarray = confirmemail.id.split(':');

        var email = document.getElementById(confirmemailarray[1]);

        if( email.value === confirmemail.value ) {

            return true;

        } else {

            alert("ERROR: \"Email\" no coincide con \"Confirmar Email\". \n Agrega tu \"Email\" y CONFIRMA este Email")

            return clear_fields(email.id, confirmemail.id);

        }

    }

function confirm_data(confirm_data_field_id){

        if( typeof(confirm_data_field_id) == 'undefined'){

            alert('Parameter error when calling javascript function confirm_data. Check your form, and make sure input field to confirm data calls the function confirm_data("confirm:data_field_id");');

            return;

        } else {

            var confirmidarray = confirm_data_field_id.split(':');

            thedata = document.getElementById(confirmidarray[1]);

            confirmthedata = document.getElementById(confirm_data_field_id);

            if( thedata.value == confirmthedata.value ) return true;
            else {

                thedatalabel = document.getElementById('label_' + thedata.id);
                confirmthedatalabel = document.getElementById('confirm:label_' + thedata.id);

                alert('ERROR: Los datos que ha ingresado en los campos de informacion \n\n' + thedatalabel.innerHTML + '\n' + confirmthedatalabel.innerHTML + '\n\n NO COINCIDEN. \n\n Para proceder con su pago agregue la informacion correcta.' );

                return clear_fields( confirmidarray[1], confirmidarray[0] + ':' + confirmidarray[1] );

            }

        }

    }

Why is this happening?
What changes do I need to do?
Thank you

A: In some browsers, an alert() can trigger focus events (because focus goes to the alert box and then back to the page afterwards).  When debugging this kind of issue, it's better to use console.log() which doesn't mess with focus to record what's going on and you can then just look at the log to see what really happened without having changed the behavior.


text:
Q: Performance of calling a method using reflection What is the performance difference of calling a method using reflection vs. calling the method directly?
Context details:
I have a class, with some string properties and for certain properties I have to set the values to Lower case or to Upper case (and a bit of logic related to that).
I have two options:

*

*either copy/paste the code for the 14 properties.

*or annotate those 14 methods and using reflection find them and call them (also using reflection).

Of course with option 2. my code would much more readable and easy to maintain, but the question is about performance. I will have some millions (around 2-3) of instances and I would go with the reflection option, if the performance impact is not bigger than 20 seconds.
Does anyone here have any experience with that?

A: It's difficult to give a set figure because it will depend on many aspects of your system, so I wrote a class to check this.
The results surprised me, it seems for my system that for simply calling a method via reflection vs statically calling the method, static calling is between 10,000 for a non empty method and 1000,000 times faster for an empty method.
I used both just in case the java compiler/vm was optimising away an empty method call.
The code is below, also available in this gist - https://gist.github.com/piersy/23b4814eec806b584266
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestReflection {

    public static long INC = 0;

    public static final int COUNT = 100000000;

    private static class Dummy {
        public void doSomething(String s1, String s2, String s3) {
            INC++;
        }
    }

    public static void main(String[] args) throws NoSuchMethodException {

        Dummy obj = new Dummy();
        Method method = obj.getClass().getMethod("doSomething", String.class, String.class, String.class);

        String s1 = "string1";
        String s2 = "string2";
        String s3 = "string3";

        //warmup
        runReflection(obj, method, s1, s2, s3, COUNT / 10);
        runStatic(obj, s1, s2, s3, COUNT/10);

        ///realtest

        long reftime = System.nanoTime();
        runReflection(obj, method, s1, s2, s3, COUNT);
        reftime = System.nanoTime() - reftime;

        long time = System.nanoTime();
        runStatic(obj, s1, s2, s3, COUNT);
        time = System.nanoTime() - time;

        System.out.println(reftime);
        System.out.println(time);

        //1000 *1000 *1000 nanoseconds in a second
        System.out.println(reftime / (1000 *1000 *1000));
        System.out.println(time / (1000 *1000 *1000));
        System.out.println((double)reftime/ (double)time );

        System.out.println("percentage speed decrease from using reflection:"+(((double)reftime/(double)time)-1)*100);

    }

    private static void runReflection(Dummy obj, Method method, String s1, String s2, String s3, int count) {
        for (int i = 0; i < count; i++) {
            try {
                method.invoke(obj, s1, s2, s3);
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
        }
    }

    private static void runStatic(Dummy obj, String s1, String s2, String s3, int count) {
        for (int i = 0; i < count; i++) {
            obj.doSomething(s1,s2,s3);
        }
    }

}

A: In general, yes, reflection is slower.  If by millions of instances you mean millions of calls then yes, in some cases you could incur more than a 20 second overhead.  In some causes you may not incur the additional overhead as the compiler will be able to optimize it out.  You will either have to give a lot more details about how exactly you plan on using reflection or run it yourself.  My GUT says that across 3 million calls you will NOT incur more than 20 seconds overhead however that is very much a gut feeling.

A: Lets start with some drawbacks of Reflection from the Oracle Docs

Drawbacks of Reflection
Reflection is powerful, but should not be used indiscriminately. If it
is possible to perform an operation without using reflection, then it
is preferable to avoid using it. The following concerns should be kept
in mind when accessing code via reflection.
Performance Overhead Because reflection involves types that are
dynamically resolved, certain Java virtual machine optimizations can
not be performed. Consequently, reflective operations have slower
performance than their non-reflective counterparts, and should be
avoided in sections of code which are called frequently in
performance-sensitive applications.
Security Restrictions
Reflection requires a runtime permission which may not be present when running
under a security manager. This is in an important consideration for
code which has to run in a restricted security context, such as in an
Applet.
Exposure of Internals
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as
accessing private fields and methods, the use of reflection can result
in unexpected side-effects, which may render code dysfunctional and
may destroy portability. Reflective code breaks abstractions and
therefore may change behavior with upgrades of the platform.

So you can take it for sure that performance would be an issue once you start scaling up.
But if you can live with the performance overhead which an intuition says should not be more than 20 seconds for Uppercase/LowerCase operations and being hugely scalable is not a concern  you can use it. But beware that intuitions on performance are usually always wrong. So you would want to test for sure.
Do look up Aspect Oriented Programming for the task you want.
My opinion: Use a AOP framework.


text:
Q: Django custom list view in admin One of the objects I am managing in my django site will only ever have one instance in the database.  I therefore want to change the list view to simply redirect to the 'edit' page for this first object.
So basically when you hit /admin/my_site/widgets I want to redirect to /admin/my_site/widget/1.  I have tried a custom view, a custom template, etc, but I can't find an easy way of doing this (or any way of doing this for that matter).
It's almost like I want to do something like this (doesn't work because I can't figure out how to change the list view):
class WidgetAdmin(admin.ModelAdmin):
    def list_view(self, request):
        widget = Widget.objects.all()[0]
        return HttpResponseRedirect('/admin/my_site/widget/%s' % widget.id)

I've also tried change the url's to match the list request and do a redirect there, but I can't seem to match the list request with anything other than a complete blanket regex, i.e. (r/^.*$/) which means I just get an infinite loop redirect.

A: I needed the same thing. I solved it slighty different using the changelist_view from ModelAdmin. Using your example it would look somthing like:
class MySingleEditAdmin(admin.ModelAdmin):
   def changelist_view(self, request, extra_context=None):
       object, created = self.get_my_object()
       url = reverse('admin:%s_%s_change' %(object._meta.app_label, object._meta.module_name),  args=[object.id] )
       return HttpResponseRedirect(url)

class WidgetAdminAdmin(MySingleEditAdmin):
   def get_my_object(self):
       return Widget.objects.get_or_create(pk=1, ...default_data...)

A: Ok this is how I sorted it out.
class WidgetAdmin(admin.ModelAdmin):
    def list_view(self, request):
        widget = Widget.objects.all()[0]
        return HttpResponseRedirect('/admin/my_site/widget/%s' % widget.id)

    def get_urls(self):
        from django.conf.urls.defaults import *
        urls = super(WidgetAdmin, self).get_urls()
        my_urls = patterns('',
                    (r'^$', admin.site.admin_view(self.list_view))
                )
        return my_urls + urls


text:
Q: C# inherit properties from a field A useful feature of C# is using static <ClassName> to for example use Math functions without prefixing them with Math.Function, but just Function. Is something similar possible as a shorthand for myField.anotherField as just anotherField?
This is of course possible by just AnotherField /*actually a property now*/ { get => myField.anotherField; set => myField.anotherField = value; } ( which adds maintenance cost ), or just extending a class.
My use case for this is that an abstract class State knows of an Entity that it is attached to ( it can't and shouldn't extend Entity ). The classes that extend State use the readonly entity field to communicate with the entity, but they act as the entity itself so I think it would be handy not to have to write "entity" each time I want to access its fields. Is this at all possible or do I have to just maintain a bunch of properties that redirect to the correct fields?


text:
Q: How to give Tkinter file dialog focus I'm using OS X.  I'm double clicking my script to run it from Finder.  This script imports and runs the function below.
I'd like the script to present a Tkinter open file dialog and return a list of files selected.
Here's what I have so far:
def open_files(starting_dir):
    """Returns list of filenames+paths given starting dir"""
    import Tkinter
    import tkFileDialog

    root = Tkinter.Tk()
    root.withdraw()  # Hide root window
    filenames = tkFileDialog.askopenfilenames(parent=root,initialdir=starting_dir)
    return list(filenames)

I double click the script, terminal opens, the Tkinter file dialog opens.  The problem is that the file dialog is behind the terminal.
Is there a way to suppress the terminal or ensure the file dialog ends up on top?
Thanks,
Wes

A: Use AppleEvents to give focus to Python. Eg:
import os

    os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')

A: I had this issue with the window behind Spyder:
root = tk.Tk()
root.overrideredirect(True)
root.geometry('0x0+0+0')
root.focus_force()
FT = [("%s files" % ftype, "*.%s" % ftype), ('All Files', '*.*')]
ttl = 'Select File'
File = filedialog.askopenfilename(parent=root, title=ttl, filetypes=FT)
root.withdraw()

A: For anybody that ends up here via Google (like I did), here is a hack I've devised that works in both Windows and Ubuntu. In my case, I actually still need the terminal, but just want the dialog to be on top when displayed.
# Make a top-level instance and hide since it is ugly and big.
root = Tkinter.Tk()
root.withdraw()

# Make it almost invisible - no decorations, 0 size, top left corner.
root.overrideredirect(True)
root.geometry('0x0+0+0')

# Show window again and lift it to top so it can get focus,
# otherwise dialogs will end up behind the terminal.
root.deiconify()
root.lift()
root.focus_force()

filenames = tkFileDialog.askopenfilenames(parent=root) # Or some other dialog

# Get rid of the top-level instance once to make it actually invisible.
root.destroy()

A: filenames = tkFileDialog.askopenfilenames(parent=root,initialdir=starting_dir)
Well parent=root is enough for making tkFileDialog on top. It simply means that your root is not on top, try making root on top and automatically tkFileDialog will take top of the parent.

A: None of the other answers above worked for me 100% of the time.
In the end, what worked for me was adding 2 attibutes: -alpha and -topmost
This will force the window to be always on top, which was what I wanted.
import tkinter as tk

root = tk.Tk()
# Hide the window
root.attributes('-alpha', 0.0)
# Always have it on top
root.attributes('-topmost', True)
file_name = tk.filedialog.askopenfilename(  parent=root,
                                            title='Open file',
                                            initialdir=starting_dir,
                                            filetypes=[("text files", "*.txt")])
# Destroy the window when the file dialog is finished
root.destroy()

A: Try the focus_set method.  For more, see the Dialog Windows page in PythonWare's An Introduction to Tkinter.


text:
Q: DFS share(s) not visible for some Citrix SBC users In short:
Some Citrix SBC servers are experiencing the following problem
When logged in to a Citrix server and browsing to a mapped drive (eg. drive D: (mapped as \domain.local\namespace\share)) the drive apears empty. When logging off and re-logging to another Citrix server that is not experiencing this problem the drive is showing all content.
A couple of known facts:

*

*When someone is experiencing this issue, everyone on the same Citrix server is experiencing the same issue.

*When performing a DFS flush (dfsutil.exe cache referral flush) on this Citrix server, the issue seems to be solved for the day.

*Every day one or more Citrix servers seem to have this problem

*All Citrix servers are provisioned using Citrix PVS, so they should be identical

*When browsing to \domain.local\namespace\share the share is empty

*When browsing to \domain\namespace\share the share is oké

*when browsing to \server\share the share is oké

*When using CMD / Powershell the share LOOKS empty, but i can still get into the share by doing cd D:\share\subfolder . So it seems like its something cosmetic?

If i turn off ABE on DFS root level, the mapped drive D: will show alle available shares including the share this specific user has access to. Leaving ABE off is not an option though since we have a lot of shares that should not be visible to everyons.
Envoiremental details

*

*We have 19 fileservers. 16 fileservers are ROOT/Namespace servers

*All fileservers are Windows Server 2012R2 servers

*The DFS namespace is AD integrated

*The Citrix XenApp servers are all based on Windows Server 2008R2

*DFSDiag / DCDiag show no errors

*DFS structure:

\domain.local\Namespace
\domain.local\Namespace\Folder (no target)
\domain.local\Namespace\Folder\Shares (90 Shares. Each share has one target to a fileserver)

Some workarounds that did not seem to work

*

*kb/2769790

*Changing Register keys: NoRemoteRecursiveEvents, NoRemoteChangeNotify

*Changing reg keys: FileinfoCacheLifeTime, FileNotFoundCacheLifetime, DirectoryCacheLifetime
When did it start?
These problems started after deploying Microsoft patch MS17-010 (WannaCry) on the fileservers and rebooting the fileservers.


text:
Q: FCM, NodeJS - Alternative for subscribing to multiple topics Users may have multiple devices. And they may subscribe to multiple channels. Each channel is a topic (from FCM's perspective).
When the use signs in from a new device, the device has to be subscribed to all the channels (could be hundreds). Making potentially hundreds of API calls sounds like a bad idea.
Also, it seems subscribing a device group to a topic is not possible either.
Is there any alternative (and cheaper) way to subscribe a client device to multiple topics?

A: There is currently no other alternative to subscribe a client to a topic otber than the usual client side subscription(subscribeToTopic()) and using the InstanceID API.
In your use case, it seems that somehow, the topics are private for some reason. In general, topics should only be used for messages that could be received publicly.
One way I could think of simply maintaining the groups on your own server, and removing and adding the corresponding token when needed. Although this may still be heavy depending on how many groups you'll add/remove the token from.


text:
Q: Sending Email to different recipients with different file attachments using python Hi I'm new to learning python and I'm trying to send emails to a few hundred different recipients with a different attachment to each of them. I have the recipients data in a database and a folder with all the files in it.
Database has supplier id, name and email
Database example
The folder structure is just one folder with all the files in it for example :
Folder screenshot
Supplier files folder --
123.xls
123.pdf
456.xls
789.pdf
any direction on how to get started with this is appreciated. Thank you

A: In this example I will use an answer that I gave to another question (How do I attach separate PDF's to contact list email addresses using Python?) , I use a csv file that contains the addresses and the file path that corresponds to it like img bellow :
users.csv :

folder with csv files :

And this is the code:
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from string import Template
import pandas as pd

# read the file containing the database with the mail and the corresponding file
e = pd.read_csv("users.csv")
# In this example we will use gmail
context = ssl.create_default_context()
server = smtplib.SMTP_SSL('smtp.gmail.com', 465,context=context)
server.login('mymail@gmail.com','mypass')

body = ("""
Hi there

Test message

Thankyou
""")
subject = "Send emails with attachment"
fromaddr='mymail@gmail.com'

for index, row in e.iterrows():
    print (row["Emails"]+row["csv"])
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))
    filename = row["csv"]
    toaddr = row["Emails"]
    attachment = open(row["csv"], "rb")
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
    msg.attach(part)
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)

print("Emails sent successfully")

server.quit()

if you use a gmail account, check that you have it permissions to send emails from other types of clients (https://support.google.com/accounts/answer/6010255)


text:
Q: postgres gem failing to install mac osx sierra This one i cant figure out im running osx sierra but was fine for a while and then all of a sudden when i tried to do a bundle update
ive tried everything i have google and completly reinstalled homebrew and postgres but nothing, any help is very appreciated
i think something that may be wrong is setting the location of postgres
   Using config values from /usr/pgsql-9.5.4/bin/pg_config
    sh: /usr/pgsql-9.5.4/bin/pg_config: No such file or directory
    sh: /usr/pgsql-9.5.4/bin/pg_config: No such file or directory

i changed something here but dont know what i did and no idea how to get it back
    Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory:
    /Users/raycove/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/pg-0.19.0/ext
    /Users/raycove/.rbenv/versions/2.3.1/bin/ruby -r
    ./siteconf20160930-43553-1i5ubpk.rb extconf.rb
    --with-pg-config=/usr/pgsql-9.5.4/bin/pg_config
    Using config values from /usr/pgsql-9.5.4/bin/pg_config
    sh: /usr/pgsql-9.5.4/bin/pg_config: No such file or directory
    sh: /usr/pgsql-9.5.4/bin/pg_config: No such file or directory
    checking for libpq-fe.h... yes
    checking for libpq/libpq-fs.h... yes
    checking for pg_config_manual.h... yes
    checking for PQconnectdb() in -lpq... yes
    checking for PQconnectionUsedPassword()... yes
    checking for PQisthreadsafe()... yes
    checking for PQprepare()... yes
    checking for PQexecParams()... yes
    checking for PQescapeString()... yes
    checking for PQescapeStringConn()... yes
    checking for PQescapeLiteral()... yes
    checking for PQescapeIdentifier()... yes
    checking for PQgetCancel()... yes
    checking for lo_create()... yes
    checking for pg_encoding_to_char()... yes
    checking for pg_char_to_encoding()... yes
    checking for PQsetClientEncoding()... yes
    checking for PQlibVersion()... yes
    checking for PQping()... yes
    checking for PQsetSingleRowMode()... yes
    checking for PQconninfo()... yes
    checking for PQsslAttribute()... yes
    checking for rb_encdb_alias()... yes
    checking for rb_enc_alias()... yes
    checking for rb_thread_call_without_gvl()... yes
    checking for rb_thread_call_with_gvl()... yes
    checking for rb_thread_fd_select()... yes
    checking for rb_w32_wrap_io_handle()... no
    checking for rb_str_modify_expand()... yes
    checking for rb_hash_dup()... yes
    checking for PGRES_COPY_BOTH in libpq-fe.h... yes
    checking for PGRES_SINGLE_TUPLE in libpq-fe.h... yes
    checking for PG_DIAG_TABLE_NAME in libpq-fe.h... yes
    checking for struct pgNotify.extra in libpq-fe.h... yes
    checking for unistd.h... yes
    checking for inttypes.h... yes
    checking for ruby/st.h... yes
    checking for C99 variable length arrays... yes
    creating extconf.h
    creating Makefile

    To see why this extension failed to compile, please check the mkmf.log which can
    be found here:

    /Users/raycove/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-16/2.3.0-static/pg-0.19.0/mkmf.log

    current directory:
    /Users/raycove/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/pg-0.19.0/ext
    make "DESTDIR=" clean

    current directory:
    /Users/raycove/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/pg-0.19.0/ext
    make "DESTDIR="
    compiling gvl_wrappers.c
    compiling pg.c
    compiling pg_binary_decoder.c
    compiling pg_binary_encoder.c
    compiling pg_coder.c
    compiling pg_connection.c
    compiling pg_copy_coder.c
    compiling pg_errors.c
    compiling pg_result.c
    compiling pg_text_decoder.c
    compiling pg_text_encoder.c
    compiling pg_type_map.c
    compiling pg_type_map_all_strings.c
    compiling pg_type_map_by_class.c
    compiling pg_type_map_by_column.c
    compiling pg_type_map_by_mri_type.c
    compiling pg_type_map_by_oid.c
    compiling pg_type_map_in_ruby.c
    compiling util.c
    linking shared-object pg_ext.bundle
    ld: file not found: dynamic_lookup
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    make: *** [pg_ext.bundle] Error 1

    make failed, exit code 2

    Gem files will remain installed in
    /Users/raycove/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/pg-0.19.0 for
    inspection.
    Results logged to
    /Users/raycove/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-16/2.3.0-static/pg-0.19.0/gem_make.out

    An error occurred while installing pg (0.19.0), and Bundler cannot
    continue.
    Make sure that `gem install pg -v '0.19.0'` succeeds before bundling.


text:
Q: ng repeat alter with media queries and screen size I have a JSon file that is meant to resemble that of a Youtube collection of info.
As such there are several img urls of varying sizes.
I'm currently listing the images in my html using an ng-repeat and directing to a specific image size.
What would be the recommended method to alter the path of this ng-repeat depending upon the screen size (media queries)

[[video.snippet.title| removeBrackets]]

but i would like it to display [[video.snippet.thumbnails.default.url]] when the screen is at a specific size. I understand I'll probably need to make a filter or a function. I'm far too new to angular and javascript to understand the best practice.
Any guidance is greatly appreciated :)


text:
Q: How to change width of div? Okay, I'm making a greasemonkey script and I'm trying to shrink the right column in facebook that has the ads on down to 1px so i can stretch the relevant content in the middle, but everything I try doesn't work!
I tried this and I didn't work:
document.getElementById('rightCol').style.width = '1px';

This is the CSS that tells the sidebar to be 244px's
#rightCol{margin-top:-10000px;float:right;padding-right:0;width:244px;word-wrap:break-word}

Any help would be greatly appreciated!

A: This will work.
window.addEventListener ("load", function() {
    document.getElementById('rightCol').style.display = 'none';
}, false);

worked for me.

A: You can try to hide the whole column:
document.getElementById('rightCol').style.display = "none"

A: Why don't you try jquery. Well I don't find any mistake in your code.
But try this.
$('#rightCol').attr('style','width: 10px;');

Or you may apply class on that particular column and select it by class selector like:
$('.rightColClass').attr('style','width: 10px;'); // It will apply width on all the element contains this class.


text:
Q: How to Stop a javascript refresh after a set time I have this code to refresh an image at a set interval:

The problem is, I need the images to refresh every 15 seconds, which works great.  But... I left the webpage open overnight, and today had 15GB of cache in firefox, and no free space on my c:\ drive. (There are about 20 pictures per page, all using this refreshing code.
So, is there a way to add to this code, and make it stop after a set time?  Like after 5 minutes maybe it would stop refreshing images?

A: Working and tested code. It will refresh your image only for 5 times.

Put this function inside your script tag.
var c = 0;

function fnSetTimer()
{
 //do whatever you want to do here.
 //document.getElementById('refreshimage1').src = 'http://somwhere/picture.jpg?\'' + new Date().getMilliseconds();
alert("testing");
var t = setTimeout(fnSetTimer,15000);
c=c+1;
if(c>5)
clearTimeout(t);
}

Might be this will help you.

A: Try it.
var c = 0;
function fnSetTimer()
{
alert("testing");
var t = setTimeout(fnSetTimer,15000);
c=c+1;
if(c>5)
clearTimeout(t);
}

A: Here is where I am at now.  Using the timer function, can't get the image to refresh.

The second img src code is the original code that refreshes the image, and still works.  Placed side by side, you can see the top image is static, and the bottom image continues to update every 5 seconds.  So the URL to the image is fine, just something is missing to make it refresh in the timer script?


text:
Q: PC boots on its own without any explicit request randomly so my desktop PC apparently sometimes just boots up without anyone being around to push the I/O button. This is kind of weirding me out, because I don't use anything which would wake up my device via Wake on Lan or something like this.
Ususally I have my PC unplugged after shutting it down to avoid stuff like this, but I thought I might just give it another try and now that it happened again, I want to check the root cause for this behaviour
I just checked my event viewers recorded System messages. There's one thing that might be interesting:
The last shutdown happened on 17th of April, 4:15:25 pm.
The first message of today, after the supposedly random boot, happened today, 18th of April, 4:15:56 pm. Given some time for the boot process, it seems like the two events are exactly 24 hours apart.
I also checked my WoL settings, apparently it was still turned on, so I disabled that, but I don't think this has to do with it necessarily.
That's all I could come up with for now, any solutions?
If there is data missing, I will happily provide it, I just don't know what might be missing.

A: Are there any Windows updates pending to install, and do you use hibernate (or shutdown without installing updates)?
I get this quite frequently on Windows 10, and I almost always use hibernate when I'm done with my PC. Turns out Windows is scheduling itself to power up so it can install updates while nobody is using the PC, but ultimately fails every time because my OS volume is Bitlocker protected. I'll just find my PC idle on the Bitlocker boot-time password prompt screen wasting electricity...
No power or GPO configuration I've come across stops this, even disabling wake timers. -- The only solution I've had yet is to use "Install updates and shutdown" to keep Windows happy.

A: I suspect a hardware fault. I too experienced such randomly auto reboots and it turned out to be a motherboard malfunctioning. You should check if it is a hardware malfunctioning.


text:
Q: iOS App transfer impact on Push notifications I am going to transfer one of my apps to another apple account. After reading some forums, what I have come to know is Push notifications will not work implicitly.

*

*Some forums say it will work, until the APNS certificate is not revoked/expired, the push notifications will continue to work. But since "App ID" is transferred to another account and APNS is associated with App ID only. It should not work then?

*If Push Notification will not work after the transfer, I am guessing I need the to create new APNS certificates and attach them to the "APP ID" in the new account and provide the same to the server team. In this case no new app submission would be required right?