问:
p values for random effects in lmer
I am working on a mixed model using lmer function. I want to obtain p-values for all the fixed and random effects. I am able to obtain p-values for fixed effects using different methods but I haven't found anything for random effects. Whatever method I have found on the internet is to make a null model for the same and then get the p-values by comparison. Can I have a method through which I don't need to make an another model?
My model looks like:</p>
```<code>mod1 = lmer(Out ~ Var1 + (1 + Var2 | Var3), data = dataset)
</code>```

答:
You must do these through model comparison, as far as I know. The lmerTest package has a function called step, which will reduce your model to just the significant parameters (fixed and random) based on a number of different tests. The documentation isn't entirely clear on how everything is done, so I much prefer to use model comparison to get at specific tests.

For your model, you could test the random slope by specifying:

```<code>mod0 <- lmer(Out ~ Var1 + (1 + Var2 | Var3), data = dataset, REML=TRUE)
mod1 <- lmer(Out ~ Var1 + (1 | Var3), data = dataset, REML=TRUE)
anova(mod0, mod1, refit=FALSE)
</code>```

This will show you the log likelihood test and test statistic (chi-square distributed). But you are testing two parameters here: the random slope of Var2 and the covariance between the random slopes and random intercepts. So you need a p-value adjustment:

```<code>1-(.5*pchisq(anova(mod0,mod1, refit=FALSE)$Chisq[[2]],df=2)+
   .5*pchisq(anova(mod0,mod1, refit=FALSE)$Chisq[[2]],df=1))
</code>```

More on those tests here or here.

Title: p values for random effects in lmer

Body:
I am working on a mixed model using lmer function. I want to obtain p-values for all the fixed and random effects. I am able to obtain p-values for fixed effects using different methods but I haven't found anything for random effects. Whatever method I have found on the internet is to make a null model for the same and then get the p-values by comparison. Can I have a method through which I don't need to make an another model?
My model looks like:

mod1 = lmer(Out ~ Var1 + (1 + Var2 | Var3), data = dataset)

Body:
You must do these through model comparison, as far as I know. The lmerTest package has a function called step, which will reduce your model to just the significant parameters (fixed and random) based on a number of different tests. The documentation isn't entirely clear on how everything is done, so I much prefer to use model comparison to get at specific tests.

For your model, you could test the random slope by specifying:

mod0 <- lmer(Out ~ Var1 + (1 + Var2 | Var3), data = dataset, REML=TRUE)
mod1 <- lmer(Out ~ Var1 + (1 | Var3), data = dataset, REML=TRUE)
anova(mod0, mod1, refit=FALSE)

This will show you the log likelihood test and test statistic (chi-square distributed). But you are testing two parameters here: the random slope of Var2 and the covariance between the random slopes and random intercepts. So you need a p-value adjustment:

1-(.5*pchisq(anova(mod0,mod1, refit=FALSE)$Chisq[[2]],df=2)+
   .5*pchisq(anova(mod0,mod1, refit=FALSE)$Chisq[[2]],df=1))

More on those tests here or here.


来源: stackexchange

问:
Interleaving array_agg in postgres
I have a postgres query in which I want to interleave my array_agg statements :

```<code>SELECT client_user_id,
       (array_agg(question), array_agg(client_intake_question_id), array_agg(answer)) as answer
FROM client_intake_answer
LEFT OUTER JOIN client_intake_question
ON       client_intake_question.id = client_user_id
GROUP BY client_user_id
</code>```

Gives me the following:

```<code> 5 | ("{""Have you ever received counselling?"",""Have you ever received counselling or mental health support in the past?""}","{1,2}","{yes,no}")
</code>```

I would like the results to be:

```<code>  5 | ("{""Have you ever received counselling?", 1, "yes"",""Have you ever received counselling or mental health support in the past?", 2, "no""}"
</code>```

How do I do this?

答:
I've set up a small example similar to yours:

```<code>create table answers(user_id int, question_id int, answer varchar(20));
create table questions(question_id int, question varchar(20));

insert into questions values
(1, 'question 1'),
(2, 'question 2');

insert into answers values
(1, 1, 'yes'),
(1, 2, 'no'),
(2, 1, 'no'),
(2, 2, 'yes');
</code>```

```<code>select user_id, array_agg(concat(questions.question, ',',  questions.question_id::text, ',', answers.answer))
from   questions
inner join answers
on     questions.question_id = answers.question_id
group by answers.user_id
</code>```

```
user_id | array_agg
------: | :-------------------------------------
      1 | {"question 1,1,yes","question 2,2,no"}
      2 | {"question 1,1,no","question 2,2,yes"}
```

dbfiddle here

ContentLicense: CC BY-SA 3.0

Title: Interleaving array_agg in postgres

Body:
I have a postgres query in which I want to interleave my array_agg statements :

SELECT client_user_id,
       (array_agg(question), array_agg(client_intake_question_id), array_agg(answer)) as answer
FROM client_intake_answer
LEFT OUTER JOIN client_intake_question
ON       client_intake_question.id = client_user_id
GROUP BY client_user_id

Gives me the following:

 5 | ("{""Have you ever received counselling?"",""Have you ever received counselling or mental health support in the past?""}","{1,2}","{yes,no}")

