text:
Q: Python logger: Prepending a string I have defined a logger as follows:
logger = logging.getLogger('APP')
syslog = logging.StreamHandler()
formatter = logging.Formatter('%(app_name)s : %(message)s')
app_name = {'app_name':'MULE'}
syslog.setFormatter(formatter)
logger.addHandler(syslog)
logger = logging.LoggerAdapter(logger, app_name)

I am trying to prepend a string to every logger message.
I have added this code based on this question and other similar questions. The problem is that now the logger is printing out 2 statements for every output that I want. The output is as  follows:
[03/Dec/2015 12:05:59] INFO views 91 1399960 [APP:1075] Picked
MULE : Picked

Why is this happening? Where am I going wrong?


text:
Q: Understanding SSE3 Matrix Multiplication Optimization With reference to http://blogs.msdn.com/b/xiangfan/archive/2009/04/28/optimize-your-code-matrix-multiplication.aspx.
template<>
void SeqMatrixMult4(int size, float** m1, float** m2, float** result)
{
    Transpose(size, m2);
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            __m128 c = _mm_setzero_ps();

            for (int k = 0; k < size; k += 4) {
                c = _mm_add_ps(c, _mm_mul_ps(_mm_load_ps(&m1[i][k]), _mm_load_ps(&m2[j][k])));
            }
            c = _mm_hadd_ps(c, c);
            c = _mm_hadd_ps(c, c);
            _mm_store_ss(&result[i][j], c);
        }
    }
    Transpose(size, m2);
}

Why is there 2 more _mm_hadd_ps(c, c) after the inner most for loop? To verify my understanding: this code loads 4 floats from m1 and another 4 from m2, then multiplies them resulting in 4 floats (__m128). Then I sum them into c (at this point, its still 4 floats?). Then after the for loop I hadd this result twice? What does that do?

My code slightly re-written produces the wrong result it appears
long long start, end;
__m128 v1, v2, vMul, vRes;
vRes = _mm_setzero_ps();

start = wall_clock_time();
transpose_matrix(m2);
for (int i = 0; i < SIZE; i++) {
    for (int j = 0; j < SIZE; j++) {
        float tmp = 0;
        for (int k = 0; k < SIZE; k+=4) {
            v1 = _mm_load_ps(&m1[i][k]);
            v2 = _mm_load_ps(&m2[j][k]);
            vMul = _mm_mul_ps(v1, v2);

            vRes = _mm_add_ps(vRes, vMul);
        }
        vRes = _mm_hadd_ps(vRes, vRes);
        _mm_store_ss(&result[i][j], vRes);
    }
}
end = wall_clock_time();
fprintf(stderr, "Optimized Matrix multiplication took %1.2f seconds\n", ((float)(end - start))/1000000000);

// reverse the transposition
transpose_matrix(m2);

A: haddps doesn't sum all four elements in a vector.  Two haddps instructions are needed to get the full horizontal sum.
If we number the elements of the vector {c0,c1,c2,c3}, the first haddps produces {c0+c1, c2+c3, c0+c1, c2+c3}.  The second produces {c0+c1+c2+c3, <same thing in the other lanes>}.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Webservice request fails for sequential call in Webshpere 7.0 I am running into this error when trying to call web service from server side of a Spring based web application.
javax.xml.ws.WebServiceException: java.io.IOException: Async IO operation failed (1),
reason: RC: 55 The specified network resource or device is no longer available.

The web application I am developing is running on WebSphere 7.0 / Windows Server 2008 R2 64bit.
The web service interface is implemented as javax.iws.WebSerivce (uses @WebService annotation). In my case it has 2 methods implemented with @WebMethod annotation which call 2 different methods on web service.
Error happens when I try to call 1st and 2nd methods sequentially one after another. The calling to both of these methods is done in the same server side function:
public MyResponse getResponse (...) {

    Res res1 = webServiceInstance.getFstCall()

    Res res2 = webServiceInstance.getSndCall()

}

1st method call always succeeds, but I always get the above mentioned error for the 2nd call.


text:
Q: Trying to compile .cpp with g++ for 64 bit windows First I tried just downloading what you get after searching mingw64 windows. That didn't work. While searching for a solution I came across this, where the answer includes what seems to be a legit version of mingw64.
This being probably the third or fourth mingw64 I've downloaded, I was happy to see a g++64.exe which I assumed would take care of everything. It doesn't, after compiling with g++64 -o hello.exe -c hello.cpp and running hello I get an error saying This version of [...]\hello.exe is not compatible[...].
What am I doing wrong? I've tried -m64. Is there some additional setting I need to change? Should I post what I get for g++64 -v?

A: Your command is wrong, you're not creating a .exe file, but an object file that you need to link to produce an executable. Do it like this:
g++64 -o hello.exe hello.cpp

The -c argument tells the compiler to just compile but not link your code. You can do the above in 2 steps, compile and link:
g++64 -c -o hello.o  hello.cpp
g++64 -o hello.exe hello.o


text:
Q: How to put data vertically in TextView in android Please let me know, how can I put strings seperated by line, vertically in an TextView?
I am scanning a QR Code and fetching the data integrated in the code, I want it shown vertically in an edittext, but it is coming horizontally in edit text.
Below is the xml code for EditText
<TextView android:layout_height="fill_parent"
       android:layout_width="wrap_content"
       android:inputType="text"
       android:id="@+id/edt"
       android:gravity="top"/>

below is my activity code
finalOutput= new StringBuffer();
qrValueArray = new ArrayList<String>();
String line= System.getProperty("line.separator");
String[] valueOfQRAfterSplit = intentQrScanValue.split(";");

for(int j = 0; j < valueOfQRAfterSplit.length; j++) {
    if(j==0){
        finalOutput.append(valueOfQRAfterSplit[j].toString());
     }else{
        finalOutput.append(System.getProperty("line.separator") + valueOfQRAfterSplit[j].toString());
     }
}
ed1.setText(finalOutput);
Toast.makeText(getApplicationContext(),finalOutput, Toast.LENGTH_LONG).show();

The thing is in Toast data is coming vertically, while in EditText it is coming horizontally and i have to scroll horizontally to see all the data.

A: You'll need a custom TextView for that. There are quite a few open implementations available if you google it. Here's one that I've used in the past:
http://code.google.com/p/dobroreader/source/browse/src/org/anonymous/dobrochan/widget/VerticalTextView.java

A: I did something similar using this example. Basically you have to create your own TextView class that extends from the standard TextView:
http://blog.stylingandroid.com/archives/796
I hope this helps and is what you're looking for!


text:
Q: Workbooks.Open populates "source" rather than "target" file I have tried the below, and many others not noted, with limited success.
https://msdn.microsoft.com/en-us/library/office/ff194819.aspx
Workbooks.Open Method in VBA
My situation is this:  I have a weekly file, produced from our ERP system, that populates limited information.  I have a macro recorded (yes, I know...) to automatically populate the other data I need, linked from another source, but the macro always requests that I open the "source" workbook before the data can populate.  I wanted to use the "Open.Workbooks" expression to open the workbook (read only & do not update links) so I would not have to "drill down" into the source workbook every time I run the macro.
I found the string that will open the workbook as a read-only file, and does not update links.  I have tested it as a stand-alone, and it works like a charm:
Workbooks.Open Filename:="SourceFile.xlsx", ReadOnly:=True, UpdateLinks:=False

The problem I am having is when I combine this small subroutine with my other macro, the data that is supposed to populate in the "target" file actually populates in the "source" file.  I need to open the "source" document, then somehow activate the "target" workbook so that the data population occurs in the "target" workbook, not the "source"
I have seen snippets of code that are relevant to setting the active workbook to the "target" workbook after the "open.workbooks" expression is used, but I do not know how to implement them.

A: dim wbsource as workbook
dim wbtarget as workbook

set wbsource = activeworkbook
set wbtarget = Workbooks.Open Filename:="SourceFile.xlsx", ReadOnly:=True, UpdateLinks:=False

'do your code here

Set two different workbook objects.


text:
Q: How do I write an if statement for my guessing game in C# Im designing a game on visual C# the game must contain two text boxes and two bottons and a lable
in the first text bos I should enter the range of numbers the program should randomly generate. ---- and its activated by the botton.
the second text box is the place where i enter the guesses ,---- also there is a botton to read the number.
I will have a limit of ten guesses , each is assgined a color.
for example the game will start with the green and if my guess was wronge the color wil change to a darker color ( dark green ,darker  ..... red etc) and if I guessed the right answer the screen will get back to the green with a lable that say you won !! or if I finished my guesse it show me Game Over !!
Now Im not that xpert in Visual C# so I find it hard where to write the code ... and how to activate actions as the color changing thing
BUT i understand that i need to use the random function and know how to set the range as you will see in the code below but Now Im stuck I don't know how to continue,,, Some one please guide me and help me.
private void button1_Click(object sender, EventArgs e)
    {

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        int range;
        range = int.Parse(textBox1.Text);
        System.Random RandNum = new System.Random();
        int Magicnumber = RandNum.Next(0, range);
        int numberofguesses = 0;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        int usersguess ;
        usersguess = int.Parse(textBox2.Text);

        if (usersguess == Magicnumber) ;
        {
            // I dont know what to write here
        }
        {
            if (usersguess != Magicnumber);
        {
            // I dont know what to write here
        }
        }
    }
}

}
I know this stupid but Im not pro and I would like to learn from you guys
and I belive this is the right place to ask ....
thanx in advance

A: (This started as a comment, but nobody mentioned it, and I got carried away...)
Please note that adding a semicolon after the if is a mistake (this is probably why else didn't work for you, and you've made this strange if-if anti pattern).
This is the proper way to write an if statement (else is optional, by the way):
if(key == 'Q')
{
   LaunchMissiles();
}
else
{
   GivePeaceAChance();
}

Now, what you've got there is quite different:
if(key == 'Q');
{
   LaunchMissiles();
}

See that semicolon after the if? That means that if(key=='Q'); and LaunchMissiles(); are two different statements, rather then a condition. This is the same as:
if(key == 'Q') DoNothing();
LaunchMissiles();

Despite it's appearance, the curly braces won't help you here - you can group a bunch of statements in curly braces, but it has no effect on flow control (unless immediately after an if, or loop, of course).

A: your if statement needs a tidy up for a start:
    if (usersguess == Magicnumber)
    {
        // I dont know what to write here
    }
    else
    {
       // I dont know what to write here
    }

A: Hmmm this seems like a homework type question but anyway (Since you did not mention whether this is a winforms or asp.net app i am going to assume winforms) .
For starters you need to move the declaration of
int Magicnumber = RandNum.Next(0, range);
and make it a member variable so that it can be accessed by all the functions in your form.
Secondly in your button click you can set the back color of a button to show the colors changing or you can use images , i would go with the button since you can dynamically change its color by keeping a variable that store the hex value of a color and incrementing it on every failure e.g.
Color myColor = Color.FromArgb(100,123,23,myvar);
btnColor.BackColor = myColor;
By incrementing/decrementing myColor in the example above the backColor of the button will change on each failure. If the user gets the answer right then you can set the backColor to a default color of your choice.

A: First of all, here is the better way to write your 'if' construction:
if (int.Parse(textBox2.Text) == Magicnumber)
{
    ...
}
else
{
    ...
}