I would like the results to be:

  5 | ("{""Have you ever received counselling?", 1, "yes"",""Have you ever received counselling or mental health support in the past?", 2, "no""}"

How do I do this?

Body:
I've set up a small example similar to yours:

create table answers(user_id int, question_id int, answer varchar(20));
create table questions(question_id int, question varchar(20));

insert into questions values
(1, 'question 1'),
(2, 'question 2');

insert into answers values
(1, 1, 'yes'),
(1, 2, 'no'),
(2, 1, 'no'),
(2, 2, 'yes');

select user_id, array_agg(concat(questions.question, ',',  questions.question_id::text, ',', answers.answer))
from   questions
inner join answers
on     questions.question_id = answers.question_id
group by answers.user_id

user_id | array_agg
------: | :-------------------------------------
      1 | {"question 1,1,yes","question 2,2,no"}
      2 | {"question 1,1,no","question 2,2,yes"}

dbfiddle here


问:
Undefined method `html_safe?' error when using rails-ckeditor with formtastic
I'm trying to get the rails-ckeditor gem to work. I followed the instructions on the README.
But I get this error

```<code>undefined method `html_safe?' for #<String:0xb6b6d080>
</code>```

This is my formtastic form code:

```<code><%= f.input :content, :as => :ckeditor %>
</code>```

Any ideas? Thanks!

UPDATE
I'm using Rails 2.3.8. And here's the stack trace.

```<code>  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/safe_buffer.rb:6:in `<<'
  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/view_helper.rb:52:in `ckeditor_textarea'
  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/formtastic.rb:9:in `send'
  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/formtastic.rb:9:in `ckeditor_input'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:1281:in `send'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:1281:in `inline_input_for'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:109:in `send'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:109:in `input'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:108:in `map'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:108:in `input'
  /home/shreyas/repos/citymgmt/app/views/articles/_form.html.erb:4
  /home/shreyas/repos/citymgmt/app/views/articles/_form.html.erb:2:in `_run_erb_app47views47articles47_form46html46erb_locals_form_object'
  /home/shreyas/repos/citymgmt/app/views/articles/_form.html.erb:1:in `_run_erb_app47views47articles47_form46html46erb_locals_form_object'
  /home/shreyas/repos/citymgmt/app/views/articles/new.html.erb:10
  /home/shreyas/repos/citymgmt/app/views/articles/new.html.erb:3:in `_run_erb_app47views47articles47new46html46erb'
</code>```

答:
Are you running an earlier version of Rails than 3.0.0? You'll want to install the rails_xss plugin which provides this functionality. In Rails 3, this comes standard.

I would advise, if at all possible, to upgrade to Rails 3 as soon as you are able.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to get the rails-ckeditor gem to work. I followed the instructions on the README.
But I get this error

undefined method `html_safe?' for #<String:0xb6b6d080>

This is my formtastic form code:

<%= f.input :content, :as => :ckeditor %>

Any ideas? Thanks!

UPDATE
I'm using Rails 2.3.8. And here's the stack trace.

  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/safe_buffer.rb:6:in `<<'
  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/view_helper.rb:52:in `ckeditor_textarea'
  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/formtastic.rb:9:in `send'
  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/formtastic.rb:9:in `ckeditor_input'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:1281:in `send'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:1281:in `inline_input_for'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:109:in `send'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:109:in `input'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:108:in `map'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:108:in `input'
  /home/shreyas/repos/citymgmt/app/views/articles/_form.html.erb:4
  /home/shreyas/repos/citymgmt/app/views/articles/_form.html.erb:2:in `_run_erb_app47views47articles47_form46html46erb_locals_form_object'
  /home/shreyas/repos/citymgmt/app/views/articles/_form.html.erb:1:in `_run_erb_app47views47articles47_form46html46erb_locals_form_object'
  /home/shreyas/repos/citymgmt/app/views/articles/new.html.erb:10
  /home/shreyas/repos/citymgmt/app/views/articles/new.html.erb:3:in `_run_erb_app47views47articles47new46html46erb'


问:
Visual Studio Dialog Editor Tab (called Toolbox) Gone
I am working with Visual Studio Ultimate 2013.

I would like to add controls to a dialog-box via the Dialog Editor Tab.

It usually appears in my IDE on the left side of the Resource View pane, as a small tag labeled Toolbox which I can expand by clicking on.

However, under some circumstances it simply disappears (thank you, Microsoft, for this lovely feature).

I'm not sure about the exact scenario, but it happened after I added a new dialog-box.

Can you please help me recover this?

I tried TOOLS --> Customize and TOOLS --> Options, but was unable to trace it.

Thank you.

答: try view -> toolbox, or Ctrl + W,X</p>

Body: try view -> toolbox, or Ctrl + W,X


问:
Creating a button in JQuery
I am trying to create some buttons in JQuery, and insert them into the existing html code. At the moment my code looks like this:
I did not know how to select the second section of the page, so i selected the first and then the next of it. It don't know if that is possible, please be gentle there.

EDIT: Section is not only the name of the section html tag here, but also the class name in the code. Thats why i tried to select it with a class selector.

```<code>var addsection = $(".Section").first();
addsection = addsection.next();

var buttonline2 = ("<div></div>");
buttonline2.addClass("Grid-full");
var button3 = ("<div>Show all!</div>");
button3.addClass("Button");
var button4 = ("<div>Hide all!</div>");
button4.addClass("Button");
buttonline2.add(button1);
buttonline2.add(button2);

button3.click(function () { // Show all
    addresses.show();
});

button4.click(function () { // Hide all
    addresses.hide();
});

addsection.append(buttonline2);
</code>```

The problem is that nothing is shown on my page. I dont know what i am doing wrong. On the forums and here on stackoverflow people kept telling to other questions that you simply need to append the part you want to have in your html. It does not show up in my html code either.
Please help :(

答:
your code is almost correct, please, follow this example:

var buttonline2 = $("
", {
  class: 'Grid-full'
});

var button3 = $("<button />", {
    text: 'Show All!',
    class: 'Button'
  })
  .click(function () { // Show all
    console.log('let\'s show them all');
  })
  .appendTo(buttonline2)
;

var button4 = $("<button />", {
    text: 'Hide All!',
    class: 'Button'
  })
  .click(function () { // Hide all
    console.log('let\'s hide them all');
  })
  .appendTo(buttonline2)
;

$('#result').append(buttonline2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div></code>```

Title: Creating a button in JQuery

Body:
I am trying to create some buttons in JQuery, and insert them into the existing html code. At the moment my code looks like this:
I did not know how to select the second section of the page, so i selected the first and then the next of it. It don't know if that is possible, please be gentle there.

EDIT: Section is not only the name of the section html tag here, but also the class name in the code. Thats why i tried to select it with a class selector.

var addsection = $(".Section").first();
addsection = addsection.next();

var buttonline2 = ("

");
buttonline2.addClass("Grid-full");
var button3 = ("
Show all!
");
button3.addClass("Button");
var button4 = ("
Hide all!
");
button4.addClass("Button");
buttonline2.add(button1);
buttonline2.add(button2);

button3.click(function () { // Show all
    addresses.show();
});

button4.click(function () { // Hide all
    addresses.hide();
});

addsection.append(buttonline2);

The problem is that nothing is shown on my page. I dont know what i am doing wrong. On the forums and here on stackoverflow people kept telling to other questions that you simply need to append the part you want to have in your html. It does not show up in my html code either.
Please help :(

Body:
your code is almost correct, please, follow this example:

var buttonline2 = $("<div />", {
  class: 'Grid-full'
});

var button3 = $("<button />", {
    text: 'Show All!',
    class: 'Button'
  })
  .click(function () { // Show all
    console.log('let\'s show them all');
  })
  .appendTo(buttonline2)
;

var button4 = $("<button />", {
    text: 'Hide All!',
    class: 'Button'
  })
  .click(function () { // Hide all
    console.log('let\'s hide them all');
  })
  .appendTo(buttonline2)
;

$('#result').append(buttonline2);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>


问:
Error:Cause: invalid stream header: 30303064
Project was running fine in emulator but suddenly after restarting the system I started getting error "Error:Cause: invalid stream header: 30303064". How do I resolve this?</p>

答: deleting .gradle folder from home and restarting again worked for me. After restarting the project .gradle file gets created automatically. </p>


问:
Form custom elements with factories
We are used to work with ZF2, but for our last project, we decided to start with ZF3.

Now I am facing a problem in the form creation.

What I want to do is to create a custom select populated with values retrieved from database.

What I did in ZF2 was creating a class extending a select, with the ServiceLocatorAwareInterface, like:

```<code>class ManufacturerSelect extends Select implements ServiceLocatorAwareInterface {

    public function init() {
        $manufacturerTable = $this->getServiceLocator()->get('Car\Model\ManufacturerTable');
        $valueOptions = [];
        foreach ($manufacturerTable->fetchAll() as $manufacturer) {
            $valueOptions[$manufacturer->getManufacturerId()] = $manufacturer->getName();
        }
        $this->setValueOptions($valueOptions);
    }

    public function getServiceLocator() {
        return $this->serviceLocator;
    }

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
        $this->serviceLocator = $serviceLocator;
    }

}
</code>```

Then, to use it in a form, it was enough to give the full name

```<code>$this->add(
    array(
        'name' => 'manufacturer_id',
        'type' => 'Car\Form\Element\ManufacturerSelect'
    )
);
</code>```

Now this is not possible anymore, since the service locator was removed and the use of factories is necessary, but I'm struggling to find how to do the same thing.

Keeping in mind to use factories, I tried this configuration in module.config.php:

```<code>'form_elements' => [
    'factories' => [
        'Car\Form\Element\ManufacturerSelect' => function ($services) {
            $manufacturerTable = $services->get('Car\Model\ManufacturerTable');
            return new ManufacturerSelect($manufacturerTable);
        },
        'Car\Form\CarForm' => function ($services) {
            $manufacturerTable = $services->get('Car\Model\ManufacturerTable');
            return new CarForm($manufacturerTable, 'car-form');
        }
    ]
]
</code>```

Result: factory of CarForm is always called, but factory of ManufacturerSelect is not.

A simple solution would be to populate the select directly in the form class, but I would prefer to use the factory for the element and reuse it everywhere I want, like I was doing in ZF2.

Does anyone already encountered this problem and found a solution?

答:
Do you add that element in "__construct" function? If so try "init"

EDIT:

First of all you don't need to create a custom select to fill in it via database. Just create a form with factory, fetch data from db in factory and pass to form. And use the data in form class as select's value options.

```<code>$this-add([
    'type' => Element\Select:.class,
    'name' => 'select-element'
    'options' => [
        'label' => 'The Select',
        'empty_option' => 'Please choose one',
        'value_options' => $this-dataFromDB
    ]
]);
</code>```

If you create form as:

```<code>new MyForm();
</code>```

Form Element Manager doesn't trigger custom elements' factories. But;

```<code>$container->get('FormElementManager')->get(MyForm::class);
</code>```

triggers custom elements' factories. Here's a working example. It's working on ZF3.

Config:

```<code>return [
    'controllers' => [
        'factories' => [
            MyController::class => MyControllerFactory::class
        ]
    ],
    'form_elements' => [
        'factories' => [
            CustomElement::class => CustomElementFactory::class,
            MyForm::class => MyFormFactory::class,
        ]
    ]
];
</code>```

don't forget to add 'Zend\Form' to application config's 'modules'.

Element:

```<code>class CustomElement extends Text
{
}
</code>```

Element Factory:

```<code>class CustomElementFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        echo 'element factory triggered';
        return new CustomElement();
    }
}
</code>```

Fieldset/Form:

```<code>class MyForm extends Form
{
    public function init()
    {
        $this
            ->add([
                'type'    => CustomElement::class,
                'name'    => 'name',
                'options' => [
                    'label' => 'label',
                ],
            ])
        ;
    }
}
</code>```

Fieldset/Form Factory:

```<code>class MyFormFactory implements FactoryInterface
{
        public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
        {
            echo 'form factory triggered';
            return new MyForm();
        }
}
</code>```

Controller's Factory:

```<code>class MyControllerFactory implements FactoryInterface
{
        public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
        {
            echo 'controller factory triggered';
            return new MyController(
                  $container->get('FormElementManager')->get(MyForm::class);
            );
        }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Form custom elements with factories

Body:
We are used to work with ZF2, but for our last project, we decided to start with ZF3.

Now I am facing a problem in the form creation.

What I want to do is to create a custom select populated with values retrieved from database.

What I did in ZF2 was creating a class extending a select, with the ServiceLocatorAwareInterface, like:

class ManufacturerSelect extends Select implements ServiceLocatorAwareInterface {

    public function init() {
        $manufacturerTable = $this->getServiceLocator()->get('Car\Model\ManufacturerTable');
        $valueOptions = [];
        foreach ($manufacturerTable->fetchAll() as $manufacturer) {
            $valueOptions[$manufacturer->getManufacturerId()] = $manufacturer->getName();
        }
        $this->setValueOptions($valueOptions);
    }

    public function getServiceLocator() {
        return $this->serviceLocator;
    }

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
        $this->serviceLocator = $serviceLocator;
    }

}

Then, to use it in a form, it was enough to give the full name

$this->add(
    array(
        'name' => 'manufacturer_id',
        'type' => 'Car\Form\Element\ManufacturerSelect'
    )
);

Now this is not possible anymore, since the service locator was removed and the use of factories is necessary, but I'm struggling to find how to do the same thing.

Keeping in mind to use factories, I tried this configuration in module.config.php:

'form_elements' => [
    'factories' => [
        'Car\Form\Element\ManufacturerSelect' => function ($services) {
            $manufacturerTable = $services->get('Car\Model\ManufacturerTable');
            return new ManufacturerSelect($manufacturerTable);
        },
        'Car\Form\CarForm' => function ($services) {
            $manufacturerTable = $services->get('Car\Model\ManufacturerTable');
            return new CarForm($manufacturerTable, 'car-form');
        }
    ]
]

Result: factory of CarForm is always called, but factory of ManufacturerSelect is not.

A simple solution would be to populate the select directly in the form class, but I would prefer to use the factory for the element and reuse it everywhere I want, like I was doing in ZF2.

Does anyone already encountered this problem and found a solution?

Body:
Do you add that element in "__construct" function? If so try "init"

EDIT:

First of all you don't need to create a custom select to fill in it via database. Just create a form with factory, fetch data from db in factory and pass to form. And use the data in form class as select's value options.

$this-add([
    'type' => Element\Select:.class,
    'name' => 'select-element'
    'options' => [
        'label' => 'The Select',
        'empty_option' => 'Please choose one',
        'value_options' => $this-dataFromDB
    ]
]);

If you create form as:

new MyForm();

Form Element Manager doesn't trigger custom elements' factories. But;

$container->get('FormElementManager')->get(MyForm::class);

triggers custom elements' factories. Here's a working example. It's working on ZF3.

Config:

return [
    'controllers' => [
        'factories' => [
            MyController::class => MyControllerFactory::class
        ]
    ],
    'form_elements' => [
        'factories' => [
            CustomElement::class => CustomElementFactory::class,
            MyForm::class => MyFormFactory::class,
        ]
    ]
];

don't forget to add 'Zend\Form' to application config's 'modules'.

Element:

class CustomElement extends Text
{
}

Element Factory:

class CustomElementFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        echo 'element factory triggered';
        return new CustomElement();
    }
}

Fieldset/Form:

class MyForm extends Form
{
    public function init()
    {
        $this
            ->add([
                'type'    => CustomElement::class,
                'name'    => 'name',
                'options' => [
                    'label' => 'label',
                ],
            ])
        ;
    }
}

Fieldset/Form Factory:

class MyFormFactory implements FactoryInterface
{
        public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
        {
            echo 'form factory triggered';
            return new MyForm();
        }
}

Controller's Factory:

class MyControllerFactory implements FactoryInterface
{
        public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
        {
            echo 'controller factory triggered';
            return new MyController(
                  $container->get('FormElementManager')->get(MyForm::class);
            );
        }
}


问:
Is it possible with Twilio to have an IVR menu and at the same time accept an extension?
For example, "Press 1 for X, 2 for Y, or dial an extension." Let's assume extensions start with 3.

If I accept three digits with a timeout, I won't get an instant response to 1 or 2. If I have 3 call another script that accepts the rest of the digits, the digits get lost if dialed too quickly (they're not buffered).

答:
Twilio developer evangelist here.

This is not possible without using the timeout as you already explained.

I'd recommend that you build it such that when the user dials 3 your initial action then returns a new <Gather> that expects the number of digits of an extension.


问:
Easeljs: pause an eventListener
Here is my code:

```<code>function main(){
/*.. stuff */
  ball.on("tick",collision);
  player1.on("pressmove",player1mov);
  field.addChild(player1);
  field.addChild(player2);
  field.addChild(ball);
  field.update();
}
function collision(){
    var a=player1.x-ball.x;
    var b=player1.y-ball.y;
    d=Math.sqrt((b*b)+(a*a));
    if(Math.round(d)<=50 ){
        document.getElementById("div").innerHTML="Collisione";
        vel();
        urto();
    }

}
</code>```

I can't figure out how to pause the event: 'ball.on("tick",collision)' and resume it after the urto() function to avoid the maximum call stack limit error. Can anyone help me?

答:
You can't pause the event listener firing, but you can pause the Ticker, and then check that property, or the paused property of the tick event.

From the Ticker documentation:

```<code> createjs.Ticker.addEventListener("tick", handleTick);
 createjs.Ticker.paused = true;
 function handleTick(event) {
     console.log(event.paused,
       createjs.Ticker.getTime(false),
       createjs.Ticker.getTime(true));
 }
</code>```

Title: Easeljs: pause an eventListener

Body:
Here is my code:

function main(){
/*.. stuff */
  ball.on("tick",collision);
  player1.on("pressmove",player1mov);
  field.addChild(player1);
  field.addChild(player2);
  field.addChild(ball);
  field.update();
}
function collision(){
    var a=player1.x-ball.x;
    var b=player1.y-ball.y;
    d=Math.sqrt((b*b)+(a*a));
    if(Math.round(d)<=50 ){
        document.getElementById("div").innerHTML="Collisione";
        vel();
        urto();
    }

}

I can't figure out how to pause the event: 'ball.on("tick",collision)' and resume it after the urto() function to avoid the maximum call stack limit error. Can anyone help me?

Body:
You can't pause the event listener firing, but you can pause the Ticker, and then check that property, or the paused property of the tick event.

From the Ticker documentation:

 createjs.Ticker.addEventListener("tick", handleTick);
 createjs.Ticker.paused = true;
 function handleTick(event) {
     console.log(event.paused,
       createjs.Ticker.getTime(false),
       createjs.Ticker.getTime(true));
 }


问:
Android ndk static linking to openssl failed with BIO_new_dgram undefined
I built libssl.a and libcryto.a. But when I want to link my.so to it, I got this error:

```<code>Error:(130) undefined reference to 'BIO_new_dgram'
</code>```

If I delete this call, I can compile it succeed.

Did I build the library of openssl in a wrong way?

BIO_new_dgram is in libcrypto.a:

```<code>nm libcrypto.a  | grep BIO_new_dgram
0000081c T BIO_new_dgram
</code>```

I configure Openssl  with:

```<code>./config shared --openssldir=$install_dir --prefix=$install_dir
</code>```

and link command:

```<code>/home/choury/bin/Android/android-sdk-linux/ndk-bundle/toolchains/llvm/prebuilt/l
inux-x86_64/bin/clang++  --target=aarch64-none-linux-android --gcc-toolchain=/ho
me/choury/bin/Android/android-sdk-linux/ndk-bundle/toolchains/aarch64-linux-andr
oid-4.9/prebuilt/linux-x86_64 --sysroot=/home/choury/bin/Android/android-sdk-lin
ux/ndk-bundle/platforms/android-21/arch-arm64 -fPIC -std=c++11 -Wall -fPIC -ggdb
 -O0  -Wl,--build-id -Wl,--warn-shared-textrel -Wl,--fatal-warnings -Wl,--no-und
efined -Wl,-z,noexecstack -Qunused-arguments -Wl,-z,relro -Wl,-z,now -Wl,--build
-id -Wl,--warn-shared-textrel -Wl,--fatal-warnings -Wl,--no-undefined -Wl,-z,noe
xecstack -Qunused-arguments -Wl,-z,relro -Wl,-z,now -shared -Wl,-soname,my.so -o
 $outpath/my.so $mypath/a.o $mypath/b.o $install_dir/lib/libssl.a $install_dir/li
b/libcrypto.a -ldl my.a -lz -llog -lm "/home/choury/bin/Android/android-sdk-linux
/ndk-bundle/sources/cxx-stl/gnu-libstdc++/4.9/libs/arm64-v8a/libsupc++.a" "/home/
choury/bin/Android/android-sdk-linux/ndk-bundle/sources/cxx-stl/gnu-libstdc++/4.9
/libs/arm64-v8a/libgnustl_shared.so"
</code>```

I build the project with cmake, the Openssl part of it:

```<code>set(OPENSSL_INCLUDE_DIR ${OPENSSL_ROOT_DIR}/include)
set(OPENSSL_LIBRARIES ${OPENSSL_ROOT_DIR}/lib)
set(OPENSSL_CRYPTO_LIBRARY ${OPENSSL_LIBRARIES}/libcrypto.a)
set(OPENSSL_SSL_LIBRARY ${OPENSSL_LIBRARIES}/libssl.a)
find_package(OpenSSL REQUIRED IMPORTED)
</code>```

The OPENSSL_ROOT_DIR is set with $install_dir in build.gradle.

答:
The linker in NDK is sensitive to the order of static libraries on command line. If libA.a depends on libB.a, the command line should be

```<code>clang++ … a.o b.o a/libA.a b/libB.a … -Llibs -lm -ldl -lz -llog -o libqq.so
</code>```

here I assume libm.so, libdl.so, libz.so and liblog.so. Note that the following command is equivalent:

```<code>clang++ … a.o b.o -La -lA -Lb -lB … -Llibs -lm -ldl -lz -llog -o libqq.so
</code>```

Body:
I built libssl.a and libcryto.a. But when I want to link my.so to it, I got this error:

Error:(130) undefined reference to 'BIO_new_dgram'

If I delete this call, I can compile it succeed.

Did I build the library of openssl in a wrong way?

BIO_new_dgram is in libcrypto.a:

nm libcrypto.a  | grep BIO_new_dgram
0000081c T BIO_new_dgram

I configure Openssl  with:

./config shared --openssldir=$install_dir --prefix=$install_dir

and link command:

/home/choury/bin/Android/android-sdk-linux/ndk-bundle/toolchains/llvm/prebuilt/l
inux-x86_64/bin/clang++  --target=aarch64-none-linux-android --gcc-toolchain=/ho
me/choury/bin/Android/android-sdk-linux/ndk-bundle/toolchains/aarch64-linux-andr
oid-4.9/prebuilt/linux-x86_64 --sysroot=/home/choury/bin/Android/android-sdk-lin
ux/ndk-bundle/platforms/android-21/arch-arm64 -fPIC -std=c++11 -Wall -fPIC -ggdb
 -O0  -Wl,--build-id -Wl,--warn-shared-textrel -Wl,--fatal-warnings -Wl,--no-und
efined -Wl,-z,noexecstack -Qunused-arguments -Wl,-z,relro -Wl,-z,now -Wl,--build
-id -Wl,--warn-shared-textrel -Wl,--fatal-warnings -Wl,--no-undefined -Wl,-z,noe
xecstack -Qunused-arguments -Wl,-z,relro -Wl,-z,now -shared -Wl,-soname,my.so -o
 $outpath/my.so $mypath/a.o $mypath/b.o $install_dir/lib/libssl.a $install_dir/li
b/libcrypto.a -ldl my.a -lz -llog -lm "/home/choury/bin/Android/android-sdk-linux
/ndk-bundle/sources/cxx-stl/gnu-libstdc++/4.9/libs/arm64-v8a/libsupc++.a" "/home/
choury/bin/Android/android-sdk-linux/ndk-bundle/sources/cxx-stl/gnu-libstdc++/4.9
/libs/arm64-v8a/libgnustl_shared.so"

I build the project with cmake, the Openssl part of it:

set(OPENSSL_INCLUDE_DIR ${OPENSSL_ROOT_DIR}/include)
set(OPENSSL_LIBRARIES ${OPENSSL_ROOT_DIR}/lib)
set(OPENSSL_CRYPTO_LIBRARY ${OPENSSL_LIBRARIES}/libcrypto.a)
set(OPENSSL_SSL_LIBRARY ${OPENSSL_LIBRARIES}/libssl.a)
find_package(OpenSSL REQUIRED IMPORTED)

The OPENSSL_ROOT_DIR is set with $install_dir in build.gradle.

Body:
The linker in NDK is sensitive to the order of static libraries on command line. If libA.a depends on libB.a, the command line should be

clang++ … a.o b.o a/libA.a b/libB.a … -Llibs -lm -ldl -lz -llog -o libqq.so

here I assume libm.so, libdl.so, libz.so and liblog.so. Note that the following command is equivalent:

clang++ … a.o b.o -La -lA -Lb -lB … -Llibs -lm -ldl -lz -llog -o libqq.so


问:
Cut JS string present in an array at every occurrance of a particular substring and append to same array
Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!

What I have:

```<code>var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]
</code>```

What I need:

```<code>["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]
</code>```

Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$

Example:

difference.$.user.$.otherinformation should be parsed to contain:

```<code>difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation
</code>```

I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.

Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.

How best can I take this to closure?

Current flawed implementation:

```<code>for(var i=0; i<array.length; i++){
    //  next, replace all array field references with $ as that is what autoform's pick() requires
    //  /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
    array[i] = array[i].replace(/\.\d+\./g,".$.");
        if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
            console.log("Substring without .$.  " + array[i].substring(0, array[i].indexOf('.$.')));
            console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')));
            }
        }
    // finally remove any duplicates if any
    array = _.uniq(array);
</code>```

答:
Use a simple for loop like below:

var str = "difference.$.user.$.otherinformation";
var sub, initial = "";
var start = 0;
var pos = str.indexOf('.');
for (; pos != -1; pos = str.indexOf('.', pos + 1)) {
  sub = str.substring(start, pos);
  console.log(initial + sub);
  initial += sub;
  start = pos;
}
console.log(str);```

Body:
Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!

What I have:

var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]

What I need:

["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]

Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$

Example:

difference.$.user.$.otherinformation should be parsed to contain:

difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation

I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.

Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.

How best can I take this to closure?

Current flawed implementation:

for(var i=0; i<array.length; i++){
    //  next, replace all array field references with $ as that is what autoform's pick() requires
    //  /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
    array[i] = array[i].replace(/\.\d+\./g,".$.");
        if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
            console.log("Substring without .$.  " + array[i].substring(0, array[i].indexOf('.$.')));
            console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')));
            }
        }
    // finally remove any duplicates if any
    array = _.uniq(array);


问:
Android running onChildAdded method every time view is accessed through startActivity
I was wondering why my android application is running fireBase onChildAdded every time I access the view through start activity. I only want to read from the fireBase database once, and from then on I use onResume to populate the list with the last entry in the databas (if any were added).

However it is running the onChildAdded every time I use startActitivity to access the view. So this means it doesn't happen when I press the back button to this view.

It's slowing down my application a lot having to repopulate the list from the database every time the user goes back to this page from the home-screen.

Here's a video showcasing how much faster it is when I press back to access the screen when compared to accessing it from the home-screen and pressing on "nightclub" card: https://www.youtube.com/watch?v=VJxsHT14PU8&feature=youtu.be

My onCreate Method:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    // start tracing to "/sdcard/calc.trace"
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nightclub_search);

    // Map and camera Positions
    // Retrieve location and camera position from saved instance state.
    if (savedInstanceState != null) {
        mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
        mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
    }

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    // Build the Play services client for use by the Fused Location Provider and the Places API.
    // Use the addApi() method to request the Google Places API and the Fused Location Provider.
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */,
                    this /* OnConnectionFailedListener */)
            .addConnectionCallbacks(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();

    // List View
    listView = (ListView) findViewById(R.id.venueList);
    listView.setOnItemClickListener(this);
    venueList = new ArrayList<>();
    arrayAdapter = new ArrayAdapter<>(nightclub_search.this, R.layout.list_layout, venueList);

    // Fill the list view from the fireBase
    fillListView();

    // Button
    Button addClub = (Button) findViewById(R.id.addClub);
    addClub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(nightclub_search.this, venue_add.class);
            startActivity(i);
        }
    });
}
</code>```

This is how I am calling the view from the home-screen:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_screen);

    CardView cardBar = (CardView) findViewById(R.id.cardBar);
    CardView cardNightclub = (CardView) findViewById(R.id.cardNightClub);

    cardBar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(home_screen.this, bar_search.class);
            startActivity(intent);
        }
    });
    cardNightclub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(home_screen.this, nightclub_search.class);
            startActivity(intent);
        }
    });
}}
</code>```

And finally this is how I populate the list from firebase which is called within onCreate (and nowhere else):

```<code>// Fills the list for the initial load of the application
protected void fillListView(){

    // Loading bar
    dialog = new ProgressDialog(nightclub_search.this);
    dialog.setMessage("Loading Venues...");
    dialog.show();

    // Separate this from the main thread so that it runs faster
    Runnable run = new Runnable() {
        @Override
        public void run() {
            myRef.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    // Loading dialog for getting fireBase entries
                    count++;
                    Log.d("Firebase", "onChildAddedFROMFILLLISTVIEW:" + dataSnapshot.getKey());
                    // A new venue has been added, add it to the displayed list
                    Nightclub nightclub = dataSnapshot.getValue(Nightclub.class);
                    clubList.add(nightclub);
                    venueList.add(nightclub.name);
                    // Read in location and add marker on map
                    addMarkers(nightclub, days);
                    // Add to listView
                    listView.setAdapter(arrayAdapter);
                    // Remove the loading bar when we've reached this point
                    if (count >= (dataSnapshot.getChildrenCount() - 1)){
                        count = 0;
                        dialog.dismiss();
                    }
                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    };

    Thread fillListThread = new Thread(run);
    fillListThread.start();

}
</code>```

答: Try setting launch mode 'singleTask' in manifest for activity so that onCreate will be called only once while initializing activity and there after all calls will be given to 'onNewIntent' method until new instance is not created in activity back stack.</p>