If you want to count the number of user attempts to guess the number, you should store it in a variable. And this variable should be reset to zero any time you start new game.
private int count = 0;

private void button2_Click(object sender, EventArgs e)
{
    ...

    if (int.Parse(textBox2.Text) == Magicnumber)
    {
        // User wins
        ...
    }
    else
    {
        // Wrong answer
        count++;
        ...
    }
}

Then, if you want to change the background color of some WinForms control, use BackColor property (its value should depend of count). This example changes background color of TextEdit instance:
textEdit1.BackColor = Color.DarkGreen;

The Color here is System.Drawing.color class that may represent any color and have a lot of named values (http://msdn.microsoft.com/en-us/library/system.drawing.color.aspx, http://msdn.microsoft.com/en-us/library/aa358802%28VS.85%29.aspx). I strictly recomed you to begin with reading some good book on C# before trying to solve any programming tasks.


text:
Q: Argument 1 passed to Doctrine\Common\EventManager::addEventSubscriber() I get some trouble when I would load symfony app:
php.CRITICAL: Type error: Argument 1 passed to Doctrine\Common\EventManager::addEventSubscriber() must implement interface Doctrine\Common\EventSubscriber, instance of optro\Help\ORM\Listener\MessageElasticaListener

See my service configuration:
helpdesk.listner.optro:
class:  Optro\Help\ORM\Listener\MessageElasticaListener
arguments:
- '@fos_elastica.object_persister.optro.technical_assistance'
- '@fos_elastica.indexable'
- { index: technical_assistance, type: post, identifier: id }
tags:
- { name: doctrine.event_listener, event: elastica.index.index_post_populate }

This is my class MessageElasticaListener:
use Doctrine\Common\EventArgs;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use FOS\ElasticaBundle\Doctrine\Listener as ElasticaListener;
use optro\Help\Entity\HelpdeskMessage;

class MessageElasticaListener extends ElasticaListener
{
    /**
    * {@inheritdoc}
    */

    private function isObjectIndexable($object)
    {
        return true;
    }

    /**
    * {@inheritdoc}
    */
    public function postPersist(LifecycleEventArgs $eventArgs)
    {
        if (!$eventArgs instanceof LifecycleEventArgs) {
            return;
        }
        $entity = $eventArgs->getObject();
        if ($entity instanceof HelpdeskMessage && $this->isObjectIndexable($entity->getTechnicalAssistance())) {
            $this->objectPersister->replaceOne($entity->getTechnicalAssistance());
        }
    }
}

What's wrong ? Bad services configuration ?
I use symfony 3.4 and FOS Elasticasearch 5.0.3


text:
Q: Erro ao fazer INSERT - Laravel 5.1 + PostgreSQL Tenho campos de data no meu formulário, porém esses campos são opcionais. Quando eu preencho com uma data o cadastro é realizado com sucesso, mas se eu deixo o campo de data vazio recebo o seguinte erro:
SQLSTATE[22007]: Invalid datetime format: 7 ERROR: invalid input syntax for type date: "" (SQL: insert into...

O mesmo acontece quando deixo um campo do tipo inteiro em branco (número da residência por exemplo), parece que o postgre não aceita que seja deixado em branco, sei la...
A propósito, os campos foram criados como podendo serem nulos:
$table->date('nascimento')->nullable();

Estou utilizando laravel 5.1 com postgresql. Alguém me da uma luz?

A: Resolvido:
Na variável que recebe o valor do número(integer) eu fiz o seguinte:
($request->get('numero') == '') ? NULL : $request->get('numero')

Na variável que recebe o valor da data de nascimento(date) eu fiz o seguinte:
($request->get('nascimento') == '') ? NULL : $request->get('nascimento')


text:
Q: Apache Kafka: bootstrap-server is not a recognized option I'm trying to set up Apache Kafka to communicate between two virtual machines running CentOS on the same network. I originally set up a Kafka producer and consumer on one machine and everything was running smoothly. I then set up Kafka on the other machine and in the process of trying to get them to connect, I get the error "bootstrap-server is not a recognized option" (I'm running the most recent version of Kafka, 2.2).
This is what I used to attempt a producer connection:
bin/kafka-console-producer.sh --bootstrap-server 10.0.0.11:9092 --topic test
And on the consumer side:
bin/kafka-console-producer.sh --bootstrap-server 10.0.0.11:9092 --topic test
The 10.0.0.11 machine is running the server itself.

A: Following command should work.
./bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test

A: According do Apache Kafka Documentation, that can be found here: https://kafka.apache.org/documentation/#quickstart_send, you should use --broker-list property to pass broker address.
Command will be:
./bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test
EDIT
From Apache Kafka 2.5 both options are supported --broker-list and --bootstrap-server. Suggested one is --bootstrap-server

A: ./kafka-console-consumer.sh  --zookeeper localhost:2181 --topic fred
Simply giving this command worked. However in upcoming major release using the option bootstrap-server will be mandatory.
When I use the above command it gives a warning: "Using the ConsoleConsumer with old consumer is deprecated and will be removed in a future major release. Consider using the new consumer by passing [bootstrap-server] instead of [zookeeper]."


text:
Q: Open new document in client/native app instead of browser tab We currently have a document library which will open already existing documents in the client application (ensured the "Library Settings" -> "Advanced Settings" -> "Opening Documents in the Browser" is set to "Open in the client application", even the server default is set to open in client).
But, when we try to create a new document from a template (Word Document), it will open the editor in a new browser tab. I have another list with custom content types which correctly open new documents via Word templates in the client app.

My hypothesis was some kind of content type setting, but since it's the "Documents" library with no custom content types, SharePoint seems to not show the content types section in the library settings, and while also looking for such an option in the content types in the other working library, I couldn't find anything.
Is there really no setting for this? And if not, how come it's working with a custom content type?


text:
Q: How do I keep terminal line from overwriting itself? In a terminal window any smaller than fullscreen, if I type in a long command it starts overwriting the current line I'm on. If I type an additional line's worth, it finally moves to the next line. Does anyone know how to fix this?
This is what happens visually:

Edit: These are my prompt settings:
PS1='\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\u@\h:\w\033[1m`__git_ps1`\033[0m\$ '
TERM=xterm

.bashrc:
if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\033[1m`__git_ps1`\033[0m\$ '
fi

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

A: For some reason the terminal size is mis-reporting. It should change when you resize the terminal.
Try this in your .bashrc command file:
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

A: I found the answer here. The answer with the most votes solved it for me.
To sum it up I had to wrap my formats in \[ \]
export PS1='\[\033[1;32m\]$(whoami)@$(hostname): \[\033[0;37m\]$(pwd)$ \[\033[0m\]'

A: For those using PuTTY terminal (v0.67) and terminal size is not updated correctly:

*

*You can right click on the window's left hand icon, then select Change Settings....

*Within PuTTY Reconfiguration, from left hand sidebar, click on Window > Set the size of the window > Columns.

*Update the Columns value manually. I changed mine to 255 and that stopped the terminal overwriting on its own line (when I type).


text:
Q: How do I use a lens with an IxSet? Say, I have Users contained in a Userlist, like so:
import Control.Lens
import Control.Lens.At -- maybe this would help?
import Data.IxSet

data User = User { _userId :: Int
                 , _userName :: String }

instance Indexable User where
    empty = ixSet [ ixFun (\u -> _userId u) ]

makeLenses ''User

data Userlist = Userlist { _users :: IxSet User }

makeLenses ''Userlist

What command would give me a lens to view, say, the 3rd member of a userlist?
Perhaps, since my data definition would allow multiple users with the same ID, a lens may not be what I want... a traversal? a prism?
Part of the difficulty for me is that all my googling leads me to a deprecated package called data-lens-ixset.


text:
Q: este.parentElement.parentElement.children.tags is not a function We have a tree which users can open up, it was working fine in explorer 8 and 9 but when we switched to Chrome, it stopped working, the function is like this:
function menuopen(este,sm,opt,id)
{

    var m=eval(sm); var n;
    if(m[opt][VOPEN]) return;

    var parent_elm = este.parentElement.parentElement;
    var all_children = parent_elm.getElementsByTagName('TD');
    var este_TD_children = getImmediateChildren(parent_elm, all_children);
    //var t0=este.parentElement.parentElement.children.tags('TD')[0];
    var t0=este_TD_children[0];
    //var t1=este.parentElement.parentElement.children.tags('TD')[1];
    var t1=este_TD_children[1];

    if(shownodelines)
    {
        //t0.children.tags('A')[0].children.tags('IMG')[0].src=menuimg(IMINUS,m[opt][VPOS]);
        var parent_elm2 = t0;
        var all_children2 = parent_elm2.getElementsByTagName('A');
        var A_children = getImmediateChildren(parent_elm2, all_children2);

        var parent_elm3 = A_children[0];
        var all_children3 = parent_elm2.getElementsByTagName('IMG');
        var IMG_children = getImmediateChildren(parent_elm3, all_children3);

        IMG_children[0].src=menuimg(IMINUS,m[opt][VPOS]);

    }
    if(showfoldericon)
    {
        //also check if we need to over ride the folder if unselectable
        //if(treeRestrictMode==1 && inarray(id,nonSelArr))
        {
            //t1.children.tags('IMG')[0].src=menuimg(IFOLDERNA,IOPEN);
        }
        //else
        {
            //t1.children.tags('IMG')[0].src=menuimg(IFOLDER,IOPEN);

            //t1.getElementsByTagName('IMG')[0].src=menuimg(IFOLDER,IOPEN);
            var parent_elm4 = t1;
            var all_children4 = parent_elm4.getElementsByTagName('IMG');
            var IMG_children4 = getImmediateChildren(parent_elm4, all_children4);
            IMG_children4[0].src=menuimg(IFOLDER,IOPEN);

        }
    }

    n=seqname++;
    t1.innerHTML+=menuhtml(sm+'['+opt+'][VMENU]',n);
    m[opt][VOPEN]=1; m[opt][VNAME]="m"+n;

    for(var i=0;i<m[opt][VMENU].length;i++)
    {
        m[opt][VMENU][i][VPARENT]=m[opt];
    }

    if(shownodelines) menubacktd(m[opt],0);
}

and it is called as follow:
function menuanchor(este,sm,opt,id)
{
    var m=eval(sm);
    if(m[opt][VOPEN])
    {
        menuclose(este,sm,opt,id);
    }
    else
    {
        menuopen(este,sm,opt,id);
    }
}

For some reason, we get this error:
este.parentElement.parentElement.children.tags is not a function
so apparently chrome deals with this in a different way or we are using some Microsoft proprietary code that needs to change.
Thanks,


text:
Q: SQLAlchemy - How to select cerain rows? How to simulate a SELECT in SQLAlchemy? I would like to create a function which takes a couple of parameters and returns a row which contains those values but I can't do SELECT.
The only way I found is below but I can't find metadata in SQLAlchemy module.
EDIT: I figured out that BoundMetaData is deprecated so MetaData is appropriate, but it says that Select has no len
# -*- coding: utf-8 -*-
import sqlalchemy
from sqlalchemy import Column, Table
from sqlalchemy import UniqueConstraint
from sqlalchemy import create_engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:///db.db', echo=False)
Base = declarative_base()

s = sqlalchemy.orm.Session(engine)

class Flight(Base):
    __tablename__ = 'flights'

    id = Column(sqlalchemy.Integer, primary_key=True)
    destination_from = Column(sqlalchemy.String)
    destination_to = Column(sqlalchemy.String)
    creation_date = Column(sqlalchemy.Date)
    start_date = Column(sqlalchemy.Date)
    return_date = Column(sqlalchemy.Date)
    price = Column(sqlalchemy.Float)
    filename = Column(sqlalchemy.String)
    bought_days_before = Column(sqlalchemy.Integer)

    __table_args__ = (
        UniqueConstraint('creation_date', 'destination_from', 'destination_to', 'start_date', 'return_date', 'price'),
    )

Base.metadata.create_all(engine)

def insert_into_flights(**kwargs):
    s.add(Flight(**kwargs))
    try:
        s.commit()
    except IntegrityError as e:
        s.rollback()

def get_prices(date_from, days, bought_days_before, destination, min=True, avg=False):
    flights = Table('flights', metadata ,autoload=True
                )
    print len(flights.select())

A: s.query(Flight).filter(Flight.id==34).all()

This is an example selecting the Flight with id 34.
See SQLAlchemy docs


text:
Q: Phpstorm can't upload to google appengine After following the quickstart for setting up google-app-engine integration into phpstorm here https://confluence.jetbrains.com/display/PhpStorm/Getting+Started+with+PhpStorm+as+Google+App+Engine+PHP+IDE
I can't upload code app engine and i get this error message. Is there anywhere in the settings of phpstorm something i shuld change tomake it work?

/usr/bin/python /path/to/google_appengine/appcfg.py -e account@gmail.com --passin --no_cookies update .
Usage: appcfg.py [options] <action>

appcfg.py: error: no such option: --passin

Process finished with exit code 2

A: JetBrains are a bit behind the updates in the SDK's appcfg.py changes and don't have support for configuring/customizing the upload arguments - I had a similar issue with PyCharm.
My recommendation is to perform the upload from the terminal, using directly appcfg.py following the SDK instructions, instead of uploading from the IDE.


text:
Q: CollectionViewCell image restored to original image on scroll? I have a button is a collectionViewCell. When the button is clicked, its image is changed. But when I scroll in my UICollectionView, the changed image reverts back to the original one.
Can anyone tell me how to resolve this issue?

A: On each time scrolling the collection, cell created again so the image is changing.
Use a boolean or any other property that will check which image should  appear.


text:
Q: Searches for Chinese characters in Sqlite database with PHP don't match I'm having some trouble getting PHP to match queries of Chinese characters in an SQLite database. The same search when done in sqlite3 from the command prompt yields a hit, but PHP shows nothing.
The code:
$db = new PDO('sqlite:database.db');
$sql=$db->prepare("SELECT * FROM character WHERE character='安';");
$sql->execute();
$result=$sql->fetchAll();
print_r($result);

This shows an empty array. When I search for any other field(not a Chinese character), it will show the correct result.
For laughs, I set the headers to utf-8, 16, 16BE, 16LE(just flailing), but this did nothing.
The data type for the field is set as nchar, but setting it to text gives no different result. Similarly, using SQLite3 instead of PDO makes no change.
Any ideas? Thank you in advance for any help.

A: By default, the Windows console does not correctly handle UTF-8 input/output.
Any data you have entered or edited in the console is some wrong encoding.
You could try to execute chcp 65001 before running sqlite3.exe, but you'd better use some other SQLite tool that handles UTF-8 correctly in the first place.

A: It appears that there is no easy answer, but it isn't a problem with the Windows console, as the database handles all input, from browser or console in the same manner.  Despite sources saying that sqlite can use utf-8, it appears to work in ucs-2, an encoding I have no knowledge of. I verified this by decoding and encoding ucs to utf.
The easy answer, and the one I took, as I couldn't get the encoding to jive, was to just use base64_encode on queries going into the database, and decode on information coming out. It's not elegant, but it allows utf characters into a non-utf database.
http://jp2.php.net/manual/en/function.base64-encode.php


text:
Q: What's your favorite web view for Subversion (SVN) repositories? I have just built up my first SVN server, along with the mod_dav_svn module for Apache so that I have a rudimentary web view into the repository.
There appear to be lots of alternate/additional packages to make the web view more full-featured, along the lines of what you would see at Launchpad or Sourceforge.
What's your favorite web view for SVN?

A: We use ViewVC internally which works great for our needs.

A: Much more than just a web interface to svn: Trac -- open source and includes issue tracking and a wiki.  Not the easiest thing to set up though.

A: Expensive but imho the best one out there
Atlassian  FishEye
http://www.atlassian.com/software/fisheye/

A: Some options:

*

*Trac It's free/open-source, and widely used. The SVN-browsing part of Trac is here

*bsSvnBrowser - an AJAX'y subversion browser (demo)

*WebSVN - Written in PHP, looks nice (demo)

A: Warehouse. Just went open source, too.

A: The folks at BeanStalk provide both the SVN server itself and an interface to permit you to work with your repository.  While this doesn't apply if you already have an SVN server, you should check them out if you are just getting started.  Note: I am a user of the service but am otherwise unaffiliated with them.


text:
Q: Least cost path: single source point, multiple target points I have a single source point in EPSG:3857, and a set of points, also in EPSG:3857. I calculated a slope layer from SRTM (in EPSG:3857) in the extent of the complete set of points. I would like to use this layer as a friction layer for calculating least cost path. I would like to do this in a way that one single action provides a set of paths, from the source point to the every destination point.
So far I tried using Least Cost Path and r.cost + r.drain and I'm able only to calculate one single path. (In the case of r.drain from closest destination point to the source point.) I am unable to produce a set of paths no matter what I try. I would welcome instructions on how I could calculate multiple cost paths, using slope layer only as cost. I am attaching the points used,for review: https://1drv.ms/u/s!Ar4Fhb0r6aPcrDPF4rlLZlin4262?e=adYYtP
Please note that I edited the friction surface (slope layer) and removed larger water bodies from the extent, in order not to interfere with the calculation.
UPDATE: Solution behind this link r.cost multiple destinations is a working one> however my previous attempts to use it failed. In this particular case i believe that CRS was the problem - I had changed CRS from the EPSG:3857 to EPSG:4326, and the whole process started running as intended.


text:
Q: "Value does not fall within the expected range." error while exporting excel to pdf I am getting the above error while trying to export the excel 2007(xlsx) format workbook to pdf. The workbook contains only one sheet and I have Ms Office 2007 installed on my windows 7 PC.
Here is the stacktrace
   at Microsoft.Office.Interop.Excel.WorkbookClass.ExportAsFixedFormat(XlFixedFormatType Type, Object Filename, Object Quality, Object IncludeDocProperties, Object IgnorePrintAreas, Object From, Object To, Object OpenAfterPublish, Object FixedFormatExtClassPtr)

at schoolwisereportprint.converttopdf() in
C:\Users\username\Desktop\Dpp2012New\schoolwisereportprint.aspx.vb:line 33

at schoolwisereportprint.Button1_Click(Object sender, EventArgs e) in C:\Users\username\Desktop\Dpp2012New\schoolwisereportprint.aspx.vb:line 158

Here is my converttopdf() function:
Public Sub converttopdf()
    Dim fileName As String = Server.MapPath("rahulserver/pdfreprt.xlsx")
    Dim xlsApp = New Microsoft.Office.Interop.Excel.Application
    xlsApp.ScreenUpdating = False
    Dim xlsBook As Microsoft.Office.Interop.Excel.Workbook
    Dim paramExportFormat As XlFixedFormatType = XlFixedFormatType.xlTypePDF
    Dim paramExportQuality As XlFixedFormatQuality = XlFixedFormatQuality.xlQualityStandard
    Dim paramOpenAfterPublish As Boolean = False
    Dim paramIncludeDocProps As Boolean = True
    Dim paramIgnorePrintAreas As Boolean = True
    Dim paramFromPage As Object = Type.Missing
    Dim paramToPage As Object = Type.Missing
    xlsBook = xlsApp.Workbooks.Open(fileName, UpdateLinks:=False, ReadOnly:=False)
    xlsBook.ExportAsFixedFormat(paramExportFormat, "rahulserver/pdfreprt" & ".pdf", paramExportQuality, paramIncludeDocProps, paramIgnorePrintAreas,paramFromPage, paramToPage, paramOpenAfterPublish)
    xlsBook.Close(SaveChanges:=False)
    xlsApp.Quit()
    MsgBox("successfully converted to pdf!")
End Sub

Even changing paramFromPage and paramToPage to 1 and 1 respectively does not help. I have already spent a whole day troubleshooting this error but could not find a way. Now I look upon SO to get me out of this...

A: Just realized that this was a really old question. By the way, the problem was that the OP hadn't the "2007 Microsoft Office Add-in: Microsoft Save as PDF" Add-In installed.
You can find that here


text:
Q: Scraping td elements with background color style BeautifulSoup I am trying to parse a webpage where i want to scrape "tr" elements which have bgcolor attribute also. Below is the html for the webpage:

        ORGANIZATION NAME	STATE	YEAR	FORM	PAGES	TOTAL ASSETS	EIN

        Zoological Society of Philadelphia Philadelphia Zoo	PA	2017	990   	68	$124,163,973.00	23-1352298

        Zoological Society of Philadelphia	PA	2016	990   	61	$125,008,026.00	23-1352298

        Zoological Society of Philadelphia	PA	2015	990   	63	$131,880,929.00	23-1352298

I am trying to scrape tr elements using style element
style="color:White;background-color:#045D99;font-weight:bold;"

Below is my code:
import requests
from bs4 import BeautifulSoup
data = requests.get(url).text
soup = BeautifulSoup(data,"lxml")
elems = soup.find_all('tr',style"color:White;background-color:#045D99;font-weight:bold;")

However my elems returns empty. Also in my soup element, i see that:
style="color:White;background-color:#045D99;font-weight:bold;"

has changed to

I am not sure if this is causing the problem, also is there a way to scrape the whole tables as a pandas dataframe instead?
Edit:
I had a typo in my code, below is the correct code:
soup.find_all('tr',{"style":"color:White;background-color:#045D99;font-weight:bold;"})

Same as mentioned in the answers, still i get null results
One more Edit:
Even after the suggestions, i am still getting null results. The html is from below webpage:
http://990finder.foundationcenter.org/990results.aspx?990_type=&fn=AMERICAN+HEART+ASSOCIATION&st=&zp=&ei=&fy=&action=Search

I am trying to parse the table present in the webpage

A: I will take you fairly literally. The background-color is not an attribute but part of the style attribute value. Assuming you want one containing that substring (and to cater for different colours perhaps), we can use contains, *, operator to match on style attribute value
html = '''

        ORGANIZATION NAME	STATE	YEAR	FORM	PAGES	TOTAL ASSETS	EIN

        Zoological Society of Philadelphia Philadelphia Zoo	PA	2017	990   	68	$124,163,973.00	23-1352298

        Zoological Society of Philadelphia	PA	2016	990   	61	$125,008,026.00	23-1352298

        Zoological Society of Philadelphia	PA	2015	990   	63	$131,880,929.00	23-1352298

'''

import requests
from bs4 import BeautifulSoup as bs
soup = bs(html,"lxml")
trs = soup.select('tr[style*=";background-color:"]')

A: Changing last line of your code:
soup.find_all('tr',{"style":"color:White;background-color:#045D99;font-weight:bold;"})

you get:
[

 ORGANIZATION NAME	STATE	YEAR	FORM	PAGES	TOTAL ASSETS	EIN

]

Concerning your last question, assuming t stores the html of the table of interest, you can convert it into a DataFrame by using pandas.read_html:
import pandas as pd

df = pd.read_html(t)

display(df[0])

In your case, you get:
                  ORGANIZATION NAME   STATE YEAR    FORM PAGES  TOTAL ASSETS       EIN
0   Zoological Society of Philadelphia  PA  2017    990    68   $124,163,973.00 23-1352298
1   Zoological Society of Philadelphia  PA  2016    990    61   $125,008,026.00 23-1352298
2   Zoological Society of Philadelphia  PA  2015    990    63   $131,880,929.00 23-1352298

A: Your syntax is off. Change to this:
elems = soup.find_all('tr', {"style":"color:White;background-color:#045D99;font-weight:bold;"})

Full Code:
data = '''

        ORGANIZATION NAME	STATE	YEAR	FORM	PAGES	TOTAL ASSETS	EIN

        Zoological Society of Philadelphia Philadelphia Zoo	PA	2017	990   	68	$124,163,973.00	23-1352298

        Zoological Society of Philadelphia	PA	2016	990   	61	$125,008,026.00	23-1352298

        Zoological Society of Philadelphia	PA	2015	990   	63	$131,880,929.00	23-1352298

'''

import requests
from bs4 import BeautifulSoup
#data = requests.get(url).text
soup = BeautifulSoup(data,"lxml")
elems = soup.find_all('tr', {"style":"color:White;background-color:#045D99;font-weight:bold;"})


text:
Q: When is the Usage of ConfigureAwait(false) in ViewModels problematic? I wonder in which situations I will run into problems when using
ConfigureAwait(false)

in my (Xamarin) MVVM approach. This is mainly because I do not fully understand the synchronization context a view and a viewmodel and its properties and the underlaying model have to each other...
1 What about observable collections?
// VM
public ObservableCollection<SomeThing> SomeThings { get; set; }
// ...
public Task InitWorkload()
{
    SomeThings = await DbService.GetSomeThings(); // <-- Should need synchronization context, doesn't it?
}

// Service
public Task<SomeThings> GetSomeThings()
{
    result = await CallToDb.ConfigureAwait(false); // <-- This is UI agnostic and shouldn't care about context or does it?
    return result;
}

2 What about Navigation (in this case with the help of FreshMvvm)?
private async Task CloseWindow()
{
    await CoreMethods.PopPageModel(); // <-- Should need synchronization context, doesn't it?
}

A: To answer the title question, "When is the Usage of ConfigureAwait(false) in ViewModels problematic?" is "Never." Its use in a view model is irrelevant. What matters is what thread you want to run on after the async method is called, whether or not you are in a view model is irrelevant. The only time that using ConfigureAwait(false) may be problematic is if you want to return to the thread that was running before the async method was called.
And for reference, docs on the SynchronizationContext class.
Maybe explaining what ConfigureAwait(false) does is the best approach to answer this. When one calls an async method like so:
var x = await SomeMethodAsync();
var y = x;

The code var y = x will run on the same thread that the work was being done on before the async method was called, i.e the Synchronization context prior to the async method call, however if you use ConfigureAwait(false), e.g.:
var x = await SomeMethodAsync().ConfigureAwait(false);
var y = x;

then the code var y = x will run on the same thread that the SomeMethodAsync method was running on when it returned. (Presumably SomeMethodAsync uses Task.Run or Thread.StartNew which are the main ways of launching a new thread... await does not start a new thread, it is only syntactic sugar to allow your async code to be more readable so that the code following the async method call does not have to be an a delegate method or lambda, but can be in-line just like synchronous code.)
So what you need depends on what might need to be updated. Any UI updates need to run on the Main or UI thread. You can always marshal code to the Main or UI thread with Device.BeginInvokeOnMainThread(Action).
Generally, when you are in a, let's say, button click handler event, the event handler method starts running on the UI thread. If you need to call one async method and then update some UI, then do not use ConfigureAwait(false) so that after the async method you return to the Main/UI thread and you can update your UI. If you do not need to update any UI, then feel free to call ConfigureAwait(false) so that you do not unnecessarily return to the UI thread when there is no need to be running on that thread.
In some cases if you are calling multiple async methods from one method that starts on the UI thread, you might want to use ConfigureAwait(false) such that you are not going back and forth to the UI thread from background threads multiple times, which cause performance issues, but rather all of the Non-UI work is done on a background thread, and then you just manually marshal back to the UI thread when and if needed.
As for an ObservableCollection, it does not have thread affinity, i.e. when an object can only be updated or modified on the same thread that it was created on, but it is also not thread safe, so your best plan is to only access or change the ObservableCollection on the same thread that it was created on, most likely he Main/UI thread.


text:
Q: Find difference of two String lists - Python Let's say I have two string lists in Python (but this problem is not really language-specific):
a = ["cat", "dog", "fish"]
b = ["cat", "dog", "fish"]

My goal is to be able to quantify the difference of those two lists. More specifically, my program has to calculate how "alike" is list 1 to list 2 and give it a "score". I am using that to calculate the error in some results I get. I process some audio and I get an list which is the result. I want to compare that result to the result I should have gotten.
Therefore, in the above examples the result is identical to the correct result so the answer should be 1 (100%).
In this case:
a = ["cat", "dog", "fish", "lion"]
b = ["cat", "dog", "fish", "tiger"]

The result is 0.75 (75%).
Here is my code:
def compare_lists(result, correct):
  # TODO: This could be way better.
  if len(result) != len(correct):
    return 0
  else:
    sum = 0
    for i in range(0, len(result)):
      if result[i] == correct[i]:
        sum += 1
  return float(sum) / float(len(result))

However, problems arise when the lists have different lengths. For example:
a = ["cat", "dog", "zebra", "fish"]
b = ["dog", "zebra", "fish"]

The logic described before cannot be applied here. In this case, b is almost the same as a but a has one more element in the beginning. I want to be able to correctly quantify this "similarity", as my current algorithm returns 0, but in reality my result with the correct result do not have a big difference.

A: You can try this algorithm:
a = ["cat", "dog", "dog", "fish"]
b = ["dog", "dog", "fish"]

if len(a) != len(b):

    results = ''.join(a).split(''.join(b))
    results = [i for i in results if i != '']
    print results
    print len(results)

    print((len(a)-len(results))/float(len(a)))

else:
   off_by = (len(b)-len([1 for i in range(len(b)) if b[i] != a[i]]))/float(len(a))
   print(off_by)

The goal of this algorithm is to determine by how much one list differs from the other. In this example, the algorithm notices that the list b exists in a, but with another element in front of it. Therefore, the list a differs from list b by one. Thus, we can say that the score should be 0.75 because three of the four elements in list a belong in list b, or 3/4

A: difflib's SequenceMatcher does exactly what I wanted.
  s = difflib.SequenceMatcher(None, result, correct)
  s.ratio()


text:
Q: How to store the previous search data and the search category in MVC c#? I'm going to try to save the previous search result and data. For example, if I search for the word 'apple', then the result displays sorting by apple. I implemented the partial sorting which means sorting by the particular category when I click. At that time, the search function is initialized. Also, when I search once more, the result shows from the original context.
What do I need to do to implement for those?
Here is the code for controller.
public ActionResult Index(string searchField, string sortOrder, string currentFilter, string searchString, int? page, string commandName)
    {
        ViewBag.CurrentSort = sortOrder;
        ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
        ViewBag.PostNumSortParm = sortOrder == "PostNum" ? "post_desc" : "PostNum";
        ViewBag.HitsSortParm = sortOrder == "HitsNum" ? "hits_desc" : "HitsNum";

        if (searchString != null)
        {
            page = 1;
        }
        else
        {
            searchString = currentFilter;
        }

        ViewBag.CurrentFilter = searchString;

        var bulletins = from s in db.Bulletins.ToList().OrderByDescending(b => b.postNum)
                        select s;

        switch (sortOrder)
        {
            case "PostNum":
                bulletins = bulletins.OrderBy(s => s.postNum);
                break;
            case "post_desc":
                bulletins = bulletins.OrderByDescending(s => s.postNum);
                break;
            case "HitsNum":
                bulletins = bulletins.OrderBy(s => s.readCnt);
                break;
            case "hits_desc":
                bulletins = bulletins.OrderByDescending(s => s.readCnt);
                break;
            case "Date":
                bulletins = bulletins.OrderBy(s => s.PostDate);
                break;
            case "date_desc":
                bulletins = bulletins.OrderByDescending(s => s.PostDate);
                break;
            default:
                break;
        }

        ViewBag.searchField = new[] { new SelectListItem() { Text = "All", Value = "All"},
                                      new SelectListItem() { Text = "Name", Value = "Name"},
                                      new SelectListItem() { Text = "Title", Value = "Title"}};

        switch (searchField)
        {
            case "Name":
                if (!String.IsNullOrEmpty(searchString))
                {
                    bulletins = bulletins.Where(s => s.Name.Contains(searchString));
                }
                break;

            case "Title":
                if (!String.IsNullOrEmpty(searchString))
                {
                    bulletins = bulletins.Where(s => s.Title.Contains(searchString));
                }
                break;

            default:
                if (!String.IsNullOrEmpty(searchString))
                {
                    bulletins = bulletins.Where(s => s.Title.Contains(searchString)
                        || s.Name.Contains(searchString));
                }
                break;
        }

        if (commandName == "NEW POST")
            return RedirectToAction("Create");
        if (commandName == "DELETE POST")
            return RedirectToAction("DeleteSelected");

        int pageSize = 6;
        int pageNumber = (page ?? 1);

        return View(bulletins.ToPagedList(pageNumber, pageSize));
    }

I created SelectListItem to keep the search category in the dropdownlist.
Here is the index view.

@using (Html.BeginForm("Index", "Bulletin", FormMethod.Get, new { searchField = ViewBag.searchField }))
{

            @Html.DropDownList("searchField")
            @Html.TextBox("SearchString", ViewBag.searchString as string)
            <input type="submit" value="Search" />

}

        Select

        @Html.ActionLink("Post No.", "Index", new { sortOrder = ViewBag.PostNumSortParm, currentFilter = ViewBag.CurrentFilter, searchField = ViewBag.searchField })

        Title

        Name

        @Html.ActionLink("Post Date", "Index", new { sortOrder = ViewBag.DateSortParm, currentFilter = ViewBag.CurrentFilter, searchField = ViewBag.searchField })

        @Html.ActionLink("Hits", "Index", new { sortOrder = ViewBag.HitsSortParm, currentFilter = ViewBag.CurrentFilter, searchField = ViewBag.searchField })

        Response

@using (Html.BeginForm("DeleteSelected", "Bulletin", FormMethod.Post, htmlAttributes: new { id = "DeleteID", searchField = ViewBag.searchField }))
{
    foreach (var item in Model)
    {

                <input type="checkbox" name="ids" value="@item.postNum" />

                @Html.DisplayFor(modelItem => item.postNum)

                @item.Title

                @Html.DisplayFor(modelItem => item.Name)

                @Html.DisplayFor(modelItem => item.PostDate)

                @Html.DisplayFor(modelItem => item.readCnt)

                @Html.DisplayFor(modelItem => item.reviewCnt)

    }
}

@Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, searchField = ViewBag.searchField }))