Body:
I was wondering why my android application is running fireBase onChildAdded every time I access the view through start activity. I only want to read from the fireBase database once, and from then on I use onResume to populate the list with the last entry in the databas (if any were added).

However it is running the onChildAdded every time I use startActitivity to access the view. So this means it doesn't happen when I press the back button to this view.

It's slowing down my application a lot having to repopulate the list from the database every time the user goes back to this page from the home-screen.

Here's a video showcasing how much faster it is when I press back to access the screen when compared to accessing it from the home-screen and pressing on "nightclub" card: https://www.youtube.com/watch?v=VJxsHT14PU8&feature=youtu.be

My onCreate Method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    // start tracing to "/sdcard/calc.trace"
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nightclub_search);

    // Map and camera Positions
    // Retrieve location and camera position from saved instance state.
    if (savedInstanceState != null) {
        mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
        mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
    }

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    // Build the Play services client for use by the Fused Location Provider and the Places API.
    // Use the addApi() method to request the Google Places API and the Fused Location Provider.
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */,
                    this /* OnConnectionFailedListener */)
            .addConnectionCallbacks(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();

    // List View
    listView = (ListView) findViewById(R.id.venueList);
    listView.setOnItemClickListener(this);
    venueList = new ArrayList<>();
    arrayAdapter = new ArrayAdapter<>(nightclub_search.this, R.layout.list_layout, venueList);

    // Fill the list view from the fireBase
    fillListView();

    // Button
    Button addClub = (Button) findViewById(R.id.addClub);
    addClub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(nightclub_search.this, venue_add.class);
            startActivity(i);
        }
    });
}

This is how I am calling the view from the home-screen:

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

    CardView cardBar = (CardView) findViewById(R.id.cardBar);
    CardView cardNightclub = (CardView) findViewById(R.id.cardNightClub);

    cardBar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(home_screen.this, bar_search.class);
            startActivity(intent);
        }
    });
    cardNightclub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(home_screen.this, nightclub_search.class);
            startActivity(intent);
        }
    });
}}

And finally this is how I populate the list from firebase which is called within onCreate (and nowhere else):