I skipped some code which seems not important. It is kind of hard for me to catch up what I'm missing.
Could you give me help?


text:
Q: Start AFP Sharing on server before user login? I would like to have access to AFP Share from our clients possible as soon as the server's system is started, without one of the users needing to open a local session on it (on the server) first.
I'm not sure but I think it was working this way with previous versions of OS X (10.6 or 10.7, we're running the latest 10.8) : as soon as you got the login screen on the server, AFP Share(s) were accessible on the network.
To be as clear as possible, I'm NOT trying to have the AFP Share automounted on the clients. I'm already using scripts and launchd for this, and it's working absolutely fine (with the obvious exception of the clients having to wait for a user session to be opened on the server for the Share to become available).
The server is a 2013 iMac and the disk being shared is a Promise Pegasus R6 (a Thunderbolt RAID drive).
2014-04-09 : still the same with OS X 10.9.x, neither SMB nor AFP share are accessible before a user open a local session on the Mac computer acting as the file server.
2015-09-08 : I gave up on this as it is no longer relevant for us, but ditto for OS X 10.10.x

A: I would set up a user to automatically log in and lock the screen immediately with a password (or as close to immediately as you care.) That will mount the external drive and start up sharin for all users.
Alternatively, you could drop the $20 on OS X server and have it mount shares at boot like you rightly expect a server to behave.