// Fills the list for the initial load of the application
protected void fillListView(){

    // Loading bar
    dialog = new ProgressDialog(nightclub_search.this);
    dialog.setMessage("Loading Venues...");
    dialog.show();

    // Separate this from the main thread so that it runs faster
    Runnable run = new Runnable() {
        @Override
        public void run() {
            myRef.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    // Loading dialog for getting fireBase entries
                    count++;
                    Log.d("Firebase", "onChildAddedFROMFILLLISTVIEW:" + dataSnapshot.getKey());
                    // A new venue has been added, add it to the displayed list
                    Nightclub nightclub = dataSnapshot.getValue(Nightclub.class);
                    clubList.add(nightclub);
                    venueList.add(nightclub.name);
                    // Read in location and add marker on map
                    addMarkers(nightclub, days);
                    // Add to listView
                    listView.setAdapter(arrayAdapter);
                    // Remove the loading bar when we've reached this point
                    if (count >= (dataSnapshot.getChildrenCount() - 1)){
                        count = 0;
                        dialog.dismiss();
                    }
                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    };

    Thread fillListThread = new Thread(run);
    fillListThread.start();

}


问:
Python pandas Timestamp.week returns 52 for first day of year
The code below returns 52 52: how come?

```<code>import pandas as pd
ts = pd.Timestamp('01-01-2017 12:00:00')
print(ts.weekofyear, ts.week)
</code>```

答:
This is correct, that's ISO week date.

Last week

The last week of the ISO week-numbering year, i.e. the 52nd or 53rd one, is the week before week 01. This week’s properties are:

It has the year's last Thursday in it.

It is the last week with a majority (4 or more) of its days in December.

Its middle day, Thursday, falls in the ending year.

Its last day is the Sunday nearest to 31 December.

It has 28 December in it. Hence the earliest possible last week extends from Monday 22 December to Sunday 28 December, the latest possible last week extends from Monday 28 December to Sunday 3 January (next gregorian year).

If 31 December is on a Monday, Tuesday or Wednesday, it is in week 01 of the next year. If it is on a Thursday, it is in week 53 of the year just ending; if on a Friday it is in week 52 (or 53 if the year just ending is a leap year); if on a Saturday or Sunday, it is in week 52 of the year just ending.

Body:
The code below returns 52 52: how come?

import pandas as pd
ts = pd.Timestamp('01-01-2017 12:00:00')
print(ts.weekofyear, ts.week)


问:
Python 2.7: Logging Class Threaded RotatingFileHandler Buffer Overflow? Error 32
I am receiving the following Error when logging goes to rotate the log files:

```<code>Traceback (most recent call last):
  File "C:\Python27\Lib\logging\handlers.py", line 72, in emit
    self.doRollover()
  File "C:\Python27\Lib\logging\handlers.py", line 174, in doRollover
    self.rotate(self.baseFilename, dfn)
  File "C:\Python27\Lib\logging\handlers.py", line 113, in rotate
    os.rename(source, dest)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
Logged from file logger_example.py, line 37
</code>```

PSMON results (full picture):

I saw in that in python 3.2 there is an implementation of a QueuedHandler for threaded logging, but I don't think that is what is going on here, as I have tried to turn logging off while threading. I even implemented a Queued Version based off of the handler.py included in python3 (like this), but received the same error. I am obviously doing something incorrectly, but I am unable to figure it out. As it is writing to the same file from multiple classes.

https://docs.python.org/3.5/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes

https://docs.python.org/3.5/library/logging.handlers.html#queuehandler

logger_example.py:

```<code>class log_this(object):
    def __init__(self,module_name, MainFrame):
        super(log_this, self).__init__()
        self.MainFrame = MainFrame
        self.module_name = module_name
        LOG_FILENAME = os.path.join('logs','test.log')
        LOG_LEVEL = logging.DEBUG
        logging.getLogger(self.module_name)
        logging.basicConfig(level=LOG_LEVEL,
                            format='\n--%(asctime)s %(funcName)s %(name)-12s %(levelname)-8s %(message)s',
                            datefmt='%m-%d %H:%M:%S',
                            filename=LOG_FILENAME,
                            filemode='w')
        #console = logging.StreamHandler()
        self.handler = logging.handlers.RotatingFileHandler(
              LOG_FILENAME, maxBytes=1000000, backupCount=5)
        #console.setLevel(logging.INFO)
        self.count = 0

    def log_info(self,name,msg):
        print('In: log_info')
        try:
            log_name = logging.getLogger(".".join([self.module_name,name]))
            log_name.addHandler(self.handler)
            if self.MainFrame.threading is False:
                log_name.info("\n%s" % (msg))
        except Exception,e:
            print(traceback.format_exc())
            print(e)
            exit()
        return

    def log_debug(self,func_name,msg,debug_info):
        try:
            log_name = logging.getLogger(".".join([self.module_name,func_name]))
            log_name.addHandler(self.handler)
            #called_frame_trace = "\n    ".join(traceback.format_stack()).replace("\n\n","\n")
            outer_frames = inspect.getouterframes(inspect.currentframe().f_back.f_back)
            call_fn = outer_frames[3][1]
            call_ln = outer_frames[3][2]
            call_func = outer_frames[3][3]
            caller = outer_frames[3][4]
            # a string with args and kwargs from log_debug
            args_kwargs_str = "\n"+str(debug_info).replace(", '","\n, '")
            if self.MainFrame.threading is False:
                results = log_name.debug("%s\nARGS_KWARGS_STR:%s\ncall_fn: %s\ncall_ln: %i\ncall_func: %s\ncaller: %s\nException:" % (
                                            msg,
                                            args_kwargs_str,
                                            call_fn,
                                            call_ln,
                                            call_func,
                                            caller
                                            ),exc_info=1)
        except Exception, e:
            print(traceback.format_exc())
            print(e)
            exit()
        return
</code>```

Example usage that is being used in multiple classes across several directories/modules:

```<code>from Logs.logger_example import log_this
class Ssh(object):

    def __init__(self, MainFrame):
        super(Ssh, self).__init__()
        self.MainFrame = MainFrame
        self.logger = log_this(__name__,self.MainFrame)
    def infoLogger(self,msg=None):
        this_function_name = sys._getframe().f_back.f_code.co_name
        self.logger.log_info(this_function_name,str(msg)+" "+this_function_name)
        return
    def debugLogger(self,msg=None,*args,**kwargs):
        debug_info = {'ARGS':args, 'KWARGS':kwargs}
        this_function_name = sys._getframe().f_back.f_code.co_name
        self.logger.log_debug(this_function_name,str(msg)+this_function_name,debug_info)
        return
    #-------------------------------------------------
    # Example Usage:
    # It used like this in other classes as well
    #-------------------------------------------------
    def someMethod(self):
        self.infoLogger('some INFO message:%s' % (some_var))
        self.debugLogger('Some DEBUG message:',var1,var2,var3=something)
</code>```

Example Output:

```<code>--06-05 12:35:34 log_debug display_image.EventsHandlers.MainFrameEventHandler.csvFileBrowse DEBUG    Inside:  csvFileBrowse
ARGS_KWARGS_STR:
{'ARGS': ()
, 'KWARGS': {}}
call_fn: C:\Python27\lib\site-packages\wx-3.0-msw\wx\_core.py
call_ln: 8660
call_func: MainLoop
caller: ['        wx.PyApp.MainLoop(self)\n']
Exception:
None

--06-05 12:35:34 log_info display_image.EventsHandlers.MainFrameEventHandler.csvFileBrowse INFO
Inside:  csvFileBrowse

--06-05 12:35:41 log_debug display_image.sky_scraper.fetchPage DEBUG    retailer_code,jNumberfetchPage
ARGS_KWARGS_STR:
{'ARGS': ('1', u'J176344')
, 'KWARGS': {}}
call_fn: C:\Users\User\Desktop\SGIS\SGIS_6-2-14\SGIS-wxpython-master\display_image\EventsHandlers\MainFrameEventHandler.py
call_ln: 956
call_func: onScanNumberText
caller: ['            results = self.updateMainFrameCurrentItemInfo(retailer_code)\n']
Exception:
None
</code>```

Any suggestions would be greatly appreciated.

答:
I got the same error while developing a flask application. To solve the problem, I had to change the environmental variable from
"FLASK_DEBUG=1" to
"FLASK_DEBUG=0".
The reason being that turning debugging on leads to threading errors.
I got the solution after reading this blog</p>

Body:
I am receiving the following Error when logging goes to rotate the log files:

Traceback (most recent call last):
  File "C:\Python27\Lib\logging\handlers.py", line 72, in emit
    self.doRollover()
  File "C:\Python27\Lib\logging\handlers.py", line 174, in doRollover
    self.rotate(self.baseFilename, dfn)
  File "C:\Python27\Lib\logging\handlers.py", line 113, in rotate
    os.rename(source, dest)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
Logged from file logger_example.py, line 37

PSMON results (full picture):

I saw in that in python 3.2 there is an implementation of a QueuedHandler for threaded logging, but I don't think that is what is going on here, as I have tried to turn logging off while threading. I even implemented a Queued Version based off of the handler.py included in python3 (like this), but received the same error. I am obviously doing something incorrectly, but I am unable to figure it out. As it is writing to the same file from multiple classes.

https://docs.python.org/3.5/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes

https://docs.python.org/3.5/library/logging.handlers.html#queuehandler

logger_example.py:

class log_this(object):
    def __init__(self,module_name, MainFrame):
        super(log_this, self).__init__()
        self.MainFrame = MainFrame
        self.module_name = module_name
        LOG_FILENAME = os.path.join('logs','test.log')
        LOG_LEVEL = logging.DEBUG
        logging.getLogger(self.module_name)
        logging.basicConfig(level=LOG_LEVEL,
                            format='\n--%(asctime)s %(funcName)s %(name)-12s %(levelname)-8s %(message)s',
                            datefmt='%m-%d %H:%M:%S',
                            filename=LOG_FILENAME,
                            filemode='w')
        #console = logging.StreamHandler()
        self.handler = logging.handlers.RotatingFileHandler(
              LOG_FILENAME, maxBytes=1000000, backupCount=5)
        #console.setLevel(logging.INFO)
        self.count = 0

    def log_info(self,name,msg):
        print('In: log_info')
        try:
            log_name = logging.getLogger(".".join([self.module_name,name]))
            log_name.addHandler(self.handler)
            if self.MainFrame.threading is False:
                log_name.info("\n%s" % (msg))
        except Exception,e:
            print(traceback.format_exc())
            print(e)
            exit()
        return

    def log_debug(self,func_name,msg,debug_info):
        try:
            log_name = logging.getLogger(".".join([self.module_name,func_name]))
            log_name.addHandler(self.handler)
            #called_frame_trace = "\n    ".join(traceback.format_stack()).replace("\n\n","\n")
            outer_frames = inspect.getouterframes(inspect.currentframe().f_back.f_back)
            call_fn = outer_frames[3][1]
            call_ln = outer_frames[3][2]
            call_func = outer_frames[3][3]
            caller = outer_frames[3][4]
            # a string with args and kwargs from log_debug
            args_kwargs_str = "\n"+str(debug_info).replace(", '","\n, '")
            if self.MainFrame.threading is False:
                results = log_name.debug("%s\nARGS_KWARGS_STR:%s\ncall_fn: %s\ncall_ln: %i\ncall_func: %s\ncaller: %s\nException:" % (
                                            msg,
                                            args_kwargs_str,
                                            call_fn,
                                            call_ln,
                                            call_func,
                                            caller
                                            ),exc_info=1)
        except Exception, e:
            print(traceback.format_exc())
            print(e)
            exit()
        return

Example usage that is being used in multiple classes across several directories/modules:

from Logs.logger_example import log_this
class Ssh(object):

    def __init__(self, MainFrame):
        super(Ssh, self).__init__()
        self.MainFrame = MainFrame
        self.logger = log_this(__name__,self.MainFrame)
    def infoLogger(self,msg=None):
        this_function_name = sys._getframe().f_back.f_code.co_name
        self.logger.log_info(this_function_name,str(msg)+" "+this_function_name)
        return
    def debugLogger(self,msg=None,*args,**kwargs):
        debug_info = {'ARGS':args, 'KWARGS':kwargs}
        this_function_name = sys._getframe().f_back.f_code.co_name
        self.logger.log_debug(this_function_name,str(msg)+this_function_name,debug_info)
        return
    #-------------------------------------------------
    # Example Usage:
    # It used like this in other classes as well
    #-------------------------------------------------
    def someMethod(self):
        self.infoLogger('some INFO message:%s' % (some_var))
        self.debugLogger('Some DEBUG message:',var1,var2,var3=something)

Example Output:

--06-05 12:35:34 log_debug display_image.EventsHandlers.MainFrameEventHandler.csvFileBrowse DEBUG    Inside:  csvFileBrowse
ARGS_KWARGS_STR:
{'ARGS': ()
, 'KWARGS': {}}
call_fn: C:\Python27\lib\site-packages\wx-3.0-msw\wx\_core.py
call_ln: 8660
call_func: MainLoop
caller: ['        wx.PyApp.MainLoop(self)\n']
Exception:
None

--06-05 12:35:34 log_info display_image.EventsHandlers.MainFrameEventHandler.csvFileBrowse INFO
Inside:  csvFileBrowse

--06-05 12:35:41 log_debug display_image.sky_scraper.fetchPage DEBUG    retailer_code,jNumberfetchPage
ARGS_KWARGS_STR:
{'ARGS': ('1', u'J176344')
, 'KWARGS': {}}
call_fn: C:\Users\User\Desktop\SGIS\SGIS_6-2-14\SGIS-wxpython-master\display_image\EventsHandlers\MainFrameEventHandler.py
call_ln: 956
call_func: onScanNumberText
caller: ['            results = self.updateMainFrameCurrentItemInfo(retailer_code)\n']
Exception:
None

Any suggestions would be greatly appreciated.


问:
How to Display and load images from URL that are visible in UITableViewCell
I tried this link, but I didn't get my solution.

I want to display and load images from URL that are visible in UITableViewCell and other cell images have to load when we scroll table view in Objective-C.

答:
Rajashekar simply you can do this</p>

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strCell=@"cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:strCell];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:strCell];
    }
    NSString *strImgURL = @"YourImageURL";
    NSError* error = nil;
    NSURL *fileURL = [NSURL fileURLWithPath:strImgURL];
    NSData* data = [NSData dataWithContentsOfURL:fileURL options:NSDataReadingUncached error:&error];
    if (error) {
        NSLog(@"%@", [error localizedDescription]);
    } else {
        NSLog(@"Data has loaded successfully.");
    }
    UIImage *img = [[UIImage alloc] initWithData:data];
    cell.imageView.image = img;

    return cell;
}
</code>```

Body:
Rajashekar simply you can do this

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strCell=@"cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:strCell];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:strCell];
    }
    NSString *strImgURL = @"YourImageURL";
    NSError* error = nil;
    NSURL *fileURL = [NSURL fileURLWithPath:strImgURL];
    NSData* data = [NSData dataWithContentsOfURL:fileURL options:NSDataReadingUncached error:&error];
    if (error) {
        NSLog(@"%@", [error localizedDescription]);
    } else {
        NSLog(@"Data has loaded successfully.");
    }
    UIImage *img = [[UIImage alloc] initWithData:data];
    cell.imageView.image = img;

    return cell;
}


问:
Calcuting the date difference for a specified number of days using LocalDate class
I'm using openjdk version 1.8.0_112-release for development but will need to support previous JDK versions too (pre-Java-8) - so can't use java.time.

I am writing a utitily class to calculate the date to see if a saved date is before the current date which means its expired.

However, I am not sure I have done this the correct way. I am using LocalDate class to calculate the days. The expiration is counted starting from the date and time the user clicked save. That date will be saved and a check will be done against this saved date and time and the current date and time i.e. when the user logs in.

Is this the best way to do it? I would like to keep to the LocalDate class.

```<code>import org.threeten.bp.LocalDate;