text:
Q: Example of E(E(X|F)|G) \neq E(E(X|G)|F) Can you find an example where
 E(E(X|F)|G) $\neq$ E(E(X|G)|F) (F and G is $\sigma$-field in probability theory)

A: Try an example with $F$ and $G$ the $\sigma$-algebras generated by random variables $Y,Z$
respectively. $\mathbb E[\ldots|F]$ is a function of $Y$ and $\mathbb E[\ldots|G]$ is a function of $Z$.  Except in "trivial" cases, these won't be equal.


text:
Q: Why is there no OpenJDK 8 packaged for guix? When I search the Guix repository there are only versions of OpenJDK from 9 and up, but I want to install OpenJDK 8. Why is there no version 8?
$ guix search openjdk | recsel -p name,version
name: openjdk
version: 9.181

name: openjdk
version: 14.0

name: openjdk
version: 13.0

name: openjdk
version: 12.33

name: openjdk
version: 11.28

name: openjdk
version: 10.46

name: icedtea
version: 1.13.13

name: java-marlin-renderer
version: 0.9.4.2

name: icedtea
version: 3.7.0

name: icedtea
version: 2.6.13

A: Apparently OpenJDK 7 and 8 are named icedtea:
$ guix environment --ad-hoc icedtea --pure
$ java -version
openjdk version "1.8.0_161"
OpenJDK Runtime Environment (IcedTea 3.7.0) (guix build 1.8.0_161-b12)
OpenJDK 64-Bit Server VM (build 25.161-b12, mixed mode)


text:
Q: HybridAuth getUserProfile returns Trying to get property of non-object Well i'm using HybridAuth for google, FB and Twitter, and for FB works just fine, google returns empty user profile.
AccessToken is OK
getUserProfile() data is set NULL:
object(Hybrid_User)#8 (3) { ["providerId"]=> string(6) "Google" ["timestamp"]=> int(1452502079) ["profile"]=> object(Hybrid_User_Profile)#9 (22) { ["identifier"]=> NULL ["webSiteURL"]=> NULL ["profileURL"]=> NULL ["photoURL"]=> NULL ["displayName"]=> NULL ["description"]=> NULL ["firstName"]=> NULL ["lastName"]=> NULL ["gender"]=> NULL ["language"]=> NULL ["age"]=> NULL ["birthDay"]=> NULL ["birthMonth"]=> NULL ["birthYear"]=> NULL ["email"]=> NULL ["emailVerified"]=> NULL ["phone"]=> NULL ["address"]=> NULL ["country"]=> NULL ["region"]=> NULL ["city"]=> NULL ["zip"]=> NULL } } } }

Any idea what to check?

A: just pointing for other user that experienced with same behaviour.
you can enable debug mode by adding parameters on config file, just like this
array(
    "base_url" => "",
    "providers" => array (
        "Google" => array (
            "enabled" => true,
            "keys"    => array ( "id" => "", "secret" => "" )
        ),
        "Facebook" => array (
            "enabled" => true,
            "keys"    => array ( "id" => "", "secret" => "" )
        ),
        "Twitter" => array (
            "enabled" => true,
            "keys"    => array ( "key" => "", "secret" => "" ),
            "includeEmail" => true
        ),
    ),

    // if you want to enable logging, set 'debug_mode' to true
    "debug_mode" => false,
    // then provide a writable file by the web server on "debug_file"
    "debug_file" => "log.txt"
);

then you can check log, that's correct to use google user data we need to enable google+ api on google developer console,
and need to wait a while during propagation


text:
Q: Panel change from ListBox edit edit: I figured out the issue.  We were putting the : inbetween the case and the value, it needed to be after.  example:  case "General" :
Thanks for your time and input everyone.
Original:
This has to be a lot more simple than I'm attempting to make it.  Simply I have a listbox with say...6 different "items"(General/oSnaps/blah/blah/blah), when someone clicks one of the items in the listbox, I want it to change Panels.  I have 6 different Panels(panel1,panel2,etc) stacked on top of each other, on load only the first one set to visible.
I'm sure it's just a matter of setting which Panel is visible, but how do I actually link that to the "items" in the listbox?  SelectedIndexChanged is the answer I presume, but I'm very very new to programming.
MSDN only demonstrates how to switch between items in different listbox's.
Any help would be appreciated.
Edit: here's my current code
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
           string curItem = listBox1.SelectedItem.ToString();

           curItem = listBox1.SelectedItem.ToString();
            MessageBox.Show(curItem);

           switch(curItem)
        {
        case : "General"   //error here is: Only assignment, call,increment,await,and new object expressions can be used as a statement
        panel1.Visible = false;
        panel2.Visible = true;
        break;
        case : "E-Snaps" // same as above
        panel2.Visible = false;
        panel3.Visible = true;
        break;
        case : "blah" // same as above
        panel3.Visible = false;
        panel4.Visible = true;
        }
        }

Clicking on the different items in the listBox does bring up a message box with the correct content(General/E-Snaps/blah/etc).  So it's reading it obviously, how do we make it switch panels now?
Shouldn't I be able to do something like this also?
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
           string curItem = listBox1.SelectedItem.ToString();

           curItem = listBox1.SelectedItem.ToString();

            if curItem = "General"
            {
                panel1.Visible = true;
            }

}
Not that I can get either to work...but it seems logical.  If I could get some form of string/bool conversion going...

A: you could start by using a switch statement on the selectedindex changed
so it would look like this
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    // Get the currently selected item in the ListBox.
    string curItem = listBox1.SelectedItem.ToString();

    switch(curItem)
    {
        case "blah":
            panel1.visible = false;
            panel2.visible = true;
            break;
        case "blah":
            panel2.visible = false;
            panel3.visible = true;
            break;
        case "blah":
            panel3.visible = false;
            panel4.visible = true;
            break;
    }
}

and so on, I hope this helps
Explanation : "blah" is what ever value you want to eval so if I was doing fruits
"blah" would = apple
or bannana or pineapple etc

A: I would use an IValueConverter in the binding -- that will let you bind each panel's visibility directly to the ListBox.SelectedIndex.
<Grid>
    <Grid.Resources>
        <local:IndexToVisibilityConverter x:Key="IndexToVisibilityConverter" />
    </Grid.Resources>
    <ListBox x:Name="listBox"> ... </ListBox>

    <Border x:Name="panel1"
            Visibility="{Binding ElementName=listBox,
                                 Path=SelectedIndex,
                                 Converter={StaticResource IndexToVisibilityConverter}
                                 ConverterParameter='0'}"
    />
    <Border x:Name="panel2"
            Visibility="{Binding ElementName=listBox,
                                 Path=SelectedIndex,
                                 Converter={StaticResource IndexToVisibilityConverter}
                                 ConverterParameter='1'}"
    />
</Grid>

The "IndexToVisibilityConverter" should return "Visibility.Visible" if the index matches the parameter:
public class IndexToVisibilityConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((int)value == int.Parse((string)parameter) ? Visibility.Visible : Visibility.Collapsed);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Alternatively, note that if you want to use transitions (like cross-fade, slide in/out, etc), then you'll probably want to use an event trigger on the SelectionChanged event, along with a Storyboard or VisualState change.


text:
Q: Recycle View had the half of the height I have a problem with this Recycle View on this layout, it don't take the complete height of your father container.
I used the weight parameters, but that is not the problem i think.
Check the code and Print screen.
Thanks in advance.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="1">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/subjects"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            app:layoutManager="android.support.v7.widget.GridLayoutManager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:orientation="horizontal"
            tools:listitem="@layout/item_subject_tab" />

        <RelativeLayout
            android:id="@+id/usageStatusListContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.1"
            android:background="@color/colorLight">

            <ListView
                android:id="@+id/chapters"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:divider="@color/colorLight"
                tools:listitem="@layout/item_chapter_usage_status"/>

        </RelativeLayout>

    </LinearLayout>

</android.support.constraint.ConstraintLayout>

Layout


text:
Q: how to load a json from parent directory I have to load a configuration file from parent directory. Here is the folder structure :
.
├── cleanup
├── _conf.json
├── data
│   ├── all_combine_200k.csv
│   ├── cyclegear.csv
│   ├── make_dataset.py
│   └── R_Result_Temp.csv
├── features
│   ├── add_template_python.py
│   ├── build_features.py
│   ├── create_templates.py
│   ├── read_template_python.py
│   └── template_features_req.proto
├── __init__.py
├── models
│   ├── hmm
│   ├── __init__.py
│   ├── predict_model.py
│   └── train_model.py
├── remotedb
│   └── cyclegeardb.py
├── utils
│   ├── c_print.py
│   └── __init__.py
└── visualization
    ├── __init__.py
    └── visualize.py

I am in add_template_python.py and need to load _conf.json from the src directory.
In order to import stuff from other directories I just use sys.path.append('..') but that won't work here. What code can load json file from parent directory?

A: You can get the path to the the file with:
path_to_json = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '_conf.py')

This will not normalize the path. If that's important, you can normalize it with os.path.normpath.


text:
Q: generate RDF document From OWL file is there any tool that can generate RDF document from OWL file ?