public final class Utilities {
    private Utilities() {}

    public static boolean hasDateExpired(int days, LocalDate savedDate, LocalDate currentDate) {
        boolean hasExpired = false;

        if(savedDate != null && currentDate != null) {
            /* has expired if the saved date plus the specified days is still before the current date (today) */
            if(savedDate.plusDays(days).isBefore(currentDate)) {
                hasExpired = true;
            }
        }

        return hasExpired;
    }
}
</code>```

I'm using the class like this:

```<code>private void showDialogToIndicateLicenseHasExpired() {
    final LocalDate currentDate = LocalDate.now();
    final int DAYS_TO_EXPIRE = 3;
    final LocalDate savedDate = user.getSavedDate();

    if(hasDateExpired(DAYS_TO_EXPIRE, savedDate, currentDate)) {
        /* License has expired, warn the user */
    }
}
</code>```

I am looking a solution that will take in account time zones. If a license was set to expire in 3 days, and the user was to travel to a different time zone. i.e. they could be ahead or behind based on hours. The license should still expire.

答:
As this question is not getting "enough responses", I have added another answer:

I have used "SimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));" to set the timezone to UTC.  So there is no longer a timezone (all Date / time will be set to UTC).

savedDate is set to UTC.

dateTimeNow is also set to UTC, with the number of expired "days" (negative number) added to dateTimeNow.

A new Date expiresDate uses the long milliseconds from dateTimeNow

Check if savedDate.before(expiresDate)

```<code>package com.chocksaway;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class ExpiredDate {
    private static final long DAY_IN_MS = 1000 * 60 * 60 * 24;

    private static boolean hasDateExpired(int days, java.util.Date savedDate) throws ParseException {
        SimpleDateFormat dateFormatUtc = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
        dateFormatUtc.setTimeZone(TimeZone.getTimeZone("UTC"));

        // Local Date / time zone
        SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

        // Date / time in UTC
        savedDate = dateFormatLocal.parse( dateFormatUtc.format(savedDate));

        Date dateTimeNow = dateFormatLocal.parse( dateFormatUtc.format(new Date()));

        long expires = dateTimeNow.getTime() + (DAY_IN_MS * days);

        Date expiresDate = new Date(expires);

        System.out.println("savedDate \t\t" + savedDate + "\nexpiresDate \t" + expiresDate);

        return savedDate.before(expiresDate);
    }

    public static void main(String[] args) throws ParseException {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 0);

        if (ExpiredDate.hasDateExpired(-2, cal.getTime())) {
            System.out.println("expired");
        } else {
            System.out.println("not expired");
        }

        System.out.print("\n");

        cal.add(Calendar.DATE, -3);

        if (ExpiredDate.hasDateExpired(-2, cal.getTime())) {
            System.out.println("expired");
        } else {
            System.out.println("not expired");
        }
    }
}
</code>```

Running this code gives the following output:

```<code>savedDate       Mon Jun 05 15:03:24 BST 2017
expiresDate     Sat Jun 03 15:03:24 BST 2017
not expired

savedDate       Fri Jun 02 15:03:24 BST 2017
expiresDate     Sat Jun 03 15:03:24 BST 2017
expired
</code>```

All dates / times are UTC.  First is not expired.  Second is expired (savedDate is before expiresDate).

Body:
I'm using openjdk version 1.8.0_112-release for development but will need to support previous JDK versions too (pre-Java-8) - so can't use java.time.

I am writing a utitily class to calculate the date to see if a saved date is before the current date which means its expired.

However, I am not sure I have done this the correct way. I am using LocalDate class to calculate the days. The expiration is counted starting from the date and time the user clicked save. That date will be saved and a check will be done against this saved date and time and the current date and time i.e. when the user logs in.

Is this the best way to do it? I would like to keep to the LocalDate class.

import org.threeten.bp.LocalDate;

public final class Utilities {
    private Utilities() {}

    public static boolean hasDateExpired(int days, LocalDate savedDate, LocalDate currentDate) {
        boolean hasExpired = false;

        if(savedDate != null && currentDate != null) {
            /* has expired if the saved date plus the specified days is still before the current date (today) */
            if(savedDate.plusDays(days).isBefore(currentDate)) {
                hasExpired = true;
            }
        }

        return hasExpired;
    }
}

I'm using the class like this:

private void showDialogToIndicateLicenseHasExpired() {
    final LocalDate currentDate = LocalDate.now();
    final int DAYS_TO_EXPIRE = 3;
    final LocalDate savedDate = user.getSavedDate();

    if(hasDateExpired(DAYS_TO_EXPIRE, savedDate, currentDate)) {
        /* License has expired, warn the user */
    }
}

I am looking a solution that will take in account time zones. If a license was set to expire in 3 days, and the user was to travel to a different time zone. i.e. they could be ahead or behind based on hours. The license should still expire.

Body:
As this question is not getting "enough responses", I have added another answer:

I have used "SimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));" to set the timezone to UTC.  So there is no longer a timezone (all Date / time will be set to UTC).

savedDate is set to UTC.

dateTimeNow is also set to UTC, with the number of expired "days" (negative number) added to dateTimeNow.

A new Date expiresDate uses the long milliseconds from dateTimeNow

Check if savedDate.before(expiresDate)

package com.chocksaway;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class ExpiredDate {
    private static final long DAY_IN_MS = 1000 * 60 * 60 * 24;

    private static boolean hasDateExpired(int days, java.util.Date savedDate) throws ParseException {
        SimpleDateFormat dateFormatUtc = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
        dateFormatUtc.setTimeZone(TimeZone.getTimeZone("UTC"));

        // Local Date / time zone
        SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

        // Date / time in UTC
        savedDate = dateFormatLocal.parse( dateFormatUtc.format(savedDate));

        Date dateTimeNow = dateFormatLocal.parse( dateFormatUtc.format(new Date()));

        long expires = dateTimeNow.getTime() + (DAY_IN_MS * days);

        Date expiresDate = new Date(expires);

        System.out.println("savedDate \t\t" + savedDate + "\nexpiresDate \t" + expiresDate);

        return savedDate.before(expiresDate);
    }

    public static void main(String[] args) throws ParseException {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 0);

        if (ExpiredDate.hasDateExpired(-2, cal.getTime())) {
            System.out.println("expired");
        } else {
            System.out.println("not expired");
        }

        System.out.print("\n");

        cal.add(Calendar.DATE, -3);

        if (ExpiredDate.hasDateExpired(-2, cal.getTime())) {
            System.out.println("expired");
        } else {
            System.out.println("not expired");
        }
    }
}

Running this code gives the following output:

savedDate       Mon Jun 05 15:03:24 BST 2017
expiresDate     Sat Jun 03 15:03:24 BST 2017
not expired

savedDate       Fri Jun 02 15:03:24 BST 2017
expiresDate     Sat Jun 03 15:03:24 BST 2017
expired

All dates / times are UTC.  First is not expired.  Second is expired (savedDate is before expiresDate).


问:
A Typical Issue with login using Zend_Form
Iam facing a typical issue with a form submit using Zend framework. Basically I have written a simple code to login a user, but this came out of the blue.

The code to show the form is pretty standard

$loginform = new Application_Form_Login();
        $loginform->setMethod('post');
        $loginform->setAction('login');
        $this->view->form = $loginform;

When I use my home page url as - http://localhost.ruin.com/public/

I get an exception

```<code>Page not found
Exception information:

Message: Invalid controller specified (login)
Stack trace:

#0 C:\domains\ruin\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#1 C:\domains\ruin\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#2 C:\domains\ruin\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#3 C:\domains\ruin\public\index.php(27): Zend_Application->run()
#4 {main}

Request Parameters:

array (
  'controller' => 'login',
  'action' => 'index',
  'module' => 'default',
  'username' => 'fsdf',
  'password' => 'fdsf',
  'submit' => 'submit',
)
</code>```

However if I use the base url as http://localhost.ruin.com/public/index/ , the same code works perfectly.

I also know that its due to the fact that in first url the zend router is messing up the index controller with login since its not able to append the login action to the default index controller.

Do you guys think this is by design of Zend Framework and I shall have to forcefully send my users to this url
http://localhost.ruin.com/public/index/ whenever they hit the home page or is there a way I can make my code work with
http://localhost.ruin.com/public/

Any suggestions?

答:
The thing you should realize first is that the "public" folder in your example should be the web root (or DocumentRoot). Once you set it up correctly, you'll see that you can access your site using http://localhost.ruin.com, and I'm quite sure that your login form will work without any problem.

Refer to http://framework.zend.com/manual/en/project-structure.project.html for more information.

Body:
Iam facing a typical issue with a form submit using Zend framework. Basically I have written a simple code to login a user, but this came out of the blue.

The code to show the form is pretty standard

$loginform = new Application_Form_Login();
        $loginform->setMethod('post');
        $loginform->setAction('login');
        $this->view->form = $loginform;

When I use my home page url as - http://localhost.ruin.com/public/

I get an exception

Page not found
Exception information:

Message: Invalid controller specified (login)
Stack trace:

#0 C:\domains\ruin\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#1 C:\domains\ruin\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#2 C:\domains\ruin\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#3 C:\domains\ruin\public\index.php(27): Zend_Application->run()
#4 {main}

Request Parameters:

array (
  'controller' => 'login',
  'action' => 'index',
  'module' => 'default',
  'username' => 'fsdf',
  'password' => 'fdsf',
  'submit' => 'submit',
)

However if I use the base url as http://localhost.ruin.com/public/index/ , the same code works perfectly.

I also know that its due to the fact that in first url the zend router is messing up the index controller with login since its not able to append the login action to the default index controller.

Do you guys think this is by design of Zend Framework and I shall have to forcefully send my users to this url
http://localhost.ruin.com/public/index/ whenever they hit the home page or is there a way I can make my code work with
http://localhost.ruin.com/public/

Any suggestions?


问:
Filter DataFrame by selecting the first row with not-NaN in the given column (or any one row if doesn't exist)
I have a pandas dataframe df with (at least) two columns: id, value and possibly more. id's are not unique. I need to filter the dataframe so that only one row per id remains. The row I want to select is the row where value is not NaN. It is guaranteed that there is at most one such row. For those id's with all NaN's in the value column I don't care which row is selected. What is the best way to achieve this?

Example: if the dataframe is

```<code>id  other   value
0   0   3.14
0   1   NaN
1   2   NaN
1   3   NaN
</code>```

the result may be either

```<code>id  other   value
0   0   3.14
1   2   NaN
</code>```

or

```<code>id  other   value
0   0   3.14
1   3   NaN
</code>```

答:
Assuming that your dataframe is called dff, the following should do:

```<code>f = lambda x: x.head(1) if x.value.isnull().all() else x[~x.value.isnull()].head(1)

dff.groupby('id').apply(f)
</code>```

Output:

```<code>#       id  other  value
# id
# 0  0   0      0   3.14
# 1  2   1      2    NaN
</code>```

It groups the dataframe by the id column first. If all elements in the value column are null, it takes the first row. Otherwise, it filters out null values and take the first row of the output.

I hope this helps.

Body:
I have a pandas dataframe df with (at least) two columns: id, value and possibly more. id's are not unique. I need to filter the dataframe so that only one row per id remains. The row I want to select is the row where value is not NaN. It is guaranteed that there is at most one such row. For those id's with all NaN's in the value column I don't care which row is selected. What is the best way to achieve this?

Example: if the dataframe is

id  other   value
0   0   3.14
0   1   NaN
1   2   NaN
1   3   NaN

the result may be either

id  other   value
0   0   3.14
1   2   NaN

or

id  other   value
0   0   3.14
1   3   NaN

Body:
Assuming that your dataframe is called dff, the following should do:

f = lambda x: x.head(1) if x.value.isnull().all() else x[~x.value.isnull()].head(1)

dff.groupby('id').apply(f)

Output:

#       id  other  value
# id
# 0  0   0      0   3.14
# 1  2   1      2    NaN

It groups the dataframe by the id column first. If all elements in the value column are null, it takes the first row. Otherwise, it filters out null values and take the first row of the output.

I hope this helps.


问:
Django Admin : How to update/change the image from the list_display itself without opening the change form for the entry
My models.py looks like

```<code>class User_Detail(models.Model):
    user_image = models.ImageField(upload_to='users',default = 'users/profile.png')
    user_image_thumbnail = ImageSpecField(source='user_image',
                                      processors=[ResizeToFill(75, 100)],
                                      format='JPEG',
                                      options={'quality': 60})
</code>```

My Admin.py looks like

```<code>class UserAdmin(admin.ModelAdmin):
    list_display = ('profile_pic',)

    def profile_pic(self, obj):  # receives the instance as an argument
        url = reverse('admin:%s_%s_change' %(obj._meta.app_label,  obj._meta.model_name),  args=[obj.id] )
        url_string = '<a style="margin: 2px;" href="%s">Update</a>' %(url)
        return '<img width=75 height=75 src="{thumb}" />'.format(
            thumb=obj.user_image_thumbnail.url,
        ) + url_string
    profile_pic.allow_tags = True
    profile_pic.short_description = 'User Picture'
</code>```

I want the django administrator to update the imagefield from the admin list display itself by providing an update button next to displayed thumbnail and save it without opening the change form for the entry.
I am using the django-imagekit for generating the thumbnails.

答:
list_editable is used to edit field in django admin list without going to the change form.
However, to use list_editable following points should be noted:

fields in list_editable should also be included in list_display

same field cannot be used as link to the change form and on list_editable.

Your admin.py should be:

```<code>class UserAdmin(admin.ModelAdmin):
    // "id" can be replaced by any other field to use as link
    list_display = ('id', 'profile_pic',)
    list_editable = ('profile_pic',)

    // rest of the code
</code>```

More information on https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_editable

Body:
My models.py looks like

class User_Detail(models.Model):
    user_image = models.ImageField(upload_to='users',default = 'users/profile.png')
    user_image_thumbnail = ImageSpecField(source='user_image',
                                      processors=[ResizeToFill(75, 100)],
                                      format='JPEG',
                                      options={'quality': 60})

My Admin.py looks like

class UserAdmin(admin.ModelAdmin):
    list_display = ('profile_pic',)

    def profile_pic(self, obj):  # receives the instance as an argument
        url = reverse('admin:%s_%s_change' %(obj._meta.app_label,  obj._meta.model_name),  args=[obj.id] )
        url_string = 'Update' %(url)
        return ''.format(
            thumb=obj.user_image_thumbnail.url,
        ) + url_string
    profile_pic.allow_tags = True
    profile_pic.short_description = 'User Picture'

I want the django administrator to update the imagefield from the admin list display itself by providing an update button next to displayed thumbnail and save it without opening the change form for the entry.
I am using the django-imagekit for generating the thumbnails.

Body:
list_editable is used to edit field in django admin list without going to the change form.
However, to use list_editable following points should be noted:

fields in list_editable should also be included in list_display

same field cannot be used as link to the change form and on list_editable.

Your admin.py should be:

class UserAdmin(admin.ModelAdmin):
    // "id" can be replaced by any other field to use as link
    list_display = ('id', 'profile_pic',)
    list_editable = ('profile_pic',)

    // rest of the code

More information on https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_editable


问:
sequelize query return Promise { _bitField: ...}
I want to return the value from sequelize query in another variable. I have to tried different solution, but i have the same result:

```<code>    Promise {
  _bitField: 2097152,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined,
  _boundTo: SellerPresent }
</code>```

my js file(at the moment):

```<code>function findIdSeller(selectEvent) {
var match = {attribute: ['seller_id'], where: {event_id: selectEvent}, raw: true};
return models.SellerPresent.findAll(match)}

exports.findDataSeller = function (selectEvent) {
    var seller = [];
    return findIdSeller(selectEvent).then(function (result) {
        return  seller.push(result.seller_id)
    })
};
</code>```

I need export this data in routes. How i can do it?

答:
First of all, be aware that asynchronous results cannot be treated (or exported) synchronously, so you need to stick with promises all the way.

Secondly, the findAll method will return an array, so you should not access the seller_id on that array, but on its elements. For that you can use map:

```<code>function findIdSeller(selectEvent) {
    var match = {
        attribute: ['seller_id'],
        where: {
            event_id: selectEvent
        },
        raw: true
    };
    return models.SellerPresent.findAll(match);
}