A: Jena (http://jena.sourceforge.net/ ) will do this.
Also look at OWLAPI (http://owlapi.sourceforge.net/ ) though personally I find it very awkward


text:
Q: How do I reserve a name for my iOS app so that no one else can use it? At what point in the iOS development process using Xcode is my app name reserved on App Store? (There are no updated answers to this question in any posts at stackoverflow.) Last I remember when I published my iOS app for sale status on iOS App Store at App Store Connect I had to change my published app name because there were already other apps using that name. I think that was the name that was actually showing on the App Store, and not the name I put in the Product Name field when I first create the project in Xcode.
I just tried to validate my iOS app and it wouldn't validate because it said there was already an app with that "App Name". I take it that means the name I put in the Product Name field when I first created the project, if I don't change it later. Is that correct?
So if my iOS app project validates, does that mean I have that App Name reserved so that no one else can use it?
How do I reserve a name for my iOS app so that no one else will get it once I reserve it?

A: As someone said in the comments, simply create a new app in App Store Connect with the name you have in mind, then no-one else can use it. You don't have to send it to Apple immediately after you do this, you can wait however long you need to until it's ready.
Just make sure the bundle identifier is the same between the two.


text:
Q: CSS grid layout with equal height rows, where the shortest cell sets the height for all rows? Like the title says, I'm trying to create a 2 column grid where the smaller cell sets the height of both columns. Is this achievable with css?

A: As @TemaniAfif mentioned, the solution was to add:
  contain: "size",
  overflow: "scroll",

to the larger cell in the grid. But it does negate any spacing styles. My workaround for this was to add a third cell in between the 2 grid items with a width of 12px (which was the initial margin size).


text:
Q: Warping a Riemannian manifold until it has non-positive curvature Let $(M,g)$ be a complete $d$-dimensional Riemannian manifold and let $(\mathbb{H}^2,h)$ be the hyperbolic upper-half plane; and suppose that $\pi_n(M)=\{0\}$ for every $n\in \mathbb{Z}^+$.  If $(M,g)$ does not have non-positive curvature, then under what conditions does there exist a strictly convex function $f\in C^{2}(M,\mathbb{R})$ and a positive integer $k$ such that the warped product
$$
M\times_f \big(\mathbb{H}^2\big)^k
$$
has non-positive sectional curvature?

Really, I guess I'm wondering if there a way to deform the Riemannian metric $g$ until we achieve non-positive curvature?


text:
Q: Why won't the device plugin install in a Cordova 6.0 project? Why won't the device plugin install on a Cordova 6.0 iOS project? Here is the text from terminal app.
Justins-Air:hipmvi itiMobile$ cordova plugin add cordova-plugin-device
Fetching plugin "cordova-plugin-device@~1.1.1" via npm
Error: Failed to fetch plugin cordova-plugin-device@~1.1.1 via registry.
Probably this is either a connection problem, or plugin spec is incorrect.
Check your connection and plugin name/version/URL.
Error: EACCES, mkdir '/Users/itiMobile/.npm/cordova-plugin-device

A: It looks like it was a permissions issue.  I tried solving it by using sudo before the commands, but got errors.  Then I rebooted the mac and tried again.  The sudo version of the command then allowed me to add the plugin.
However, I could not open xCode at that point.  I got around that by selecting the folder in finder and choosing get info from the file menu.  I scrolled to the bottom, clicked on the lock icon, and granted read write to everyone.  After that, I chose apply to all items in folder from the settings drop down list at the bottom of the get info window.  I was then allowed to open the project in xCode.
Thank you @alexchance for pointing me in the right direction.


text:
Q: How to make Maxima display more digits How do you make Maxima print out all the digits it possibly can?
For example I entered 256^(256); and maxima returned 323170060713110073007148766886[557 digits]952148193555853611059596230656. I want it to print all the 557 digits in between, how do I go about doing that?

A: If you are using wxMaxima, change 2D-display in the Maxima entry of the menu to ascii or none.
You can obtain the same result with
set_display('ascii)$
or
set_display('none)$


text:
Q: Multiple insert and select into a single query Is there a way to convert this multiple insert and select into a single statement only?
INSERT INTO `subject` (`subject_code`, `student_id`)
   SELECT 'mathematics', student_id FROM student;
INSERT INTO `subject` (`subject_code`, `company_id`)
   SELECT 'science', student_id FROM student;
INSERT INTO `subject` (`subject_code`, `company_id`)
   SELECT 'chemistry', student_id FROM student;

A: use union all or union (depends on your data)
INSERT INTO `subject` (`subject_code`, `student_id`)
(SELECT 'mathematics' as subjectcode, student_id FROM student
union all
SELECT 'science', student_id FROM student
union all
SELECT 'chemistry', student_id FROM student);

A: You can do this with a cross join as well:
INSERT INTO `subject` (`subject_code`, `student_id`)
   SELECT sub.subject, s.student_id
   FROM student s CROSS JOIN
        (SELECT 'mathematics' as subject UNION ALL
         SELECT 'science' as subject UNION ALL
         SELECT 'chemistry' as subject
        ) sub;


text:
Q: Can someone help me with my regex? I am trying to get everything between quotations. What will be between the quotations is file locations. So it will be like "C:\Users\Documents and Settings\Pictures\mypic.bmp" The regex I am currently using is:
   "([""'])(?:(?=(\\?))\2.)*?\1"

It works to get numbers and letters except it splits it at the backslash. Can someone help me out so I can match the full string?
Thanks in advance.

A: I would go with:
@"""\s*(.*?)\s*"""

Sample code I used to test it:
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Match match = Regex.Match(txtString.Text, @"""\s*(.*?)\s*""",
            RegexOptions.IgnoreCase);

        if (match.Success)
        {
            string key = match.Groups[1].Value;
            lblFinal.Text = key;
        }
    }

Can we fix my negative votes? ;)

A: You can use the following regex (quoting in C# string literal):
string regexPattern = "\\\"(.+?)\\\"";

or
string regexPattern = @"\""(.+?)\""";

Without C# literal escaping
\"(.+?)\"

This way the matched group will be the string within the quotations
If testing at http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
Source
"C:\Users\Documents and Settings\Pictures\mypic.bmp"

Pattern
\"(.+?)\"

Result
C:\Users\Documents and Settings\Pictures\mypic.bmp


text:
Q: Is Ubuntu's mouse(pointer) weird? I used Ubuntu 10.04 previously and 10.10 now. What i felt is, it's pointer is a bit weird. It does point exactly on the target area but it slightly trembles or shake while the finger is on touchpad.Some of u might have noticed and may be not.Similar is not the case in Windows. I found this case in my friends Ubuntu too. Is this the bug? if yes ,anyway to fix it?

A: It is possible that your sensitivity is too high. Try opening your Mouse Preferences and lowering your acceleration and sensitivity options.

A: I experience this too. It is a bug.
You can file a bug report here at Launchpad
You can also initiate a bug report from within Ubuntu. First open System Monitor and identify what process-ID the bug most likely relates to. I'm not sure which process to use here, so you might guess and indicate it's a guess in the bug-report description. Let's say the process-ID is 1234 for purposes of this example. You would do the following:
Alt+F2
ubuntu-bug 1234

A: I caught one reason for this occasionally happening was that my mouse's wire or some other object was touching my laptop's trackpad. Thus the two separate mouse inputs were colliding with each other and causing the mouse pointer to shake and not respond as well.
Removing the obstruction from the trackpad fixed it.


text:
Q: Determining an event from a date range I would like to know if it's possible in Excel to select information from a seperate column if a date is within a specified list of ranges.
I have a list of dates and another list of date ranges I want to check them against. I already know how to mark my dates with a "yes" or "no" but is it possible to pick up additional information if the result is a "yes".
For instance. Column A is my list of dates I want to check

A
01/01/14
20/01/14
05/02/14
09/03/14
08/05/14
10/05/14

I then have a list of date ranges which relate to various events

B              C          D
Start data    End date   reason
24/12/13      02/01/14   Christmas
20/01/14      20/01/14   Fred Birthday
01/03/14      14/03/14   Holiday
10/05/14      10/05/14   Anniversary

Using the formula
=IF(AND(A2>=MIN(B1:C6),A2<=MAX(B1:C6)),"yes","no")

Can tell me for each of my dates in column A whether they fall within any of the date ranges with a yes of no, but I would like, to return the reason code from column D relating to the date match.
So the results would look like this:

A            B
01/01/14     Christmas
20/01/14     Fred Birthday
05/02/14
09/03/14     Holiday
08/05/14
10/05/14     Anniversary

I hope this is possible without using VBA?
Thanks

A: A very dumb way to do this will be making use of the else clause in the IF statement. The basic idea is for every field in A, check against every B and C, if matched, return D, otherwise Continue.
E.g.
 A             B              C          D
01/01/14    24/12/13      02/01/14   Christmas
            20/01/14      20/01/14   Fred Birthday
            01/03/14      14/03/14   Holiday
            10/05/14      10/05/14   Anniversary

=IF(AND(A1>=B1,A1<=C1),D1,
    IF(AND(A1>=B2,A1<=C2),D2,
      IF(AND(A1>=B3,A1<=C3),D3
         ...so on
      )
    )
  )

The above will return Christmas. The indentations are just for better understanding here...


text:
Q: Strange results of typeof operator on DOM node element (angular 1) I have a question regarding typeof DOM node.
Is that ok that Safari 5.1.7 on Windows return "function"?
typeof document.getElementsByTagName('head') === "function",

but on chrome
typeof document.getElementsByTagName('head') === "object"

This causes Angular 1 to break down on getting "jqLite" element:
jqLite(document.getElementsByTagName('head')) === Object[0]

as there are check in angular.js 1.6.1:
function JQLite(element) {
  //...
  if (argIsString) {
    jqLiteAddNodes(this, jqLiteParseHTML(element));
  } else if (isFunction(element)) {
    //it returns true
    jqLiteReady(element);
  } else {
    jqLiteAddNodes(this, element);
  }

So basically my question is it suppose that isFunction called with dom element parameter return true? Is it Safari bug or not?


text:
Q: "Invalid snapshot time" error without table decorator usage We got an error that {"message":"Invalid snapshot time 1472342794519, unable to read before 1472342794785","reason":"invalid"}. Other QA describes that such an error happens when table decorators' parameters are invalid, however, our query does not have table decorators.
The query uses TABLE_DATE_RANGE, but its arguments are date timestamp, so the lower digits must be 0s, not like that in the above error.
Retrying the same query succeeded.
I can provide the job ID, but because it includes internal information of our company. I apologize that I cannot directly write it here.

A: The tables that the TABLE_DATE_RANGE wildcard evaluates to are resolved as of the time of the start of the query. Looking at the timestamps, it looks like the table was deleted right after the job started execution. This causes the table resolution to throw that error.


text:
Q: How to build a HATEOAS link when using a model attribute? I have a Spring @RestController producing application/hal+json. Normally I would return a Resource with Links created by ControllerLinkBuilder. When I use @RequestParam for all query parameters passed one by one to the mapped method this works perfectly.
For a search endpoint with multiple filtering options I created a POJO containing all options as properties and Spring automatically puts all matching query parameters into that object, cool. I can even do bean validation on that object if needed:
@GetMapping("objects")
Resource<?> fetchObjects(@Validated Query query) {
  ...
  return new Resource(..., linkTo(methodOn(getClass()).fetchObjects(query));
}

But the link builder does not do the reverse mapping and so no query parameters are added.
Is there any elegant way without replacing the query object by all of its members in the signature? The only way I found so far is (a little hacky from my point):
private Link createQueryLink(Query query) {
   UriComponentsBuilder link = linkTo(methodOn(getClass()).fetchObjects(query))
    .toUriComponentsBuilder();
  Optional.ofNullable(query.getFoo()).ifPresent(foo -> link.queryParam("foo", foo));
  ...
  return new Link(link.build().toUriString(), Link.REL_SELF);
}

PS: I am using Spring Boot 1.5.7.RELEASE


text:
Q: any css after this code not working , what is the problem in this css code, only in firefox? Footer css after form's css is not working , what is the problem in this css code?
/*------------------------------------*\
    FORMS */

fieldset { padding: 10px; border: 1px solid #ccc; margin-bottom: 1.5em; }
label { display: block; cursor: pointer; }
    label:after { content:\": "; }
    label::after { content:\": "; }
input,textarea { font-family: inherit; font-size: 1em; line-height: 1.5; }
[placeholder] { cursor: pointer; }
    [placeholder]:active,[placeholder]:focus { cursor: text; }
fieldset > :last-child { margin: 0; }

footer {background:red; height:200px; width:200px}

jSfiddle http://jsfiddle.net/Aw239/
in jsfiddle example footer should be red background.

A: At least firefox Doesnt seem to understand this label:after { content:\": "; } i have no idea whats going on here but all i know is that it is the culprit. I've never actually used content properly.
But, remove those lines and everything runs smoothly.. ( OR reformat those two lines as Kyle showed and it should do it. )
Seems like it doesnt like to have closing semicolons in the same row with everything else
http://jsfiddle.net/Aw239/3/
Or.. get rid of the \'s ?

A: I formatted your CSS a bit and it seems to work in my FF5. http://jsfiddle.net/Aw239/2/

A: It is red. Are you using IE8? Because you'll need to use the HTML5 shim if you want to style HTML5 elements.
Does this work for you?


text:
Q: Counting coins using OpenCV I have been trying to develop a program - written with C++ and using OpenCV -which counts the overall value of coins shown in some image.
I should note that I am new to the opencv platform.
In order to achieve this goal, as far as I understand - there has to be a use of  the Hough transform to detect the ratio of the coins. I found this code example on the OpenCV site, but I can't put a value for the coins.
Here is what I have done so far.
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>

using namespace std;
using namespace cv;
namespace
{

    const std::string windowName = "Coins detection";
    const std::string cannyThresholdTrackbarName = "Canny threshold";
    const std::string accumulatorThresholdTrackbarName = "Accumulator Threshold";

    const int cannyThresholdInitialValue = 41;
    const int accumulatorThresholdInitialValue = 87;
    const int maxAccumulatorThreshold = 200;
    const int maxCannyThreshold = 255;

    void HoughDetection(const Mat& src_gray, const Mat& src_display, int cannyThreshold, int accumulatorThreshold)
    {

        std::vector<Vec3f> circles;

        HoughCircles( src_gray, circles, HOUGH_GRADIENT, 1, src_gray.rows/8, cannyThreshold, accumulatorThreshold, 0, 0 );

        Mat display = src_display.clone();
        for( size_t i = 0; i < circles.size(); i++)
        {
            Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
            int radius = cvRound(circles[i][2]);

            circle( display, center, 3, Scalar(0,255,0), -1, 8, 0 );

            circle( display, center, radius, Scalar(0,0,255), 3, 8, 0 );

        }

        imshow( windowName, display);
    }
}

int main(int argc, char** argv)
{
    Mat src, src_gray;

    String imageName("c:\\moedas.jpg");
    if (argc > 1)
    {
       imageName = argv[1];
    }
    src = imread( imageName, IMREAD_COLOR );

    if( src.empty() )
    {
        std::cerr<<"Invalid input image\n";

        return -1;
    }

    cvtColor( src, src_gray, COLOR_BGR2GRAY );

    GaussianBlur( src_gray, src_gray, Size(9, 9), 2, 2 );

    int cannyThreshold = cannyThresholdInitialValue;
    int accumulatorThreshold = accumulatorThresholdInitialValue;

    namedWindow( windowName, WINDOW_AUTOSIZE );
    createTrackbar(cannyThresholdTrackbarName, windowName, &cannyThreshold,maxCannyThreshold);
    createTrackbar(accumulatorThresholdTrackbarName, windowName, &accumulatorThreshold, maxAccumulatorThreshold);

    char key = 0;
    while(key != 'q' && key != 'Q')
    {

        cannyThreshold = std::max(cannyThreshold, 1);
        accumulatorThreshold = std::max(accumulatorThreshold, 1);

        HoughDetection(src_gray, src, cannyThreshold, accumulatorThreshold);

        key = (char)waitKey(10);
    }

    return 0;
}

A: The code you have so far only segments circle shapes in an input image. This is just the first step to count the coins. There are many ways to perform that task, ranging from simple contour counting techniques to complicated deep learning, and the explanation of such techniques is too broad and large in scope to put efficiently and concisely in an SO answer. However, here are some coin detectors/counter implementations/tutorials that you can check:

*

*Implementation 1 in Python. This is the best of the list, although the code file is larger than yours, not too hard to port to C++. It has the best detection/counting performance but deals with Neural Networks, specifically, a Multilayer Perceptron.

*Implementation 2 in Python. This is a very small code file, nearly as large as yours and has no idiomatic Python code, porting it to C++ is a no brainer, you should start here. This implementation uses mere contour counting with the aid of the Canny edge detector.

*Tutorial 1 in C++. A simple tutorial in C++, but only serves introductory purposes, the implementations listed above are the real thing.


text:
Q: Photocurrent in photodiode smaller than expected I have a question regarding the usage of the phototransistor SFH 203 P, which I want to use for a project, where I need a small fall- and rise-time. The data sheet (I think) implies that if I use the photodiode as follows (in reverse bias) I should get a photocurrent of about 800µA (see page 3 under "Rise and fall time of the photocurrent").

simulate this circuit – Schematic created using CircuitLab
But unfortunately I only measure 2.3µA with bright room lighting. Did I misinterpret the datasheet, use the wrong circuit or is my photodiode maybe broken?

A: Actually, that sounds about right. I don't know where you got the 800 µA figure from — both the table and the graph indicate much less.
"Bright office lighting" is about 500 lux. The sensitivity of the SFH 203 P is specified as minimum 5 µA, typical 9.5 µA @ 1000 lux.
The graph in the middle of page 4 agrees with this.
The rise and fall times were measured with a much brighter pulse of light than room lighting -- probably a laser or flashtube. Interestingly, none of the graphs go up that far, implying that that would not be a "normal" regime of operation.

A:
I should get a photocurrent of about 800µA (see page 3 under "Rise and fall time of the photocurrent").

From the datasheet:
Photosensitive area: 1 mm^2
Sensitivity: 0.86 A/W (at 850nm), about 0.5 in the visible.
To get 800uA in the visible, you would need 1.6mW.  From a 1x1 mm area, that is 1600 w per square meter, or about 2.5 times as bright as noon-time sunlight.  No way you're going to get that kind of current indoors without an arc lamp or a laser beam.
If you need more current, get an avalanche photodiode (about 100x more current) or a silicon photomultiplier (about 1,000,000x more current).  They're actually not that much more expensive than the diode you have, although bias voltage will be 30-40v.


text:
Q: Where is the implementation of abi::__cxa_demangle in libstdc++ GNU's libstdc++ provides the function abi::__cxa_demangle. The declaration of this function can be found in gcc / libstdc++-v3 / libsupc++ / cxxabi.h (code repository here)
I am interested in reviewing the implementation of this function but I am unable to find a definition in the aforementioned repository. There is one definition in gcc / libiberty but, from what I can gather, this library is only used in a few GNU programs and mostly decommissioned (or so claims Wikipedia).
I managed to dig up some old discussion threads from 2003 that mention replacing the libstdc++-v3 demangler with the libiberty demangler which further confused me.
Here are my questions:

*

*Does a libstdc++-v3 demangler still exist (as mentioned in the thread linked to above)?

*Is the libiberty demangler used in libstdc++-v3?

*Where can I find the implementation of abi::__cxa_demangle


text:
Q: Show underlying div part Jsfiddle
I have two divs, one big and red, and one smaller, blue, part in the red one and part outside of it.
When hovered, they are shown by changing their opacity to 1. I put the red one on top and the blue one behind.
When I hover the red one it is fully displayed. When I hover the blue one, I have to hover over the part that is outside of the red one to fully display it.
What I want is, when I hover over the blue part outside the red one, to show only this part and not the part that is inside(under) the red one. How can I do this?

$(".blue, .red").on({

    mouseenter: function () {
        $('.squares > div').css('opacity', '0');
        $(this).css('opacity', '1');
    },
    mouseleave: function () {
        $(this).css('opacity', '0');
    }
});
.red {
    background-color:red;
    width:200px;
    height:200px;
    position:absolute;
    opacity:0;
     z-index:2;
}
.blue {
    background-color:blue;
    width:100px;
    height:100px;
    position:absolute;

    top:150px;
    left:50px;
    opacity:0;
}

It should look like this: http://s14.postimg.org/rqzujr9xt/Untitled.png Note that I can't split the blue part nor have a smaller one outside only. A section of the blue part MUST be under the red one. And I don't know how big it will be.

A: do you want this?
https://jsfiddle.net/0qfxw8z8/38/
I created an illusion by changing bg color of red div to white (same as bg color of parent div)
UPDATE: a small bug was fixed, now the red div disappears on mouseleave, confirm it by seeing the border I have added to the red div
https://jsfiddle.net/0qfxw8z8/45/

A: https://jsfiddle.net/0qfxw8z8/37/
HTML:

CSS:
.red {
    background-color:red;
    width:200px;
    height:200px;
    position:absolute;
    opacity:0.1;
}
.blue {
    background-color:transparent;
    width:100px;
    height:100px;
    position:absolute;
    top:158px;
    left:50px;
}

.blue > .upper, .blue > .lower {
    opacity: 0.1;
    height: 50px;
    background-color: blue;
}

.blue > .lower:hover, .red:hover {
    opacity: 1;
}

Here you are what you asked for:

*

*when you HOVER RED div:  shows whole red div

*when you HOVER BLUE div: shows only the bottom (non-covered) part

A: JSFiddle (Updated 4.0)

Content

.js-main-container {
    background-color:red;
    width:200px;
    height:200px;
    position:absolute;
    z-index:2;
}
.js-show-content {
    background-color: black;
    width:100px;
    height:100px;
    position:absolute;

    top:150px;
    left: 0;
    right: 0;
    margin: 0 auto;
    opacity:0.1;
    z-index: 3;
}

.js-hidden-container {
    color: #fff;
    display: none;
    background-color:blue;
    width:100px;
    position:absolute;

    top:100%;
    left:0;
    right: 0;
    margin: 0 auto;
}

var oShowContent = $(".js-show-content");
var oHiddenContainer = $(".js-hidden-container");
var oMainContainer = $(".js-main-container");

oShowContent.on({
    mouseenter: function () {
        oHiddenContainer.show();
    },
    mouseleave: function () {
        oHiddenContainer.hide();
    }
});

JSFiddle (Updated 3.0)

A: try this one
$(".blue, .red").on({

    mouseenter: function() {

        if ($(this).attr('class') == 'red') {

            $('.squares .red').css('background-color', 'red');
            $('.squares > div').css('opacity', '0');
            $(this).css('opacity', '1');

        } else if ($(this).attr('class') == 'blue') {

            $('.squares .red').css('opacity', '1');
            $('.squares .red').css('background-color', 'white');
            $(this).css('opacity', '1');

        }

    },
    mouseleave: function() {
        $(this).css('opacity', '0');
    }
});

here is the fiddle

A: Try this,
Demo
I just add the z-index:-1 of .blue and background-color:"white" of .squares.

A: You should include third block to your code. And animate it like other part. JSfiddle here

$(".blue, .red").on({
    mouseenter: function () {
        $('.squares > div').css('opacity', '0');
        $(this).css('opacity', '1');
    },
    mouseleave: function () {
        $(this).css('opacity', '0');
    }
});

$(".blue-on-red, .red").on({
    mouseenter: function () {
        $('.squares > div').css('opacity', '0');
        $(this).css('opacity', '1');
    },
    mouseleave: function () {
        $(this).css('opacity', '0');
    }
});
.red {
    background-color:red;
    width:500px;
    height:500px;
    position:absolute;
    z-index:1;
    opacity: 0;
}

.blue-on-red {
    background-color:blue;
    width:300px;
    height:300px;
    position:absolute;
    top:250px;
    z-index: 2;
    left:100px;
    opacity: 0;
}

.blue {
    background-color:blue;
    width:300px;
    height:40px;
    position:absolute;
    top:505px;
    z-index: 3;
    left:100px;
    opacity: 0;
}

A:

$(".blue, .red").on({

    mouseenter: function () {
        $('.squares > div').css('opacity', '0');
        $(this).css('opacity', '1');
    },
    mouseleave: function () {
        $(this).css('opacity', '0');
    }
});
.red {
    background-color:red;
    width:500px;
    height:500px;
    position:absolute;

     z-index:2;
}
.blue {
    background-color:blue;
    width:300px;
    height:300px;
    position:absolute;

    top:250px;
    left:100px;

}

As you can see here the blue part is down from the red Squere and its working when you hover this part.

A: Here's an updated fiddle of working solution as I understand your problem.
https://jsfiddle.net/0qfxw8z8/1/
Your problem was in the use of 'this' which only animated the opacity of the div that the mouse was entering. But you actually want to animate the opacity of all the divs.
Updated JS
$(".red").on({

    mouseenter: function () {
        //$('.squares > div').css('opacity', '0');
        $('.square').css('opacity', '1');
    },
    mouseleave: function () {
        $('.square').css('opacity', '0');
    }
});

Updated HTML


text:
Q: I'm getting some of these prints in my console while running my application from Xcode 9.4 in my iPhone 7,8 with iOS 10,11 the 'GoogleMaps' pods are all updated so where is this bug still shows
the Error is : CoreData: Failed to load optimized model at path '/var/mobile/Containers/Bundle/Application/0000000B-BDBC-0000-000B-0000FB00000B/GoogleMaps.bundle/GMSCacheStorage.momd/StorageWithTileProto.omod'


text:
Q: Where to call an Ajax Request that would Happen before Render? I have a page that has a dropdown of categories and once a user chooses a choice from the dropdown they go to another page.
However sometimes there is only 1 category and I want to skip the dropdown selection and go right to the second page.
However I am getting the categories by an ajax call so I don't know how many catgories are coming back till the ComponentDidMount happens.
If there is only 1 choice I then do a route change(in the ComponentDidMount ) and send them to the second page automatically.
However this leads to a flicker on the ui(first tries to render the first page but once it mounts the code to go to the next page gets hit).
Is there another area I can do this kind of check?

A: How about just showing a loader while result is being fetched from server. That way user wouldn't see any flicker on screen.
componentDidMount() {
  fetchCategories().then((categories) => {
     if (categories.length === 1) {
       // Redirect
     }
     else {
       this.setState({ categories })
     }
  })
}

render() {
  if (!this.state.categories) {
      // Show loader while categories are being fetched.
      return <Loader />
  }
  else if(this.state.categories.length > 1) {
     // Show content if categories are more
     return <Categories />
  }
}

A: You could add a loading state/indicator before rendering/re-routing.
When the ajax call is complete set the loaded state/prop after which either the dropdown will be rendered or page re-routed without a flicker.
Sample without redux/global state management
//****************************************************************************/

constructor(props) {

    super(props)

    this.state = {
        categoriesLoaded: false
    }
}

//****************************************************************************/

componentDidMount() {

    this.props.fetchCategories().then(response => {

        this.setState({ categoriesLoaded: true })

    }).catch(e => {

        ...handle
    })
}

//****************************************************************************/

render() {

    return (
        {this.state.categoriesLoaded && (

            handle list display or reroute
        )}
    )
}


text:
Q: Calculate $\int_{0}^{1} \int_{0}^{1} \frac{1}{\sqrt{|x-y|}} \mathrm{d}x\mathrm{d}y$ I am asked to evaluate de following integral:
$$\int_{0}^{1} \int_{0}^{1} \frac{1}{\sqrt{|x-y|}} \mathrm{d}x\mathrm{d}y$$

My attempt.
Note that
$$
    \frac{x-y}{|x-y|} = 1, \text{ if } x-y > 0
    \qquad\qquad
    \text{ and }
    \qquad\qquad
    \frac{y-x}{|x-y|} = 1, \text{ if } x-y < 0
$$
Thus,
\begin{align*}
    &\int_{0}^{1} \int_{0}^{1} \frac{1}{\sqrt{|x-y|}} \mathrm{d}x \mathrm{d}y
    %
    = \int_{0}^{1} \int_{0}^{1} \frac{1}{\sqrt{|x-y|}} \frac{x-y}{|x-y|} \mathrm{d}x \mathrm{d}y \\[5pt]
    %
    &\implies \int \frac{1}{\sqrt{|x-y}} \frac{x-y}{|x-y|} \mathrm{d}x
    %
    = \int \frac{1}{\sqrt{u}} \mathrm{d}u
    %
    = 2u^{\frac{1}{2}} + k \qquad\qquad \left( u = |x-y|, \, \mathrm{d}u = \frac{x-y}{|x-y|} \mathrm{d}x\right)\\[5pt]
    %
    &\implies \int_{0}^{1} \frac{1}{\sqrt{|x-y|}} \frac{x-y}{|x-y|} \mathrm{d}x
    %
    = 2 \sqrt{|x-y|} \Big|_{0}^{1}
    %
    = 2 \sqrt{|1-y|} - 2 \sqrt{|-y|}
    %
    = 2 \left( \sqrt{1-y} - \sqrt{y} \right)\\[5pt]
    %
    &\implies 2\int_{0}^{1} \left[ \sqrt{1-y} - \sqrt{y} \right] \mathrm{d}y
    %
    = -\tfrac{4}{3} \left[ (1-y)^{3/2}
        + y^{3/2} \right] \Big|_{0}^{1}
    %
    = 0
\end{align*}
According to WolframAlpha this answer is incorrect and the actual value should be $\frac{8}{3}$.
Moreover, throwing the indefinite integral with respect to x to Wolfram yields $\sqrt{y-x}(\operatorname{sgn}(x-y)-1) + \sqrt{x-y}(\operatorname{sgn}(x-y)+1)$. For this last result I have no clue on how to get there...
Also, integration in the given bounds should not be a problem since removing the line y=x (where the function is not determined) is a set of length 0.

A: Your very first step contains an error, since multiplication by $(x-y)/|x-y|$ on the unit square will cause the sign of the integrand to be reversed for the region $x < y$.  This is why you get $0$.
Instead, recognize the symmetry of the integrand about $x = y$ and compute the half integral $$\int_{y=0}^1 \int_{x=y}^1 \frac{1}{\sqrt{|x-y|}} \, dx \, dy = \int_{y=0}^1 \int_{x=y}^1 \frac{1}{\sqrt{x-y}} \, dx \, dy = \int_{y=0}^1 \int_{u=0}^{1-y} \frac{1}{\sqrt{u}} \, du \, dy.$$


text:
Q: Convert PDFs to Images using pdf2image in python I have a folder contains files of type PDF, PNG, and JPEG. I'm trying to convert PDF files to images and this is the code I've tried:
from pdf2image import convert_from_path, convert_from_bytes

from pdf2image.exceptions import (
 PDFInfoNotInstalledError,
 PDFPageCountError,
 PDFSyntaxError
)

images = convert_from_path('41117 UIs in eng.pdf')

for i, image in enumerate(images):
    fname = 'image'+str(i)+'.jpg'
    image.save(fname, "JPEG")

Clearly this code is only for a single pdf file and I want to transfer the code to serve several pdf files that are mixed with other file types in the same folder.
please help.

A: You could try something like this (this script finds pdf files in the same directory with your python program):
 import os

from pdf2image import convert_from_path, convert_from_bytes

from pdf2image.exceptions import (
    PDFInfoNotInstalledError,
    PDFPageCountError,
    PDFSyntaxError
)

# get all pdf files from directory
pdf_files = [filename for filename in os.listdir(
    '.') if filename.endswith('.pdf')]

for pdf_file in pdf_files:
    images = convert_from_path(pdf_file)

    print(pdf_file)

    for i, image in enumerate(images):
        fname = pdf_file+'_image'+str(i)+'.jpg'
        image.save(fname, "JPEG")


text:
Q: How to save images using filename of data from CSV file in R? I have a CSV file called data which contains latitude and longitude coordinates. A sample:
Lat    Lon
13.3   100.3
23.2   90.3

Using an API key, I can retrieve Google Street View images using these coordinates which are saved on my computer with the googleway package. They are saved as .jpeg files.
The code below loops through the coordinates in data, gets the associated image and saves them as e.g. image_00001.jpeg, image_00002.jpeg, etc.
jpeg('image_%05d.jpeg')
purrr::map2(data$Lat, data$Lon, function)
dev.off()

However, instead of saving these files as e.g. image_00001.jpeg, I want the filename to be the coordinates that correspond to the image. So for instance, if the image is from the 13.3, 100.3 coordinate pair/row from data, I want to save the file as 13.3-100.3.jpeg.
Does anybody know how to do this?

A: As Andrew Gustar stated in his comment. You can use paste in your loop to generate rowwise filenames of your data.
data <- data.frame(Lat = c(13.3, 23.2),
                   Lon = c(100.3, 90.3))
data
   Lat   Lon
1 13.3 100.3
2 23.2  90.3

sapply(1:nrow(data), function(x) return(paste0(paste(data[x,], collapse = "-"), ".jpeg")))
[1] "13.3-100.3.jpeg" "23.2-90.3.jpeg"


text:
Q: Cannot post question - 'Your post appears to contain code that is not properly formatted as code' I am trying to post a question to Stack Overflow (and also relevant on a few other sites) but am met with the following message:

Your post appears to contain code that is not properly formatted as code. Please indent all code by 4 spaces using the code toolbar button or the CTRL+K keyboard shortcut. For more editing help, click the [?] toolbar icon.

I'm not entirely sure why given that I've followed the formatting where I believe it is required. My question is formatted as follows:

I would like to {do something with this data}:

Country
Year
LifeExp
GDP

Chile
2000
77.3
7.79e+10

Chile
2000
77.3
7.79e+10

Chile
2000
77.3
7.79e+10

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

Zimbabwe
2013
58.0
1.55e+10

Zimbabwe
2014
59.2
1.59e+10

Zimbabwe
2015
60.7
1.63e+10

Ideally, I would like to {do more stuff with this data}.
gdp_data['GDP%'] = 0
gdp_country = gdp_data[gdp_data['Country'] == 'Chile']
gdp_data['GDP%'] = gdp_country['GDP'].pct_change()

Is there a (correct and) more efficient way?