// You can export a promise, not the promised value:
exports.findDataSellerPromise = function (selectEvent) {
    return findIdSeller(selectEvent).then(function (result) {
        return result.map(function(seller) {
            return seller.seller_id
        });
    });
});
</code>```

You need to call findDataSellerPromise as returning a promise. So, for instance, if you need to use the promised data as a response in routing, then call then on it:

```<code>app.get('/', function (req, res) {
    // ....
    findDataSellerPromise(selectEvent).then(function(sellers) {
        res.send(sellers);
    });
});
</code>```

Body:
I want to return the value from sequelize query in another variable. I have to tried different solution, but i have the same result:

    Promise {
  _bitField: 2097152,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined,
  _boundTo: SellerPresent }

my js file(at the moment):

function findIdSeller(selectEvent) {
var match = {attribute: ['seller_id'], where: {event_id: selectEvent}, raw: true};
return models.SellerPresent.findAll(match)}

exports.findDataSeller = function (selectEvent) {
    var seller = [];
    return findIdSeller(selectEvent).then(function (result) {
        return  seller.push(result.seller_id)
    })
};

I need export this data in routes. How i can do it?

Body:
First of all, be aware that asynchronous results cannot be treated (or exported) synchronously, so you need to stick with promises all the way.

Secondly, the findAll method will return an array, so you should not access the seller_id on that array, but on its elements. For that you can use map:

function findIdSeller(selectEvent) {
    var match = {
        attribute: ['seller_id'],
        where: {
            event_id: selectEvent
        },
        raw: true
    };
    return models.SellerPresent.findAll(match);
}

// You can export a promise, not the promised value:
exports.findDataSellerPromise = function (selectEvent) {
    return findIdSeller(selectEvent).then(function (result) {
        return result.map(function(seller) {
            return seller.seller_id
        });
    });
});

You need to call findDataSellerPromise as returning a promise. So, for instance, if you need to use the promised data as a response in routing, then call then on it:

app.get('/', function (req, res) {
    // ....
    findDataSellerPromise(selectEvent).then(function(sellers) {
        res.send(sellers);
    });
});


问:
SQL convert column to float in where clause
I have this column in my database table and its a string. I didnt make this table and I cant change the data type.

However I need to convert it to a float in my where clause so I can compare it against a float.

I have tried the casting my column as a float:

```<code>sql += " AND CAST (ec.bedrooms as float) <= " + id.beds.Max().Split('-')[1] + " AND CAST (ec.bedrooms as float) >= " + id.beds.Min().Split('-')[0];
</code>```

but that didnt work as I got this error:

```<code>An error occurred while reading from the store provider's data reader. See the inner exception for details
</code>```

What am I doing wrong?

Here is what is generated for that section

```<code>AND CAST (ec.bedrooms as float) <= 3 AND CAST (ec.bedrooms as float) >= 2

"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Error converting data type nvarchar to float.","ExceptionType":"System.Data.SqlClient.SqlException","StackTrace":"   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n   at System.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)\r\n   at System.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)\r\n   at System.Data.SqlClient.SqlDataReader.Read()\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.StoreRead()"}}
</code>```

答:
Looks like your ec.bedrooms is having non-numeric values... You can check like below:</p>

```<code>sql += " AND CAST (iif(isnumeric(ec.bedrooms)>0,ec.bedrooms,null) as float) <= " + id.beds.Max().Split('-')[1] + " AND
CAST (iif(isnumeric(ec.bedrooms)>0,ec.bedrooms,null) as float) >= " + id.beds.Min().Split('-')[0];
</code>```

Body:
I have this column in my database table and its a string. I didnt make this table and I cant change the data type.

However I need to convert it to a float in my where clause so I can compare it against a float.

I have tried the casting my column as a float:

sql += " AND CAST (ec.bedrooms as float) <= " + id.beds.Max().Split('-')[1] + " AND CAST (ec.bedrooms as float) >= " + id.beds.Min().Split('-')[0];

but that didnt work as I got this error:

An error occurred while reading from the store provider's data reader. See the inner exception for details

What am I doing wrong?

Here is what is generated for that section

AND CAST (ec.bedrooms as float) <= 3 AND CAST (ec.bedrooms as float) >= 2

"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Error converting data type nvarchar to float.","ExceptionType":"System.Data.SqlClient.SqlException","StackTrace":"   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n   at System.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)\r\n   at System.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)\r\n   at System.Data.SqlClient.SqlDataReader.Read()\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.StoreRead()"}}

Body:
Looks like your ec.bedrooms is having non-numeric values... You can check like below:

sql += " AND CAST (iif(isnumeric(ec.bedrooms)>0,ec.bedrooms,null) as float) <= " + id.beds.Max().Split('-')[1] + " AND
CAST (iif(isnumeric(ec.bedrooms)>0,ec.bedrooms,null) as float) >= " + id.beds.Min().Split('-')[0];


问:
json: cannot unmarshal array into Go value of type main.Posts
I'm trying to read a json file with golang but i'm getting this error.
I've checked almost every question about it but still couldnt get it.

Here's the example json file:
https://jsonplaceholder.typicode.com/posts

And my code:

```<code>package main

import (
    "net/http"
    "log"
    "fmt"
    "io/ioutil"
    "encoding/json"
)

type Posts struct {
    Post []struct{
        UserId int `json:"userId"`
        ID int `json:"id"`
        Title string `json:"title"`
        Body string `json:"body"`
    }
}

func main (){
    resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")

    if err != nil {
        log.Fatal(err)
    }

    content, _ := ioutil.ReadAll(resp.Body)

    var posts Posts

    parsed := json.Unmarshal([]byte(content), &posts)

    //fmt.Println(string(content))

    fmt.Println(parsed)

}
</code>```

答:
Posts is an array of Post struct but you defined Post as array it is your first mistake, also Unmarshal doesn't returns result it returns only error and fills given parameter.</p>

```<code>package main

import (
    "net/http"
    "log"
    "fmt"
    "io/ioutil"
    "encoding/json"
)

type Post struct {
        UserId int `json:"userId"`
        ID int `json:"id"`
        Title string `json:"title"`
        Body string `json:"body"`
}

type Posts []Post

func main (){
    resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")

    if err != nil {
        log.Fatal(err)
    }

    content, _ := ioutil.ReadAll(resp.Body)

    var posts Posts

    err = json.Unmarshal(content, &posts)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(posts[0].Body)

}
</code>```

Body:
I'm trying to read a json file with golang but i'm getting this error.
I've checked almost every question about it but still couldnt get it.

Here's the example json file:
https://jsonplaceholder.typicode.com/posts

And my code:

package main

import (
    "net/http"
    "log"
    "fmt"
    "io/ioutil"
    "encoding/json"
)

type Posts struct {
    Post []struct{
        UserId int `json:"userId"`
        ID int `json:"id"`
        Title string `json:"title"`
        Body string `json:"body"`
    }
}

func main (){
    resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")

    if err != nil {
        log.Fatal(err)
    }

    content, _ := ioutil.ReadAll(resp.Body)

    var posts Posts

    parsed := json.Unmarshal([]byte(content), &posts)

    //fmt.Println(string(content))

    fmt.Println(parsed)

}

Body:
Posts is an array of Post struct but you defined Post as array it is your first mistake, also Unmarshal doesn't returns result it returns only error and fills given parameter.

package main

import (
    "net/http"
    "log"
    "fmt"
    "io/ioutil"
    "encoding/json"
)

type Post struct {
        UserId int `json:"userId"`
        ID int `json:"id"`
        Title string `json:"title"`
        Body string `json:"body"`
}

type Posts []Post

func main (){
    resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")

    if err != nil {
        log.Fatal(err)
    }

    content, _ := ioutil.ReadAll(resp.Body)

    var posts Posts

    err = json.Unmarshal(content, &posts)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(posts[0].Body)

}


问:
Regex: replace all numbers and "number-like" strings except for years in range
I have the following string:

```<code>s = '2014 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'
</code>```

I want to replace with '' every part of this string which contains a number, except for those parts of the string that are in the year range 1950 to 2025. The resultant string would look like this (don't worry about the extraneous whitespace):

```<code>'2014          keep this text      2015 2025 '
</code>```

So, effectively I want the brute-force removal of anything and everything remotely "numerical," except for something standalone (i.e. not part of another string, and of length 4 excluding whitespace) that resembles a year.

I know I can use this to remove everything containing digits:

```<code>re.sub('\w*[0-9]\w*', '', s)
</code>```

But that doesn't return what I want:

```<code>'           keep this text        '
</code>```

Here's my attempt at replacing anything that doesn't match the patterns listed below:

```<code>re.sub(r'^([A-Za-z]+|19[5-9]\d|20[0-1]\d|202[0-5])', '*', s)
</code>```

Which returns:

```<code>'* 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'
</code>```

I've been here and here, but wasn't able to find what I was looking for.

Body:
I have the following string:

s = '2014 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'

I want to replace with '' every part of this string which contains a number, except for those parts of the string that are in the year range 1950 to 2025. The resultant string would look like this (don't worry about the extraneous whitespace):

'2014          keep this text      2015 2025 '

So, effectively I want the brute-force removal of anything and everything remotely "numerical," except for something standalone (i.e. not part of another string, and of length 4 excluding whitespace) that resembles a year.

I know I can use this to remove everything containing digits:

re.sub('\w*[0-9]\w*', '', s)

But that doesn't return what I want:

'           keep this text        '

Here's my attempt at replacing anything that doesn't match the patterns listed below:

re.sub(r'^([A-Za-z]+|19[5-9]\d|20[0-1]\d|202[0-5])', '*', s)

Which returns:

'* 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'

I've been here and here, but wasn't able to find what I was looking for.

Body:
Short solution using re.findall() function:

s = '2014 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'
result = ''.join(re.findall(r'\b(19[5-9][0-9]|20[01][0-9]|202[0-5]|[a-z]+|[^0-9a-z]+)\b', s, re.I))

print(result)

The output:

2014           keep this text      2015 2025