问:
How to resolve ambiguous column names when retrieving results?
I have two tables in my database:

NEWS table with columns:

id - the news id

user - the user id of the author)

USERS table with columns:

id - the user id

I want to execute this SQL:

```<code>SELECT * FROM news JOIN users ON news.user = user.id
</code>```

When I get the results in PHP I would like to get associative array and get column names by $row['column-name']. How do I get the news ID and the user ID, having the same column name?

答:
You can either use the numerical indices ($row[0]) or better, use AS in the MySQL:

SELECT *, user.id AS user_id FROM ...

OwnerDisplayName: Dan

Body:
I have two tables in my database:

NEWS table with columns:

id - the news id

user - the user id of the author)

USERS table with columns:

id - the user id

I want to execute this SQL:

SELECT * FROM news JOIN users ON news.user = user.id

When I get the results in PHP I would like to get associative array and get column names by $row['column-name']. How do I get the news ID and the user ID, having the same column name?

LastEditorDisplayName: Dan

OwnerDisplayName: RoBorg


来源: stackexchange

问:
Issue about loading bitmaps in CTreeCtrl
I am trying to create an image list to my control, and load additional images. The problem is that only the image that i create is used and the loaded images does not displayed. Here is my ccode:

define IMAGE1          1

define IMAGE2          2

define IMAGE3          3

define IMAGE4          4

define IMAGE5          5

```<code>m_Bitmap1.LoadBitmap(IDB_BITMAP1);
m_Bitmap2.LoadBitmap(IDB_BITMAP2);
m_Bitmap3.LoadBitmap(IDB_BITMAP3);

m_ImageListTree = new CImageList;
m_ImageListTree->Create(IDB_BITMAP1, 16, 1, RGB(255, 255, 255));
m_ImageListTree->Add(&m_Bitmap2, RGB(255, 255, 255));
m_ImageListTree->Add(&m_Bitmap3, RGB(255, 255, 255));

while( ItemTree != NULL)
{
    BasicTree->SetItemImage(ItemTree, nCounter, nCounter);
    ItemTree = BasicTree->GetNextItem(ItemTree, TVGN_CHILD);
    nCounter++;
}
</code>```

The only IDB_BITMAP1 is displayed in all tree levels. Any ideas?

答:
Actually I was never in the loop, as i did not get the initial HTRREITEM before entering the loop.

Also the creation of the list in the control, intialises every new item with the bitmap you are using for the creation. You can set the image eitehr in insertion or in alter though you need to specify diferent image (fo insertion you need to define a TVINSERTSTRUCTW and set the image before inserting the whole item.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to create an image list to my control, and load additional images. The problem is that only the image that i create is used and the loaded images does not displayed. Here is my ccode:

define IMAGE1          1

define IMAGE2          2

define IMAGE3          3

define IMAGE4          4

define IMAGE5          5

m_Bitmap1.LoadBitmap(IDB_BITMAP1);
m_Bitmap2.LoadBitmap(IDB_BITMAP2);
m_Bitmap3.LoadBitmap(IDB_BITMAP3);

m_ImageListTree = new CImageList;
m_ImageListTree->Create(IDB_BITMAP1, 16, 1, RGB(255, 255, 255));
m_ImageListTree->Add(&m_Bitmap2, RGB(255, 255, 255));
m_ImageListTree->Add(&m_Bitmap3, RGB(255, 255, 255));

while( ItemTree != NULL)
{
    BasicTree->SetItemImage(ItemTree, nCounter, nCounter);
    ItemTree = BasicTree->GetNextItem(ItemTree, TVGN_CHILD);
    nCounter++;
}

The only IDB_BITMAP1 is displayed in all tree levels. Any ideas?


问:
Use vs Include in PHP
I'm trying to get my head around PHP namespaces and testing with PHPUnit.

These tests from Codewars pass when I run phpunit test.php in the command line on Windows:

```<code><?php
require 'solution.php';
use PHPUnit\Framework\TestCase;

class myTests extends TestCase {
  public function testExamples() {
        $this->assertEquals(pair_sum([1,9,2,8,3,7,4,6,5,5,13,14,11,13,-1],10),6);
        $this->assertEquals(pair_sum([1,2,3,1],3),1);
        $this->assertEquals(pair_sum([1,3,2,2],4),2);
        $this->assertEquals(pair_sum([1],4),false);
        $this->assertEquals(pair_sum([2,3,10,-5],5),2);
  }
}
</code>```

However, when I comment out use PHPUnit\Framework\TestCase; I get Class 'TestCase' not found which makes sense since there is no reference to the needed classes/functions.

What's confusing me though is that lots of answers here on SO about namespacing claim that the use keyword is NOT a substitute for include/require and that the classes still need to be included/autoloaded(?).

I'm not using any autoloading here - just a solution.php file and the tests above in a test.php file.

Can someone please explain what I'm missing here? How come the tests work without  any explicit including of the PHPunit functionality?

I should mention that I have PHPUnit installed globally via Composer.

答:
Like @deceze said, the PHPUnit did the job for you, but don't think that use will not require the file included.

Look with atention to the structure:
https://phpunit.de/manual/current/en/database.html#database.tip-use-your-own-abstract-database-testcase

PRO-TIP: Open the phpunit files that you'll understand better.

ContentLicense: CC BY-SA 3.0

Title: Use vs Include in PHP

Body:
I'm trying to get my head around PHP namespaces and testing with PHPUnit.

These tests from Codewars pass when I run phpunit test.php in the command line on Windows:

<?php
require 'solution.php';
use PHPUnit\Framework\TestCase;

class myTests extends TestCase {
  public function testExamples() {
        $this->assertEquals(pair_sum([1,9,2,8,3,7,4,6,5,5,13,14,11,13,-1],10),6);
        $this->assertEquals(pair_sum([1,2,3,1],3),1);
        $this->assertEquals(pair_sum([1,3,2,2],4),2);
        $this->assertEquals(pair_sum([1],4),false);
        $this->assertEquals(pair_sum([2,3,10,-5],5),2);
  }
}

However, when I comment out use PHPUnit\Framework\TestCase; I get Class 'TestCase' not found which makes sense since there is no reference to the needed classes/functions.

What's confusing me though is that lots of answers here on SO about namespacing claim that the use keyword is NOT a substitute for include/require and that the classes still need to be included/autoloaded(?).

I'm not using any autoloading here - just a solution.php file and the tests above in a test.php file.

Can someone please explain what I'm missing here? How come the tests work without  any explicit including of the PHPunit functionality?

I should mention that I have PHPUnit installed globally via Composer.


问:
How to test 500.html error page in django development env?
I am using Django for a project and is already in production.

In the production environment 500.html is rendered whenever a server error occurs.

How do I test the rendering of 500.html in dev environment? Or how do I render 500.html in dev, if I turn-off debug I still get the errors and not 500.html

background: I include some page elements based on a page and some are missing when 500.html is called and want to debug it in dev environment.

答:
How i do and test custom error handlers

Define custom View based on TemplateView

```<code># views.py
from django.views.generic import TemplateView

class ErrorHandler(TemplateView):

    """ Render error template """

    error_code = 404
    template_name = 'index/error.html'

    def dispatch(self, request, *args, **kwargs):
        """ For error on any methods return just GET """
        return self.get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['error_code'] = self.error_code
        return context

    def render_to_response(self, context, **response_kwargs):
        """ Return correct status code """
        response_kwargs = response_kwargs or {}
        response_kwargs.update(status=self.error_code)
        return super().render_to_response(context, **response_kwargs)
</code>```

Tell django to use custom error handlers

```<code># urls.py

from index.views import ErrorHandler

# error handing handlers - fly binding
for code in (400, 403, 404, 500):
    vars()['handler{}'.format(code)] = ErrorHandler.as_view(error_code=code)
</code>```

Testcase for custom error handlers

```<code># tests.py

from unittest import mock

from django.test import TestCase
from django.core.exceptions import SuspiciousOperation, PermissionDenied
from django.http import Http404
from index import views

class ErrorHandlersTestCase(TestCase):

    """ Check is correct error handlers work """

    def raise_(exception):
        def wrapped(*args, **kwargs):
            raise exception('Test exception')
        return wrapped

    def test_index_page(self):
        """ Should check is 200 on index page """
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'index/index.html')

    @mock.patch('index.views.IndexView.get', raise_(Http404))
    def test_404_page(self):
        """ Should check is 404 page correct """
        response = self.client.get('/')
        self.assertEqual(response.status_code, 404)
        self.assertTemplateUsed(response, 'index/error.html')
        self.assertIn('404 Page not found', response.content.decode('utf-8'))

    @mock.patch('index.views.IndexView.get', views.ErrorHandler.as_view(error_code=500))
    def test_500_page(self):
        """ Should check is 500 page correct """
        response = self.client.get('/')
        self.assertEqual(response.status_code, 500)
        self.assertTemplateUsed(response, 'index/error.html')
        self.assertIn('500 Server Error', response.content.decode('utf-8'))

    @mock.patch('index.views.IndexView.get', raise_(SuspiciousOperation))
    def test_400_page(self):
        """ Should check is 400 page correct """
        response = self.client.get('/')
        self.assertEqual(response.status_code, 400)
        self.assertTemplateUsed(response, 'index/error.html')
        self.assertIn('400 Bad request', response.content.decode('utf-8'))

    @mock.patch('index.views.IndexView.get', raise_(PermissionDenied))
    def test_403_page(self):
        """ Should check is 403 page correct """
        response = self.client.get('/')
        self.assertEqual(response.status_code, 403)
        self.assertTemplateUsed(response, 'index/error.html')
        self.assertIn('403 Permission Denied', response.content.decode('utf-8'))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How i do and test custom error handlers

Define custom View based on TemplateView

# views.py
from django.views.generic import TemplateView

class ErrorHandler(TemplateView):

    """ Render error template """

    error_code = 404
    template_name = 'index/error.html'

    def dispatch(self, request, *args, **kwargs):
        """ For error on any methods return just GET """
        return self.get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['error_code'] = self.error_code
        return context

    def render_to_response(self, context, **response_kwargs):
        """ Return correct status code """
        response_kwargs = response_kwargs or {}
        response_kwargs.update(status=self.error_code)
        return super().render_to_response(context, **response_kwargs)

Tell django to use custom error handlers

# urls.py

from index.views import ErrorHandler

# error handing handlers - fly binding
for code in (400, 403, 404, 500):
    vars()['handler{}'.format(code)] = ErrorHandler.as_view(error_code=code)

Testcase for custom error handlers

# tests.py

from unittest import mock

from django.test import TestCase
from django.core.exceptions import SuspiciousOperation, PermissionDenied
from django.http import Http404
from index import views

class ErrorHandlersTestCase(TestCase):

    """ Check is correct error handlers work """

    def raise_(exception):
        def wrapped(*args, **kwargs):
            raise exception('Test exception')
        return wrapped

    def test_index_page(self):
        """ Should check is 200 on index page """
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'index/index.html')

    @mock.patch('index.views.IndexView.get', raise_(Http404))
    def test_404_page(self):
        """ Should check is 404 page correct """
        response = self.client.get('/')
        self.assertEqual(response.status_code, 404)
        self.assertTemplateUsed(response, 'index/error.html')
        self.assertIn('404 Page not found', response.content.decode('utf-8'))

    @mock.patch('index.views.IndexView.get', views.ErrorHandler.as_view(error_code=500))
    def test_500_page(self):
        """ Should check is 500 page correct """
        response = self.client.get('/')
        self.assertEqual(response.status_code, 500)
        self.assertTemplateUsed(response, 'index/error.html')
        self.assertIn('500 Server Error', response.content.decode('utf-8'))

    @mock.patch('index.views.IndexView.get', raise_(SuspiciousOperation))
    def test_400_page(self):
        """ Should check is 400 page correct """
        response = self.client.get('/')
        self.assertEqual(response.status_code, 400)
        self.assertTemplateUsed(response, 'index/error.html')
        self.assertIn('400 Bad request', response.content.decode('utf-8'))

    @mock.patch('index.views.IndexView.get', raise_(PermissionDenied))
    def test_403_page(self):
        """ Should check is 403 page correct """
        response = self.client.get('/')
        self.assertEqual(response.status_code, 403)
        self.assertTemplateUsed(response, 'index/error.html')
        self.assertIn('403 Permission Denied', response.content.decode('utf-8'))


问:
Contextual styling of ReactJS styled-components
I'm running into problems with Styled Components, and I'm not sure if it's a technical limitation, or if my mental model of how to use them is wrong.

In this example (I just wrote it quickly in Codepen, so disregard spelling mistakes) I have a component that is a username in a span. I want to be able to use that component anywhere, so it's styling is pretty minimal:

```<code>// From User.js
import React from 'react';
import styled from 'styled-components';

const Username = styled.span`
  color: black;
`

const User = () => (
  <UserName>bla</Username>
);

export default User;
</code>```

I want to be able to use this span in a different component, but in that case I want it's styling to be overridden in this context:

```<code>// From Userblock.js
import React from 'react';
import styled from 'styled-components';
import User from './user';

const UserWrapper = styled.div`
  // Some styles
`

const User = styled(User)`
  color: red; // Different color when displayed in a UserBlock
`

const UserBlock = () => (
  <UserWrapper>
    <User />
  </UserWrapper>
);

export default UserBlock;
</code>```

From what I know, that's the way to set styling on a third party component (and that works elsewhere in my application), and it should work as far as I can tell, but I get nothing.

Also, going back to the mental model question - is this the way you're supposed to do it when you're using styled-components?

Thanks for any help!

答:
When you wrap a normal React component with styled(X) you need to make sure to attach the class that styled-components passes in.

This means for your example, this will solve the issue:

```<code>const User = (props) => (
  <UserName className={props.className}>bla</Username>
);
</code>```

When you override the styles of an existing component styled-components goes ahead, generates a class, injects it and passes it to the component. That means if you don't attach the class to anything you'll never see the styles though! (see the documentation for more information)

Body:
I'm running into problems with Styled Components, and I'm not sure if it's a technical limitation, or if my mental model of how to use them is wrong.

In this example (I just wrote it quickly in Codepen, so disregard spelling mistakes) I have a component that is a username in a span. I want to be able to use that component anywhere, so it's styling is pretty minimal:

// From User.js
import React from 'react';
import styled from 'styled-components';

const Username = styled.span`
  color: black;
`

const User = () => (
  <UserName>bla</Username>
);

export default User;

I want to be able to use this span in a different component, but in that case I want it's styling to be overridden in this context:

// From Userblock.js
import React from 'react';
import styled from 'styled-components';
import User from './user';

const UserWrapper = styled.div`
  // Some styles
`

const User = styled(User)`
  color: red; // Different color when displayed in a UserBlock
`

const UserBlock = () => (
  <UserWrapper>
    <User />
  </UserWrapper>
);

export default UserBlock;

From what I know, that's the way to set styling on a third party component (and that works elsewhere in my application), and it should work as far as I can tell, but I get nothing.

Also, going back to the mental model question - is this the way you're supposed to do it when you're using styled-components?

Thanks for any help!

Body:
When you wrap a normal React component with styled(X) you need to make sure to attach the class that styled-components passes in.

This means for your example, this will solve the issue:

const User = (props) => (
  <UserName className={props.className}>bla</Username>
);

When you override the styles of an existing component styled-components goes ahead, generates a class, injects it and passes it to the component. That means if you don't attach the class to anything you'll never see the styles though! (see the documentation for more information)


问:
How to replace the following character with an empty space and write in next line?
How to replace that character which is square in shape(□) with a \n or an empty space and write in next line using c#?...It is writing in text file with □... Here is my code....

```<code> string line = dt.Rows[0].ItemArray[0].ToString().Replace(Environment.NewLine, "<br>");
</code>```

and

```<code> if (line.IndexOf(line2, StringComparison.CurrentCultureIgnoreCase) != -1)
    {
        if (!patternwritten)
        {
            dest.WriteLine("");
            dest.WriteLine("Pattern Name : " + line2 );
             patternwritten = true;
         }

  dest.WriteLine("LineNo : " + counter.ToString() + " : " + "" + line.TrimStart());
}
</code>```

But it is writing the whole line with  □....Any suggestion??

答:
My guess is that your string contains simple linefeed characters, whereas your Environment.NewLine value is "\r\n".

One simple way of coping with this is to perform two replacements:

```<code>text = text.Replace("\r\n", "<br>")
           .Replace("\n", "<br>")
</code>```

To find our for sure what's going on, you should open up your file in a binary file editor and see what binary data is in the file. My guess is that you'll find a character represented by 0x0A in binary.

Body:
How to replace that character which is square in shape(□) with a \n or an empty space and write in next line using c#?...It is writing in text file with □... Here is my code....

 string line = dt.Rows[0].ItemArray[0].ToString().Replace(Environment.NewLine, "
");

and

 if (line.IndexOf(line2, StringComparison.CurrentCultureIgnoreCase) != -1)
    {
        if (!patternwritten)
        {
            dest.WriteLine("");
            dest.WriteLine("Pattern Name : " + line2 );
             patternwritten = true;
         }

  dest.WriteLine("LineNo : " + counter.ToString() + " : " + "" + line.TrimStart());
}

But it is writing the whole line with  □....Any suggestion??

Body:
My guess is that your string contains simple linefeed characters, whereas your Environment.NewLine value is "\r\n".

One simple way of coping with this is to perform two replacements:

text = text.Replace("\r\n", "<br>")
           .Replace("\n", "<br>")

To find our for sure what's going on, you should open up your file in a binary file editor and see what binary data is in the file. My guess is that you'll find a character represented by 0x0A in binary.


问:
Is it possible to create ipv4-enabled Docker Machine on Windows 10?
Given fresh Windows 10 pro installed and latest 1.13.1 (10072) "Docker for Windows", if I create a new machine via:

```<code>docker-machine create --driver hyperv node1
</code>```

The machine will have only ipv6 address attached to it. Simple commands like docker ssh node1 will work, but if I try something advanced like "docker swarm" it will fail:

```<code>$ docker-machine ls
NAME    ACTIVE   DRIVER   STATE     URL                                     SWARM   DOCKER    ERRORS
node1   -        hyperv   Running   tcp://[fe80::215:5dff:fe0f:ae10]:2376           v1.13.1
</code>```

Is it any way to create and IPv4 docker machine, or it's not intended to be used on Windows boxes?

答:
It is possible. You have to use external network switch.

To create external network switch open hyper-v manager and then open virtual switch manager.

Related docker documentation

Finally create node with this command (Primary Virtual Switch is the name of the external virtual switch):

docker-machine create --driver hyperv --hyperv-virtual-switch "Primary
  Virtual Switch" node1

Body:
Given fresh Windows 10 pro installed and latest 1.13.1 (10072) "Docker for Windows", if I create a new machine via:

docker-machine create --driver hyperv node1

The machine will have only ipv6 address attached to it. Simple commands like docker ssh node1 will work, but if I try something advanced like "docker swarm" it will fail:

$ docker-machine ls
NAME    ACTIVE   DRIVER   STATE     URL                                     SWARM   DOCKER    ERRORS
node1   -        hyperv   Running   tcp://[fe80::215:5dff:fe0f:ae10]:2376           v1.13.1

Is it any way to create and IPv4 docker machine, or it's not intended to be used on Windows boxes?


问:
Python Multiple Classes Error in Calling specific class
I am a newbie, and picking up Python (3.4) and trying to work on classes.

I have created a module BootstrapYieldCurve, with two classes (BootstrapYieldCurve and ForwardRates) inside.

When I import the module, I can call and manipulate the BootstrapYieldCurve class, but I get an error from calling the ForwardRates class.

Would someone be able to advise if the code is wrong, or the way I call the class in Python Shell?

```<code>>>> from BootstrapYieldCurve import ForwardRates
>>> Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    from BootstrapYieldCurve import ForwardRates
ImportError: cannot import name 'ForwardRates'
</code>```

This is my module code structure

```<code>import math

class BootstrapYieldCurve():
    def __init__(self):
    def add_instrument(..........):
    ..........
class ForwardRates():
    def .........
</code>```

答:
You cannot import one class from another class like this :

```<code>from BootstrapYieldCurve import ForwardRates
</code>```

because ForwardRates is not encapsulated inside BootstrapYieldCurve (Also, there is no such concept in Python). See encapsulation.

You can import variables, functions, and classes from a module (a python file that generally have variables, functions, and classes)

You can do something like :

```<code>from module_file import BootstrapYieldCurve
</code>```

and

```<code>from module_file import ForwardRates
</code>```

You can refer to this basic tutorial on importing modules.

Also, try not to name module and class with same name as that may create confusion. It is a not a good practice to do that as module names share the same namespace as everything else.

Body:
I am a newbie, and picking up Python (3.4) and trying to work on classes.

I have created a module BootstrapYieldCurve, with two classes (BootstrapYieldCurve and ForwardRates) inside.

When I import the module, I can call and manipulate the BootstrapYieldCurve class, but I get an error from calling the ForwardRates class.

Would someone be able to advise if the code is wrong, or the way I call the class in Python Shell?

>>> from BootstrapYieldCurve import ForwardRates
>>> Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    from BootstrapYieldCurve import ForwardRates
ImportError: cannot import name 'ForwardRates'

This is my module code structure

import math

class BootstrapYieldCurve():
    def __init__(self):
    def add_instrument(..........):
    ..........
class ForwardRates():
    def .........

Body:
You cannot import one class from another class like this :

from BootstrapYieldCurve import ForwardRates

because ForwardRates is not encapsulated inside BootstrapYieldCurve (Also, there is no such concept in Python). See encapsulation.

You can import variables, functions, and classes from a module (a python file that generally have variables, functions, and classes)

You can do something like :

from module_file import BootstrapYieldCurve

and

from module_file import ForwardRates

You can refer to this basic tutorial on importing modules.

Also, try not to name module and class with same name as that may create confusion. It is a not a good practice to do that as module names share the same namespace as everything else.


问:
Dynamically accessing Ruby JSON object variables
```<code>puts @file
# {
#   "0.js": "js/0.js",
#   "about-page.js": "js/about-page.js",
#   "img/heart.png": "img/ae985f1437f67f39c4393e31c6785970.png",
#   "index-page.js": "js/index-page.js",
#   "init.js": "js/init.js",
#   "main.js": "js/main.js"
# }
a = "0.js"
puts a // => "0.js"
puts @file[a] // => "0.js"  ????!!!???
</code>```

Why the above code wouldn't work? I am expecting the last line to output "js/0.js" instead of "0.js".

Thanks

答:
Because your hash is getting created like this

```<code>{:"0.js"=>"js/0.js",
 :"about-page.js"=>"js/about-page.js",
 :"img/heart.png"=>"img/ae985f1437f67f39c4393e31c6785970.png",
 :"index-page.js"=>"js/index-page.js",
 :"init.js"=>"js/init.js",
 :"main.js"=>"js/main.js"}
</code>```

in order to access it you need to do  @file[:"0.js"]

Body:
puts @file
# {
#   "0.js": "js/0.js",
#   "about-page.js": "js/about-page.js",
#   "img/heart.png": "img/ae985f1437f67f39c4393e31c6785970.png",
#   "index-page.js": "js/index-page.js",
#   "init.js": "js/init.js",
#   "main.js": "js/main.js"
# }
a = "0.js"
puts a // => "0.js"
puts @file[a] // => "0.js"  ????!!!???

Why the above code wouldn't work? I am expecting the last line to output "js/0.js" instead of "0.js".

Thanks

Body:
Because your hash is getting created like this

{:"0.js"=>"js/0.js",
 :"about-page.js"=>"js/about-page.js",
 :"img/heart.png"=>"img/ae985f1437f67f39c4393e31c6785970.png",
 :"index-page.js"=>"js/index-page.js",
 :"init.js"=>"js/init.js",
 :"main.js"=>"js/main.js"}

in order to access it you need to do  @file[:"0.js"]


问:
How to query date data with millisecond through mongolite?
As below, type of 'stime' and 'etime' is 'Date' with millisecond:

```<code>{
"_id" : ObjectId("58d843dd4da8fc62c8c6a0bd"),
"stime" : ISODate("2017-03-26T22:21:34.923Z"),
"etime" : ISODate("2017-03-26T22:42:17.341Z"),
}
</code>```

And I queried data like this:

```<code>data.names<-c("stime","etime")
mongo.data <- mongo(collection = "data_1",db = "data_test",
                    url = "mongodb://10.23.102.122:32800")
journey <- mongo.data$find(query = '{\"_id\" : {\"$oid\":\"58d843dd4da8fc62c8c6a0bd\"}}',
                           fields = paste('{\"_id\":true, ',
                                          paste('\"',data.names,'\":true', collapse = ', ', sep=''),
                                          '}', sep = ''))
</code>```

But the data queried are UTC time-stamp without millisecond data:

```<code>> journey
                       _id      stime      etime
1 58d843dd4da8fc62c8c6a0bd 1490566894 1490568137
> format(as.POSIXct(unlist(journey[1,-1]), origin = "1970-01-01 00:00:00"), format="%Y-%m-%d %H-%M-%OS3")
                    stime                     etime
"2017-03-27 06-21-34.000" "2017-03-27 06-42-17.000"
</code>```

So, how can I query the data with millisecond data?

答:
I've found a solution via mongo aggregate method:

```<code> journey <- mongo.data$aggregate(pipeline = '[{\"$match\":{\"_id\":{\"$oid\":\"58d843dd4da8fc62c8c6a0bd\"}}}, {\"$project\":{\"_id\":1, \"stime\":1, \"stime_milliseconds\":{\"$millisecond\":\"$stime\"}, \"etime\":1, \"etime_milliseconds\":{\"$millisecond\":\"$etime\"}}}]')
</code>```

In the code above, I extracted the millisecond data of 'stime' and 'etime' as two new variables 'stime_milliseconds' and 'etime_milliseconds' using the 'millisecond' method in mongo. Then extract the data from mongo via R, which is like this:

```<code>> journey
                       _id      stime      etime stime_milliseconds etime_milliseconds
1 58d843dd4da8fc62c8c6a0bd 1490566894 1490568137                923                341
</code>```

The last two numbers stands for the millisecond data.

This is my solution, and welcome better answer

Forgive my poor English~()~

Body:
As below, type of 'stime' and 'etime' is 'Date' with millisecond:

{
"_id" : ObjectId("58d843dd4da8fc62c8c6a0bd"),
"stime" : ISODate("2017-03-26T22:21:34.923Z"),
"etime" : ISODate("2017-03-26T22:42:17.341Z"),
}

And I queried data like this:

data.names<-c("stime","etime")
mongo.data <- mongo(collection = "data_1",db = "data_test",
                    url = "mongodb://10.23.102.122:32800")
journey <- mongo.data$find(query = '{\"_id\" : {\"$oid\":\"58d843dd4da8fc62c8c6a0bd\"}}',
                           fields = paste('{\"_id\":true, ',
                                          paste('\"',data.names,'\":true', collapse = ', ', sep=''),
                                          '}', sep = ''))

But the data queried are UTC time-stamp without millisecond data:

> journey
                       _id      stime      etime
1 58d843dd4da8fc62c8c6a0bd 1490566894 1490568137
> format(as.POSIXct(unlist(journey[1,-1]), origin = "1970-01-01 00:00:00"), format="%Y-%m-%d %H-%M-%OS3")
                    stime                     etime
"2017-03-27 06-21-34.000" "2017-03-27 06-42-17.000"

So, how can I query the data with millisecond data?

Body:
I've found a solution via mongo aggregate method:

 journey <- mongo.data$aggregate(pipeline = '[{\"$match\":{\"_id\":{\"$oid\":\"58d843dd4da8fc62c8c6a0bd\"}}}, {\"$project\":{\"_id\":1, \"stime\":1, \"stime_milliseconds\":{\"$millisecond\":\"$stime\"}, \"etime\":1, \"etime_milliseconds\":{\"$millisecond\":\"$etime\"}}}]')

In the code above, I extracted the millisecond data of 'stime' and 'etime' as two new variables 'stime_milliseconds' and 'etime_milliseconds' using the 'millisecond' method in mongo. Then extract the data from mongo via R, which is like this:

> journey
                       _id      stime      etime stime_milliseconds etime_milliseconds
1 58d843dd4da8fc62c8c6a0bd 1490566894 1490568137                923                341

The last two numbers stands for the millisecond data.

This is my solution, and welcome better answer

Forgive my poor English~()~


问:
c++ paste value and print string
I declare 2 string type strings, qhich is s, s1. I use s string with 'cin'
and I paste 3 values in s1. Then I print with 'cout' but it can't print string.

Here is my code

```<code>#include<iostream>
#include<cstdio>
using namespace std;

int main()

{

    string s,s1;
    cin>>s;
    s1[0]=s[1];
    s1[1]=s[2];
    s1[2]=s[3];
    s1[3]='\0';
    cout<<s1<<endl;
    return 0;
}
</code>```

s1 was not empty.... cout<<s1[0]<<s1[1]<<s1[2] and see.
Why s1 can't print?

答:
Probably, the easiest way to accomplish OP's task is to use a library function like substr() which takes care of all the details the posted code is missing (and already pointed out):

memory management. The second string s1 is empty, so trying to write its first four (unallocated) elements is undefined behavior. In general, s1 should be resized to the needed length.

null terminator. A std::string can manage it's internal representation and always returns a null-terminated string via its member functions c_str and data (since C++11).

That's how it could be done:

```<code>#include <iostream>
#include <string>

int main()
{
    std::string s;

    std::cin >> s;

    std::string s1;
    std::string::size_type start_pos = 1,
                           count = 3;
    if ( s.size() > start_pos )
        s1 = s.substr(start_pos, count);

    std::cout << s1 << '\n';
}
</code>```

Title: c++ paste value and print string

Body:
I declare 2 string type strings, qhich is s, s1. I use s string with 'cin'
and I paste 3 values in s1. Then I print with 'cout' but it can't print string.

Here is my code

#include<iostream>
#include<cstdio>
using namespace std;

int main()

{

    string s,s1;
    cin>>s;
    s1[0]=s[1];
    s1[1]=s[2];
    s1[2]=s[3];
    s1[3]='\0';
    cout<<s1<<endl;
    return 0;
}

s1 was not empty.... cout<<s1[0]<<s1[1]<<s1[2] and see.
Why s1 can't print?

Body:
Probably, the easiest way to accomplish OP's task is to use a library function like substr() which takes care of all the details the posted code is missing (and already pointed out):

memory management. The second string s1 is empty, so trying to write its first four (unallocated) elements is undefined behavior. In general, s1 should be resized to the needed length.

null terminator. A std::string can manage it's internal representation and always returns a null-terminated string via its member functions c_str and data (since C++11).

That's how it could be done:

#include <iostream>
#include <string>

int main()
{
    std::string s;

    std::cin >> s;

    std::string s1;
    std::string::size_type start_pos = 1,
                           count = 3;
    if ( s.size() > start_pos )
        s1 = s.substr(start_pos, count);

    std::cout << s1 << '\n';
}


问:
Get the list of child if the selected value is same value as in the Firebase database value
My database is as following :

```<code>List_of_users>
             sunil dhakal>
                        departmnet:"Computer Science",
                        level:"Level 3 Undergraduate",
                        name:"sunil dhakal",
                        student_id:"1412361",
                        username:"1412361@my.brunel.ac.uk",
</code>```

```<code>root.child("List_of_user").addValueEventListener(new ValueEventListener() {

    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot data :dataSnapshot.getChildren()){
            if (data.child(department).exists()&& data.child(level).exists()){
                Set<String> set = new HashSet<String>();
                Iterator i = dataSnapshot.child("List_of_users").getChildren().iterator();
                while (i.hasNext()) {
                    set.add(((DataSnapshot) i.next()).getKey());
                }
                list_of_rooms.clear();
                list_of_rooms.addAll(set);
                arrayAdapter.notifyDataSetChanged();
            }
            else{
                Toast.makeText(searchuser.this,"There is not user with the department and level that was selected",Toast.LENGTH_SHORT).show();
                return;
            }
        }
    }

    public void onCancelled(DatabaseError databaseError) {}
});
</code>```

I have a spinner where user is able to select department and level and click a button which list all the user in the database with that department and level.

答:
searchusers.setOnClickListener(new View.OnClickListener() {

```<code>        public void onClick(View v) {
            final String department = dep.getSelectedItem().toString().trim();
            final String level = lev.getSelectedItem().toString().trim();
            root.addValueEventListener(new ValueEventListener() {

                public void onDataChange(DataSnapshot dataSnapshot) {
                    root.child("List_of_users")
                            .orderByChild("department")
                            .equalTo(department)
                            .orderByChild("level")
                            .equalTo(level);
                    Set<String> set = new HashSet<String>();
                    Iterator i = dataSnapshot.child("List_of_users").getChildren().iterator();
                    while (i.hasNext()) {
                        set.add(((DataSnapshot) i.next()).getKey());
                    }
                    list_of_rooms.clear();
                    list_of_rooms.addAll(set);
                    arrayAdapter.notifyDataSetChanged();
                }
</code>```

Is this format ok?

Body:
My database is as following :

List_of_users>
             sunil dhakal>
                        departmnet:"Computer Science",
                        level:"Level 3 Undergraduate",
                        name:"sunil dhakal",
                        student_id:"1412361",
                        username:"1412361@my.brunel.ac.uk",

root.child("List_of_user").addValueEventListener(new ValueEventListener() {

    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot data :dataSnapshot.getChildren()){
            if (data.child(department).exists()&& data.child(level).exists()){
                Set<String> set = new HashSet<String>();
                Iterator i = dataSnapshot.child("List_of_users").getChildren().iterator();
                while (i.hasNext()) {
                    set.add(((DataSnapshot) i.next()).getKey());
                }
                list_of_rooms.clear();
                list_of_rooms.addAll(set);
                arrayAdapter.notifyDataSetChanged();
            }
            else{
                Toast.makeText(searchuser.this,"There is not user with the department and level that was selected",Toast.LENGTH_SHORT).show();
                return;
            }
        }
    }

    public void onCancelled(DatabaseError databaseError) {}
});

I have a spinner where user is able to select department and level and click a button which list all the user in the database with that department and level.

Body:
searchusers.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            final String department = dep.getSelectedItem().toString().trim();
            final String level = lev.getSelectedItem().toString().trim();
            root.addValueEventListener(new ValueEventListener() {

                public void onDataChange(DataSnapshot dataSnapshot) {
                    root.child("List_of_users")
                            .orderByChild("department")
                            .equalTo(department)
                            .orderByChild("level")
                            .equalTo(level);
                    Set<String> set = new HashSet<String>();
                    Iterator i = dataSnapshot.child("List_of_users").getChildren().iterator();
                    while (i.hasNext()) {
                        set.add(((DataSnapshot) i.next()).getKey());
                    }
                    list_of_rooms.clear();
                    list_of_rooms.addAll(set);
                    arrayAdapter.notifyDataSetChanged();
                }

Is this format ok?


问:
How to change z-index for primefaces growl component?
My problem is that, i have a fixed navbar on the top of the page, which has 1030 z-index value. The growl component shows behind the fixed navbar. I tried to override the z-index value for the growl like this (from a custom css file):

.ui-growl {
    z-index: 9999;
}

Note: My custom css file is the last one which is loaded:

```<code>...
 <h:body>
        <f:facet name="last">
            <h:outputStylesheet library="css" name="custom.css"/>
        </f:facet>
...
</code>```

When i check the growl component in chrome it has an inline css style with a z-index value:

```<code><div id="growl_container" class="ui-growl ui-widget" style="z-index: 1004;">...</div>
</code>```

How should i solve this problem?

答:
As .ui-growl has a inline style . So z-index:9999 will not override the css. So you have to use !important in this case.

So add !important to your css as below.

```<code>.ui-growl {
    z-index: 9999 !important;
}
</code>```

Note :Its not a good practice to use !important .
I will suggest you to reduce the z-index of navbar ;)

Body:
My problem is that, i have a fixed navbar on the top of the page, which has 1030 z-index value. The growl component shows behind the fixed navbar. I tried to override the z-index value for the growl like this (from a custom css file):

.ui-growl {
    z-index: 9999;
}

Note: My custom css file is the last one which is loaded:

...
 <h:body>
        <f:facet name="last">
            <h:outputStylesheet library="css" name="custom.css"/>
        </f:facet>
...

When i check the growl component in chrome it has an inline css style with a z-index value:

...

How should i solve this problem?

Body:
As .ui-growl has a inline style . So z-index:9999 will not override the css. So you have to use !important in this case.

So add !important to your css as below.

.ui-growl {
    z-index: 9999 !important;
}

Note :Its not a good practice to use !important .
I will suggest you to reduce the z-index of navbar ;)


问:
Creating self-executable node.js server
I would like to create an executable bash file that will execute the command
node app.js - the goal is to have an executable file that can be opened on a local machine on which node is already installed and the executable is inside the project directory (It's an express.js app).

I'm trying to do it on a mac, I've written a .command file, made it executable and added the command.
Problem is, the process immediately closes, as the terminal seems to automatically add exit; after the last command.
I would like to do it on Windows machines also.

I don't need the entire app in an executable file, only the option to double click a file instead of opening the terminal and manually writing that simple command.

Any idea how to achieve this?

答:
forever should do this.

In additional to node, install forever:

npm i -g forever

And change the command to:

forever app.js

The server should run continuously after the process closes.

To stop the server, you can use another .command file with this command:

forever stopall

Title: Creating self-executable node.js server


问:
Rails 4 - will_paginate and mongodb
I'm getting a no method error when trying to implement pagination on my rails project.
undefined method 'paginate' for #<Mongoid::Criteria:0x007fb256e54588>

In my controller I have:

@user = User.all.paginate(:page => params[:page], :per_page => 10)

In my index.html.erb file I have <%= will_paginate @user %> above my html
 tag and below the closing html
 tag

I have the will_paginate and mongoid-pagination gems installed properly. And I have tried restarting the dev server.. Am I missing anything else?

答:
The will_paginate gem has support for Mongoid out of the box.

```<code>require 'will_paginate/mongoid'
</code>```

In your controller action

```<code>User.all.paginate(page: params[:page], per_page: 10)
</code>```

Title: Rails 4 - will_paginate and mongodb

Body:
The will_paginate gem has support for Mongoid out of the box.

require 'will_paginate/mongoid'

In your controller action

User.all.paginate(page: params[:page], per_page: 10)


问:
Webhooks to desktop
This document states that WebHooks requires you to register a server, with a URL and all, before confirming the website is yours.

I wish to use this API in a (C#) desktop, to get notified when a remote drive change has been made.

I tried registering a domain using an IP address, with the link provided in the document, but it does not work.

Is this API really only to be used by back-end servers?

答:
To use push notifications, you need to do three things:

Register the domain of your receiving URL. For example, if you plan to use https://example.com/notifications as your receiving URL, you need to register https://example.com.

Set up your receiving URL, or "Webhook" callback receiver.

Set up a notification channel for each resource endpoint you want to watch.

The domain must be a URL hosted.  Your not going to be able o use it on a normal pc unless you have a webserver installed on that.   With a registered domain and not just an ip address.

Title: Webhooks to desktop


问:
RadGridView Dynamic columns adding
I'm trying to combine static and dynamic columns in my RadGridView.
The problem is that dynamic column represents object with different properties that should be displayed within one cell.

This is how I add columns:

```<code>InitializeComponent();

        // Get some mock data
        ICollection <EmployeeRecord> employeeRecords = GetDummyData();

        this.grid.ItemsSource = employeeRecords;

        //Add the known columns
        this.grid.Columns.Add(new GridViewDataColumn()
        {
            UniqueName = "EmployeeName"
            , DataMemberBinding = new Binding("EmployeeName")
        });

        this.grid.Columns.Add(new GridViewDataColumn()
        {
            UniqueName = "ID"
            , DataMemberBinding = new Binding("ID")
        });

        // Now add the dynamic number of columns

        // Determines the maximum number of months that any employee has worked.
        int maxNumberOfMonths = employeeRecords.Max((x) => x.Subjects.Count);
        for (int i = 0; i < maxNumberOfMonths; i++)
        {
            this.grid.Columns.Add(new GridViewDataColumn()
            {
                UniqueName = "Subject " + (i + 1) ,
                DataMemberBinding = new Binding("Subjects[" + i + "]"),
                CellTemplate = this.Resources["SubjectTemplate"] as DataTemplate,
                DataType = typeof(Subject)
            });
        }
</code>```

Data template for cell

```<code>    <DataTemplate x:Key="SubjectTemplate" DataType="ticket212220CreateGridColumnsOnTheFly:Subject">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <TextBlock Grid.Row="0" Grid.Column="0" Text="Subject"/>
            <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Name}"/>

            <TextBlock Grid.Row="1" Grid.Column="0" Text="Mark"/>
            <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Mark}"/>

        </Grid>
    </DataTemplate>
</code>```

Model

```<code> public class EmployeeRecord
{
    public string EmployeeName
    {
        get;
        set;
    }

    public int ID
    {
        get;
        set;
    }

    List<Subject> subjects = new List<Subject>();
    public IList<Subject> Subjects
    {
        get { return this.subjects; }
    }
}

public class Subject
{
    public string Name { get; set; }
    public int Mark { get;set; }
}
</code>```

Generating fake data

```<code>      static ICollection<EmployeeRecord> GetDummyData()
    {
        ICollection<EmployeeRecord> employeeRecords = new List<EmployeeRecord>();

        EmployeeRecord stevie = new EmployeeRecord() { EmployeeName = "Steven Gerrard", ID = 333 };
        stevie.Subjects.Add(new Subject
        {
            Name = "Math",
            Mark = 5
        });

        employeeRecords.Add(stevie);

        EmployeeRecord ryan = new EmployeeRecord() { EmployeeName = "Ryan Giggs", ID = 222 };
        ryan.Subjects.Add(new Subject
        {
            Name = "Math",
            Mark = 5
        });
        ryan.Subjects.Add(new Subject
        {
            Name = "Geograph",
            Mark = 3
        });
        employeeRecords.Add(ryan);

        EmployeeRecord john = new EmployeeRecord() { EmployeeName = "John Terry", ID = 111 };
        john.Subjects.Add(new Subject
        {
            Name = "Math",
            Mark = 5
        });
        john.Subjects.Add(new Subject
        {
            Name = "Geograph",
            Mark = 3
        });
        john.Subjects.Add(new Subject
        {
            Name = "Physics",
            Mark = 7
        });
        employeeRecords.Add(john);

        return employeeRecords;
    }
</code>```

Any idea why Name and Mark are not displayed in cell?

答:
The DataContext of a cell is an EmployeeRecord object since you set the ItemsSource property to an ICollection<EmployeeRecord>.

If you want to display all subjects for an employee in a column, you could use an ItemsControl that binds to the Subjects collection of the EmployeeRecord:

```<code><DataTemplate x:Key="SubjectTemplate" DataType="ticket212220CreateGridColumnsOnTheFly:Subject">
    <ItemsControl ItemsSource="{Binding Subjects}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid Margin="0 3 0 0">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>

                    <TextBlock Grid.Row="0" Grid.Column="0" Text="Subject" FontWeight="Bold" Margin="0 0 5 0"/>
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Name}"/>

                    <TextBlock Grid.Row="1" Grid.Column="0" Text="Mark" FontWeight="Bold" Margin="0 0 5 0"/>
                    <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Mark}"/>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</DataTemplate>
</code>```

Title: RadGridView Dynamic columns adding

Body:
I'm trying to combine static and dynamic columns in my RadGridView.
The problem is that dynamic column represents object with different properties that should be displayed within one cell.

This is how I add columns:

InitializeComponent();

        // Get some mock data
        ICollection <EmployeeRecord> employeeRecords = GetDummyData();

        this.grid.ItemsSource = employeeRecords;

        //Add the known columns
        this.grid.Columns.Add(new GridViewDataColumn()
        {
            UniqueName = "EmployeeName"
            , DataMemberBinding = new Binding("EmployeeName")
        });

        this.grid.Columns.Add(new GridViewDataColumn()
        {
            UniqueName = "ID"
            , DataMemberBinding = new Binding("ID")
        });

        // Now add the dynamic number of columns

        // Determines the maximum number of months that any employee has worked.
        int maxNumberOfMonths = employeeRecords.Max((x) => x.Subjects.Count);
        for (int i = 0; i < maxNumberOfMonths; i++)
        {
            this.grid.Columns.Add(new GridViewDataColumn()
            {
                UniqueName = "Subject " + (i + 1) ,
                DataMemberBinding = new Binding("Subjects[" + i + "]"),
                CellTemplate = this.Resources["SubjectTemplate"] as DataTemplate,
                DataType = typeof(Subject)
            });
        }

Data template for cell

    <DataTemplate x:Key="SubjectTemplate" DataType="ticket212220CreateGridColumnsOnTheFly:Subject">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <TextBlock Grid.Row="0" Grid.Column="0" Text="Subject"/>
            <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Name}"/>

            <TextBlock Grid.Row="1" Grid.Column="0" Text="Mark"/>
            <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Mark}"/>

        </Grid>
    </DataTemplate>

Model

 public class EmployeeRecord
{
    public string EmployeeName
    {
        get;
        set;
    }

    public int ID
    {
        get;
        set;
    }

    List<Subject> subjects = new List<Subject>();
    public IList<Subject> Subjects
    {
        get { return this.subjects; }
    }
}

public class Subject
{
    public string Name { get; set; }
    public int Mark { get;set; }
}

Generating fake data

      static ICollection<EmployeeRecord> GetDummyData()
    {
        ICollection<EmployeeRecord> employeeRecords = new List<EmployeeRecord>();

        EmployeeRecord stevie = new EmployeeRecord() { EmployeeName = "Steven Gerrard", ID = 333 };
        stevie.Subjects.Add(new Subject
        {
            Name = "Math",
            Mark = 5
        });

        employeeRecords.Add(stevie);

        EmployeeRecord ryan = new EmployeeRecord() { EmployeeName = "Ryan Giggs", ID = 222 };
        ryan.Subjects.Add(new Subject
        {
            Name = "Math",
            Mark = 5
        });
        ryan.Subjects.Add(new Subject
        {
            Name = "Geograph",
            Mark = 3
        });
        employeeRecords.Add(ryan);

        EmployeeRecord john = new EmployeeRecord() { EmployeeName = "John Terry", ID = 111 };
        john.Subjects.Add(new Subject
        {
            Name = "Math",
            Mark = 5
        });
        john.Subjects.Add(new Subject
        {
            Name = "Geograph",
            Mark = 3
        });
        john.Subjects.Add(new Subject
        {
            Name = "Physics",
            Mark = 7
        });
        employeeRecords.Add(john);

        return employeeRecords;
    }

Any idea why Name and Mark are not displayed in cell?

Body:
The DataContext of a cell is an EmployeeRecord object since you set the ItemsSource property to an ICollection<EmployeeRecord>.

If you want to display all subjects for an employee in a column, you could use an ItemsControl that binds to the Subjects collection of the EmployeeRecord:

<DataTemplate x:Key="SubjectTemplate" DataType="ticket212220CreateGridColumnsOnTheFly:Subject">
    <ItemsControl ItemsSource="{Binding Subjects}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid Margin="0 3 0 0">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>

                    <TextBlock Grid.Row="0" Grid.Column="0" Text="Subject" FontWeight="Bold" Margin="0 0 5 0"/>
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Name}"/>

                    <TextBlock Grid.Row="1" Grid.Column="0" Text="Mark" FontWeight="Bold" Margin="0 0 5 0"/>
                    <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Mark}"/>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</DataTemplate>


问:
SSIS Change datasource in connections
I'm new to SSIS and .net environment, I need to migrate one of the connection to new database server, I have tried by right click on connection and edit the details in dialog testing the connection results into successful notification popup message but when I click ok and review the connection it still the same as it was in the beginning.

I'm trying to change the server name but it never get change

答:
The connection name does not matter but the actual connection does. The connection name will remain the same before you rename it and it will be the name as the first server that you connected to. For example, if you see A as connection name, when you check the connection, it is B, it is still connecting to B if you do not want to rename the connection manager name to A.

UPDATE

if you see the Server name inside the connection manager remains the same even if you tried to change it, that is most likely the connection string was set to dynamic expression not the static one, check the Expression of that connection in the properties page, see whether there is a expression specified for Connection string

2nd UPDATE
If it has expression for Connection string, you have two ways to change to a new connection.

(1) Define a new connection string expression for Connection string in the Expression page.

(2) Remove expression, then the connection manager will not evaluate the connection as what it shows in the expression, after then you could repeat what you did before to specify a connection.

UPDATE after OP accepted it as an answer

I suggested op first try to remove the expression for connection and specify as a new like what he did before, and it shows the correct result.

For the connection string expression, if it does not have any parameter involved in deciding the final connection string, there is no need to specify a pure string to it, only when the connection string need to be a dynamic one, it is necessary to use expression to get the target server name.

Title: SSIS Change datasource in connections


问:
Upgrading from Sitefinity 3.7 to 4 - what are the defining pro's?
I have a number of Sitefinity sites, running on 3.7.

I am looking to hear pro's / cons for updating to version 4. Why would, or wouldn't you?

Edit: forget the cons. Can anyone list convincing pro's that will make a difference for them? I'm not just looking for a re-hash of the feature list, thanks.

Edit2: I still welcome comments once SF4.0 is RTM.

答:
Be sure to read more about the licensing issues with Sitefinity 4.
Sitefinity community is not liking the pricing announcement</p>


问:
JFileChooser showOpenDialog method not working with ActionListener
I have been trying to follow these set of Java tutorials from this website

http://www.homeandlearn.co.uk/java/java.html

However the tutorials are in Netbeans and I am using Eclipse.

Till now there has been no difficulties until now.
http://www.homeandlearn.co.uk/java/opening_files.html

In the given tutorial using JFileChooser to open files through a JMenuItem called 'Open' is shown. However when i use the code given in the website the following error occurs

The method showOpenDialog(Component) in the type JFileChooser is not applicable for the arguments (new ActionListener(){})

This is the code for which the error is occuring.

```<code>    JMenuItem mntmNewMenuItem = new JMenuItem("Open");
    mntmNewMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        int returnVal = db.showOpenDialog(this);
        }
    });
</code>```

So, my question is, what should i change in the above code stub to be able to use the file chooser?

If you want to view the entire code, i will put it in on your request.

答:
Meaning of the error: the method showOpenDialog requires a parameter of type Component but is being called with an ActionListener. More exactly, the given parameter is of an anonymous class implementing ActionListener and not a Component:

```<code>new ActionListener()  { ... }
</code>```

inside the methods declared where I used . . . the keyword this points to the instance of that anonymous class.

See the documentation of showOpenDialog(), it requires a parent or null:

Pops up an "Open File" file chooser dialog. Note that the text that
  appears in the approve button is determined by the L&F.

Parameters:

```<code>parent - the parent component of the dialog, can be null; see showDialog for details
</code>```

And the relevant documentation of showDialog():

The parent argument determines two things: the frame on which the open
  dialog depends and the component whose position the look and feel should
  consider when placing the dialog.
  ...
  If the parent is null, then the dialog depends on no visible window, and
  it's placed in a look-and-feel-dependent position such as the center of
  the screen.

Usually the passed parameter is the JFrame or JPanel that should visually contain the dialog, but it can be null:

```<code>    int returnVal = db.showOpenDialog(null);
</code>```

Body:
I have been trying to follow these set of Java tutorials from this website

http://www.homeandlearn.co.uk/java/java.html

However the tutorials are in Netbeans and I am using Eclipse.

Till now there has been no difficulties until now.
http://www.homeandlearn.co.uk/java/opening_files.html

In the given tutorial using JFileChooser to open files through a JMenuItem called 'Open' is shown. However when i use the code given in the website the following error occurs

The method showOpenDialog(Component) in the type JFileChooser is not applicable for the arguments (new ActionListener(){})

This is the code for which the error is occuring.

    JMenuItem mntmNewMenuItem = new JMenuItem("Open");
    mntmNewMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        int returnVal = db.showOpenDialog(this);
        }
    });

So, my question is, what should i change in the above code stub to be able to use the file chooser?

If you want to view the entire code, i will put it in on your request.

Body:
Meaning of the error: the method showOpenDialog requires a parameter of type Component but is being called with an ActionListener. More exactly, the given parameter is of an anonymous class implementing ActionListener and not a Component:

new ActionListener()  { ... }

inside the methods declared where I used . . . the keyword this points to the instance of that anonymous class.

See the documentation of showOpenDialog(), it requires a parent or null:

Pops up an "Open File" file chooser dialog. Note that the text that
  appears in the approve button is determined by the L&F.

Parameters:

parent - the parent component of the dialog, can be null; see showDialog for details

And the relevant documentation of showDialog():

The parent argument determines two things: the frame on which the open
  dialog depends and the component whose position the look and feel should
  consider when placing the dialog.
  ...
  If the parent is null, then the dialog depends on no visible window, and
  it's placed in a look-and-feel-dependent position such as the center of
  the screen.

Usually the passed parameter is the JFrame or JPanel that should visually contain the dialog, but it can be null:

    int returnVal = db.showOpenDialog(null);


问:
How to calculate aspect ratio of car in matlab?
I am trying to detect a car in a video. After the background subtraction we get the following image:

Now I surround the car with a bounding box.

```<code>blobAnalysis = vision.BlobAnalysis('BoundingBoxOutputPort', true, ...
'AreaOutputPort', false, 'CentroidOutputPort', false, ...
'MinimumBlobArea', 150);
bbox = step(blobAnalysis, filteredForeground);
result = insertShape(frame, 'Rectangle', bbox, 'Color', 'green');
</code>```

The next step is to calculate the aspect ratio of the bounding box. How do I do that ?

The link to the matlab website hosting the code is :
https://in.mathworks.com/help/vision/examples/detecting-cars-using-gaussian-mixture-models.html?prodcode=VP&language=en

答:
Assuming your bounding box (bbox) to be 1 x 4 matrix in MATLAB, which specifies x, y, width and height respectively. Then, your aspect ratio would simply be ratio of width to the height of bbox.</p>

```<code>aspect_ratio = bbox(1, 3) / bbox(1, 4);
</code>```

Body:
I am trying to detect a car in a video. After the background subtraction we get the following image:

Now I surround the car with a bounding box.

blobAnalysis = vision.BlobAnalysis('BoundingBoxOutputPort', true, ...
'AreaOutputPort', false, 'CentroidOutputPort', false, ...
'MinimumBlobArea', 150);
bbox = step(blobAnalysis, filteredForeground);
result = insertShape(frame, 'Rectangle', bbox, 'Color', 'green');

The next step is to calculate the aspect ratio of the bounding box. How do I do that ?

The link to the matlab website hosting the code is :
https://in.mathworks.com/help/vision/examples/detecting-cars-using-gaussian-mixture-models.html?prodcode=VP&language=en

Body:
Assuming your bounding box (bbox) to be 1 x 4 matrix in MATLAB, which specifies x, y, width and height respectively. Then, your aspect ratio would simply be ratio of width to the height of bbox.

aspect_ratio = bbox(1, 3) / bbox(1, 4);


问:
How to concatenate variable name AngularJS?
Concatenate variable name in HTML code like:

app.controller code

```<code>  $scope.name ='abc';
  $scope.abc123 = response.data;
</code>```

HTML code

```<code>   <h1>{{name}}</h1>
   <h1>{{{{name}}123}}</h1> <!-- here i need value of abc123 -->
</code>```

答:
Here it is

angular.module('myApp', []);

function myCtrl($scope) {
  $scope.model = {};
  $scope.name = 'abc'
  $scope.name2 = 'def'
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
  <div ng-controller="myCtrl">
    {{name}} 123 {{name2}}
  </div>
</body></code>```

Body:
Concatenate variable name in HTML code like:

app.controller code

  $scope.name ='abc';
  $scope.abc123 = response.data;

HTML code

{{name}}

{{{{name}}123}}

Body:
Here it is

angular.module('myApp', []);

function myCtrl($scope) {
  $scope.model = {};
  $scope.name = 'abc'
  $scope.name2 = 'def'
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
  <div ng-controller="myCtrl">
    {{name}} 123 {{name2}}
  </div>
</body>


问:
Activity crash when open external url
I have an activity that opens another activity and in this I can not make the code run to open an external URL in android Studio.
The app breaks...
I used the internet permission.

code:

```<code>public void onClick(View v){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.addCategory(Intent.CATEGORY_BROWSABLE);
    intent.setData(Uri.parse("https://www.google.com.br"));
    startActivity(intent);
}
</code>```

Do I need to create another JavaClass to enter these codes, or can I use it in MainActivity java?

Logcat

```<code>Process: br.com.vinnydantas.curriculo, PID: 3355
java.lang.IllegalStateException: Could not find method Linkedin(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.ImageView with id 'imageLinkedin'
    at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4479)
    at android.view.View$DeclaredOnClickListener.onClick(View.java:4443)
    at android.view.View.performClick(View.java:5198)
    at android.view.View$PerformClick.run(View.java:21147)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
You can call like this </p>

```<code>public static void openBrowser(final Context context, String url) {

 if (!url.startsWith(HTTP) && !url.startsWith(HTTPS)) {
        url = HTTP + url;
 }

 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
 context.startActivity(Intent.createChooser(intent, "Choose browser"));// Choose browser is arbitrary :)
}
</code>```

Title: Activity crash when open external url

Body:
I have an activity that opens another activity and in this I can not make the code run to open an external URL in android Studio.
The app breaks...
I used the internet permission.

code:

public void onClick(View v){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.addCategory(Intent.CATEGORY_BROWSABLE);
    intent.setData(Uri.parse("https://www.google.com.br"));
    startActivity(intent);
}

Do I need to create another JavaClass to enter these codes, or can I use it in MainActivity java?

Logcat

Process: br.com.vinnydantas.curriculo, PID: 3355
java.lang.IllegalStateException: Could not find method Linkedin(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.ImageView with id 'imageLinkedin'
    at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4479)
    at android.view.View$DeclaredOnClickListener.onClick(View.java:4443)
    at android.view.View.performClick(View.java:5198)
    at android.view.View$PerformClick.run(View.java:21147)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
You can call like this

public static void openBrowser(final Context context, String url) {

 if (!url.startsWith(HTTP) && !url.startsWith(HTTPS)) {
        url = HTTP + url;
 }

 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
 context.startActivity(Intent.createChooser(intent, "Choose browser"));// Choose browser is arbitrary :)
}


问:
how to escape special characters in the formData in jquery POST?
I want to pass $scope.data.responseFields=CustType,AddedDt. I have tried toString() to make this as string value and pass it as for data. But i see it being passed like this: responseFields=CustType%252CAddedDt

I have tried using escpace characters to supress ",". Still it doesnot work. Can anyone suggest me what exactly is wrong with this?

```<code>$.post(tempURL,$scope.data).done(function(oResponse, status, xhR){
        if(null!=oResponse){
             $scope.data = oResponse.result;
        }
        else
            alert("error retrieving information");
        $scope.$apply();
    }).fail(function(oResponse, status, xhR){
        alert(status);
    });
</code>```

答:
In your case encodeURI should work:
encodeURI($scope.data)

Body:
I want to pass $scope.data.responseFields=CustType,AddedDt. I have tried toString() to make this as string value and pass it as for data. But i see it being passed like this: responseFields=CustType%252CAddedDt

I have tried using escpace characters to supress ",". Still it doesnot work. Can anyone suggest me what exactly is wrong with this?

$.post(tempURL,$scope.data).done(function(oResponse, status, xhR){
        if(null!=oResponse){
             $scope.data = oResponse.result;
        }
        else
            alert("error retrieving information");
        $scope.$apply();
    }).fail(function(oResponse, status, xhR){
        alert(status);
    });


问:
Python opencv and dicom files
while trying to use  opencv with a dicom monochrome file, i saw only one solution : first transform the monochrom  dicom file with pixel values between -2000( black) to 2000 (white)in RGB with
0<=R=G=B<=255. (To ensure grayscale, i have to set R=G=B)
So i made a linear interpolation to go
from first [-2000;2000] to [0, 255]. The results for my pictures were not good so i decided to put a black threeshlod under which all pixels are black and a white threeshol above which all pixels are white. Doing so, i could work with opencv but
1) I would like to automize the black thressholds and the white threesholds
2) since i have 512*512 pixels, the double for loop takes time to execute.

Do you have any idea how i could automize and speedup the process ? Or simply a good idea ?
the code is :

```<code>    # import the necessary packages
from imutils import contours
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import scipy
from skimage import measure
import numpy as np # numeric library needed
import pandas as pd #for dataframe
import argparse # simple argparser
import imutils
import cv2  # for opencv image recognising tool
import dicom
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import pdb

#filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
#filename ="../inputs/12e0e2036f61c8a52ee4471bf813c36a/7e74cdbac4c6db70bade75225258119d.dcm"
dicom_file = dicom.read_file(filename) ## original dicom File
#### a dicom monochrome file has pixel value between approx -2000 and +2000, opencv doesn't work with it#####
#### in a first step we transform those pixel values in (R,G,B)
### to have gray in RGB, simply give the same values for R,G, and B,
####(0,0,0) will be black, (255,255,255) will be white,

## the threeshold to be automized with a proper quartile function of the pixel distribution
black_threeshold=0###pixel value below 0 will be black,
white_threeshold=1400###pixel value above 1400 will be white
wt=white_threeshold
bt=black_threeshold

###### function to transform a dicom to RGB for the use of opencv,
##to be strongly improved, as it takes to much time to run,
## and the linear process should be replaced with an adapted weighted arctan function.
def DicomtoRGB(dicomfile,bt,wt):
    """Create new image(numpy array) filled with certain color in RGB"""
    # Create black blank image
    image = np.zeros((dicomfile.Rows, dicomfile.Columns, 3), np.uint8)
    #loops on image height and width
    i=0
    j=0
    while i<dicomfile.Rows:
        j=0
        while j<dicomfile.Columns:
            color = yaxpb(dicom_file.pixel_array[i][j],bt,wt) #linear transformation to be adapted
            image[i][j] = (color,color,color)## same R,G, B value to obtain greyscale
            j=j+1
        i=i+1
    return image
##linear transformation : from [bt < pxvalue < wt] linear to [0<pyvalue<255]: loss of information...
def yaxpb(pxvalue,bt,wt):
    if pxvalue < bt:
        y=0
    elif pxvalue > wt:
        y=255
    else:
        y=pxvalue*255/(wt-bt)-255*bt/(wt-bt)
    return y

image=DicomtoRGB(dicom_file,bt=0,wt=1400)
>>image
array([[[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       ...,
       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]], dtype=uint8)

## loading the RGB in a proper opencv format
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
## look at the gray file
cv2.imshow("gray", gray)
cv2.waitKey(0)
cv2.destroyWindow("gray")
</code>```

答:
EDIT2 - Now performing the proper transformation

We can vectorize your entire code with numpy. Here's an example:

```<code>import numpy as np

def dicom_to_rgb(img,bt,wt):

    # enforce boundary conditions
    img = np.clip(img,bt,wt)

    # linear transformation
    # multiplicative
    img = np.multiply(img,-255/(wt-bt)).astype(np.int)
    # additive
    img += 255

    # stack thrice on the last axis for R G B
    rgb_img = np.stack([img]*3,axis=-1)

    return rgb_img

    pixels = 512
    img = np.random.randint(-2000,2000,pixels**2).reshape(pixels,pixels)
    bt = 0
    wt = 1400

    rgb = dicom_to_rgb(img,bt,wt)
</code>```

Or with your input:

```<code>dicom_file = dicom.read_file(filename)
img = np.array(dicom_file.pixel_array)

rgb = dicom_to_rgb(img,wt,bt)
</code>```

Title: Python opencv and dicom files

Body:
while trying to use  opencv with a dicom monochrome file, i saw only one solution : first transform the monochrom  dicom file with pixel values between -2000( black) to 2000 (white)in RGB with
0<=R=G=B<=255. (To ensure grayscale, i have to set R=G=B)
So i made a linear interpolation to go
from first [-2000;2000] to [0, 255]. The results for my pictures were not good so i decided to put a black threeshlod under which all pixels are black and a white threeshol above which all pixels are white. Doing so, i could work with opencv but
1) I would like to automize the black thressholds and the white threesholds
2) since i have 512*512 pixels, the double for loop takes time to execute.

Do you have any idea how i could automize and speedup the process ? Or simply a good idea ?
the code is :

    # import the necessary packages
from imutils import contours
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import scipy
from skimage import measure
import numpy as np # numeric library needed
import pandas as pd #for dataframe
import argparse # simple argparser
import imutils
import cv2  # for opencv image recognising tool
import dicom
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import pdb

#filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
#filename ="../inputs/12e0e2036f61c8a52ee4471bf813c36a/7e74cdbac4c6db70bade75225258119d.dcm"
dicom_file = dicom.read_file(filename) ## original dicom File
#### a dicom monochrome file has pixel value between approx -2000 and +2000, opencv doesn't work with it#####
#### in a first step we transform those pixel values in (R,G,B)
### to have gray in RGB, simply give the same values for R,G, and B,
####(0,0,0) will be black, (255,255,255) will be white,

## the threeshold to be automized with a proper quartile function of the pixel distribution
black_threeshold=0###pixel value below 0 will be black,
white_threeshold=1400###pixel value above 1400 will be white
wt=white_threeshold
bt=black_threeshold

###### function to transform a dicom to RGB for the use of opencv,
##to be strongly improved, as it takes to much time to run,
## and the linear process should be replaced with an adapted weighted arctan function.
def DicomtoRGB(dicomfile,bt,wt):
    """Create new image(numpy array) filled with certain color in RGB"""
    # Create black blank image
    image = np.zeros((dicomfile.Rows, dicomfile.Columns, 3), np.uint8)
    #loops on image height and width
    i=0
    j=0
    while i<dicomfile.Rows:
        j=0
        while j<dicomfile.Columns:
            color = yaxpb(dicom_file.pixel_array[i][j],bt,wt) #linear transformation to be adapted
            image[i][j] = (color,color,color)## same R,G, B value to obtain greyscale
            j=j+1
        i=i+1
    return image
##linear transformation : from [bt < pxvalue < wt] linear to [0<pyvalue<255]: loss of information...
def yaxpb(pxvalue,bt,wt):
    if pxvalue < bt:
        y=0
    elif pxvalue > wt:
        y=255
    else:
        y=pxvalue*255/(wt-bt)-255*bt/(wt-bt)
    return y

image=DicomtoRGB(dicom_file,bt=0,wt=1400)
>>image
array([[[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       ...,
       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]], dtype=uint8)

## loading the RGB in a proper opencv format
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
## look at the gray file
cv2.imshow("gray", gray)
cv2.waitKey(0)
cv2.destroyWindow("gray")

Body:
EDIT2 - Now performing the proper transformation

We can vectorize your entire code with numpy. Here's an example:

import numpy as np

def dicom_to_rgb(img,bt,wt):

    # enforce boundary conditions
    img = np.clip(img,bt,wt)

    # linear transformation
    # multiplicative
    img = np.multiply(img,-255/(wt-bt)).astype(np.int)
    # additive
    img += 255

    # stack thrice on the last axis for R G B
    rgb_img = np.stack([img]*3,axis=-1)

    return rgb_img

    pixels = 512
    img = np.random.randint(-2000,2000,pixels**2).reshape(pixels,pixels)
    bt = 0
    wt = 1400

    rgb = dicom_to_rgb(img,bt,wt)

Or with your input:

dicom_file = dicom.read_file(filename)
img = np.array(dicom_file.pixel_array)

rgb = dicom_to_rgb(img,wt,bt)


问:
JavaScript RegExp: Can I get the last matched index or search backwards/RightToLeft?
Suppose I have a string

```<code>foo bar baz foo bar baz foo bar baz foo bar baz
</code>```

I want to find for the last occurance of bar, how can I effectively do this? do I need to loop through add matches? In .NET I can do a RightToLeft search in JS, I guess I can't?

答:
```<code>bar(?!.*bar)
</code>```

will find the last bar in a string:

```<code>bar   # Match bar
(?!   # but only if it's not followed by...
 .*   # zero or more characters
 bar  # literal bar
)     # end of lookahead
</code>```

If your string may contain newline characters, use

```<code>bar(?![\s\S]*bar)
</code>```

instead. [\s\S] matches any character, including newlines.

For example:

```<code>match = subject.match(/bar(?![\s\S]*bar)/);
if (match != null) {
    // matched text: match[0]
    // match start: match.index
}
</code>```

You might also want to surround your search words (if they are indeed words composed of alphanumeric characters) with \b anchors to avoid partial matches.

```<code>\bbar\b(?![\s\S]*\bbar\b)
</code>```

matches the solitary bar instead of the bar within foobar:

```<code>Don't match bar, do match bar, but not foobar!
  no match---^     match---^    no match---^
</code>```

Body:
Suppose I have a string

foo bar baz foo bar baz foo bar baz foo bar baz

I want to find for the last occurance of bar, how can I effectively do this? do I need to loop through add matches? In .NET I can do a RightToLeft search in JS, I guess I can't?

Body:
bar(?!.*bar)

will find the last bar in a string:

bar   # Match bar
(?!   # but only if it's not followed by...
 .*   # zero or more characters
 bar  # literal bar
)     # end of lookahead

If your string may contain newline characters, use

bar(?![\s\S]*bar)

instead. [\s\S] matches any character, including newlines.

For example:

match = subject.match(/bar(?![\s\S]*bar)/);
if (match != null) {
    // matched text: match[0]
    // match start: match.index
}

You might also want to surround your search words (if they are indeed words composed of alphanumeric characters) with \b anchors to avoid partial matches.

\bbar\b(?![\s\S]*\bbar\b)

matches the solitary bar instead of the bar within foobar:

Don't match bar, do match bar, but not foobar!
  no match---^     match---^    no match---^


问:
r - Can you rearrange legend labels in ggplot2?
Apparently worded it terribly first time so here is what I mean. The legend looks like this:

10%

15%

20%

25%

30%

35%

40%

45%

5%

50%

This is done automatically. Does anyone know if you can just move the 5% to the top manually?

答:
Your best bet would be to reorder the corresponding factor before plotting, e.g.

```<code>mydata$percentage <- with(mydata,
        factor(percentage,levels=gtools::mixedsort(levels(percentage))))
</code>```

That should probably work, but a reproducible example would be better.

Body:
Your best bet would be to reorder the corresponding factor before plotting, e.g.

mydata$percentage <- with(mydata,
        factor(percentage,levels=gtools::mixedsort(levels(percentage))))

That should probably work, but a reproducible example would be better.


问:
Creating a function handle to an overloaded `end` function
MATLAB allows overloading various operators for custom classes. One of the unlisted overloadable operators is end, as can be learned from \matlab\lang\end.m:

%   END(A,K,N) is called for indexing expressions involving the object A
%   when END is part of the K-th index out of N indices.  For example,
%   the expression A(end-1,:) calls A's END method with END(A,1,2).
```

<p>An example of such a method is <code>table.end</code> (paste in the MATLAB command line and press "Open Selection" to go to its definition; it is defined in <code>...\matlab\datatypes\@tabular\end.m</code>).</p>

<p>Unlike a normal method, one cannot simply write <code>hEnd = @end</code>, because this gives the error:</p>

```>> hEnd = @end;
 hEnd = @end;
         ↑
Error: Illegal use of reserved keyword "end".
```

On the other hand, writing e = str2func('end'); works, but it links to the default end function (even when temporarily switching to the folder where the desired end.m is found).

Failed attempts include str2func('table>end');, str2func('table\end');, str2func('table.end'); and @(a,b,c)table.end(a,b,c);.

My question: How do I create a handle to the end function of a specific class?

答:
Overloading — If the function you specify overloads a function in a class that is not a fundamental MATLAB class, the function is not associated with the function handle at the time it is constructed. Instead, MATLAB considers the input arguments and determines which implementation to call at the time of evaluation.

Function handles store their absolute path, so when you have a valid handle, you can invoke the function from any location. You do not have to specify the path to the function when creating the handle, only the function name.

so if your 'end' function is in matlab path , matlab consider it as a candidate for evaluation depending on the inputs,in your case if input object is of 'table' class type the feval(str2func('end'),i,j) evaluate the end function which is defined in the folder @table/end.m

Body:
MATLAB allows overloading various operators for custom classes. One of the unlisted overloadable operators is end, as can be learned from \matlab\lang\end.m:

%   END(A,K,N) is called for indexing expressions involving the object A
%   when END is part of the K-th index out of N indices.  For example,
%   the expression A(end-1,:) calls A's END method with END(A,1,2).

An example of such a method is table.end (paste in the MATLAB command line and press "Open Selection" to go to its definition; it is defined in ...\matlab\datatypes\@tabular\end.m).

Unlike a normal method, one cannot simply write hEnd = @end, because this gives the error:

>> hEnd = @end;
 hEnd = @end;
         ↑
Error: Illegal use of reserved keyword "end".

On the other hand, writing e = str2func('end'); works, but it links to the default end function (even when temporarily switching to the folder where the desired end.m is found).

Failed attempts include str2func('table>end');, str2func('table\end');, str2func('table.end'); and @(a,b,c)table.end(a,b,c);.

My question: How do I create a handle to the end function of a specific class?


问:
How to know the size of a file from url befor downloading it?
Hi I am new for android and in my app I have to find the file size before downloading it.

For this I wrote the code below, but it's giving me content length 2588 but the actual size of my file is 745 MB.

Please help me. How can I find the exact file size in MB's?

code:-

```<code>URL url = new URL("mu url");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int file_size = urlConnection.getContentLength();
</code>```

答:
You can try this to find file size:</p>

```<code>String value = null;
long fileSize = getFileSize(file)/1024;
if(fileSize >= 1024)
   value = fileSize/1024+" Mb";
else
   value = fileSize+" Kb";

// this method returns file size
public long getFileSize(File f) {
    long size = 0;
    if (f.isDirectory()) {
        for (File file : f.listFiles()) {
            size += getFolderSize(file);
        }
    } else {
        size=f.length();
    }
    return size;
}
</code>```

Body:
Hi I am new for android and in my app I have to find the file size before downloading it.

For this I wrote the code below, but it's giving me content length 2588 but the actual size of my file is 745 MB.

Please help me. How can I find the exact file size in MB's?

code:-

URL url = new URL("mu url");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int file_size = urlConnection.getContentLength();

Body:
You can try this to find file size:

String value = null;
long fileSize = getFileSize(file)/1024;
if(fileSize >= 1024)
   value = fileSize/1024+" Mb";
else
   value = fileSize+" Kb";

// this method returns file size
public long getFileSize(File f) {
    long size = 0;
    if (f.isDirectory()) {
        for (File file : f.listFiles()) {
            size += getFolderSize(file);
        }
    } else {
        size=f.length();
    }
    return size;
}


问:
In Javascript console.log I am not getting the result
I want console.log to print only firstname if lastname was undefined, instead I get firstname + undefined on the console. What could I change in the code so it only gives me firstname or lastname if one of them is undefined without printing the word 'undefined' in the console, and if both are defined to print them both. This is the code I am trying:

```<code>    document.getElementById("runButton").onclick = function run() {
        var lastName = "arm";
        var firstName;
        function Greeting(firstName, lastName) {
            if (lastName = 'undefined') {
                console.log("Hello, " + firstName + "!");
            } else if (firstName = 'undefiend') {
                console.log("hello, " + lastName + "!!");
            } else {
                console.log("hello, " + firstName + lastName + "!!!");
            }
        }
        Greeting(firstName + " " + lastName);
    };
</code>```

答:
use === instead of == to compare the type as well.

firstName === undefiend

Body:
I want console.log to print only firstname if lastname was undefined, instead I get firstname + undefined on the console. What could I change in the code so it only gives me firstname or lastname if one of them is undefined without printing the word 'undefined' in the console, and if both are defined to print them both. This is the code I am trying:

    document.getElementById("runButton").onclick = function run() {
        var lastName = "arm";
        var firstName;
        function Greeting(firstName, lastName) {
            if (lastName = 'undefined') {
                console.log("Hello, " + firstName + "!");
            } else if (firstName = 'undefiend') {
                console.log("hello, " + lastName + "!!");
            } else {
                console.log("hello, " + firstName + lastName + "!!!");
            }
        }
        Greeting(firstName + " " + lastName);
    };


问:
Decode nested variable-length JSON in ELM
I'm having trouble wrapping my head around decoding a bit complex JSON response in ELM. The JSON response structure(I have no control over it) doesn't match my application's data tree/model.

What will the decoder code look like for this JSON ?

I'm using NoRedInk's Json.Decode.Pipeline - http://package.elm-lang.org/packages/NoRedInk/elm-decode-pipeline/3.0.0/Json-Decode-Pipeline

My project's Github repo - https://github.com/areai51/my-india-elm

The JSON response - https://data.gov.in/node/85987/datastore/export/json

Code

```<code> type alias Leader =
    { attendance : Float      <------- Logic = (Sessions Attended / Total Sessions) * 100
    , name : String
    , state : String
    }

type alias Model =
    { leaders : WebData (List Leader)
    }

initialModel : Model
initialModel =
    { leaders = RemoteData.Loading
    }
</code>```

JSON
Note that there aren't keys I can directly map to inside the "data" array.

```<code>{
   "fields":[   // Definitions for the "data" key
      {
         "id":"a",
         "label":"S.No.",
         "type":"string"
      },
      {
         "id":"b",
         "label":"Division\/Seat No.",
         "type":"string"
      },....
    ],
   "data":[      <------- Leaders
      [
         1,
         3,
         "Smt.  Sonia  Gandhi",      <------- Name
         15,
         12,
         "Uttar Pradesh",      <------- State
         "Rae Barelii",
         20,      <------- Total Sessions (Attendance)
         9      <------- Sessions Attended (Attendance)
      ],
      [
         2,
         15,
         "Shri  Dayanidhi  Maran",      <------- Name
         15,
         12,
         "Tamil Nadu",      <------- State
         "Chennai Central",
         20,      <------- Total Sessions (Attendance)
         7      <------- Sessions Attended (Attendance)
      ],
      [
         3,
         16,
         "Shri  A.  Raja",      <------- Name
         15,
         12,
         "Tamil Nadu ",      <------- State
         "Nilgiris",
         20,      <------- Total Sessions (Attendance)
         16      <------- Sessions Attended (Attendance)
      ],.....
    ]
}
</code>```

UPDATED SOLUTION

```<code>leadersDecoder : Decode.Decoder (List Leader)
leadersDecoder =
    Decode.at [ "data" ] (Decode.list leaderDecoder)

leaderDecoder : Decode.Decoder Leader
leaderDecoder =
    let
        sessionsAttendedDecoder =
            Decode.index 7 Decode.float
                |> Decode.andThen (\total -> attendanceDecoder
                |> Decode.map (\attended -> (attended / total) * 100))
    in
        Decode.map3 Leader
            sessionsAttendedDecoder
            (Decode.index 2 Decode.string)
            (Decode.index 5 Decode.string)

attendanceDecoder : Decode.Decoder Float
attendanceDecoder =
    (Decode.oneOf
        [ Decode.index 8 Decode.float
        , Decode.succeed 0
        ]
    )
</code>```

答:
Json.Decode.index can be used to pull a specific index out of an array with the specified decoder. Couple that with andThen and map to do the attendance calculation based on multiple fields:

import Json.Decode exposing (..)

leaderDecoder : Decoder Leader
leaderDecoder =
    let
        sessionsAttendedDecoder =
            index 7 float
                |> andThen (\total -> index 8 float
                |> map (\attended -> (attended / total) * 100))
    in
        map3 Leader
            sessionsAttendedDecoder
            (index 2 string)
            (index 5 string)
```

Body:
I'm having trouble wrapping my head around decoding a bit complex JSON response in ELM. The JSON response structure(I have no control over it) doesn't match my application's data tree/model.

What will the decoder code look like for this JSON ?

I'm using NoRedInk's Json.Decode.Pipeline - http://package.elm-lang.org/packages/NoRedInk/elm-decode-pipeline/3.0.0/Json-Decode-Pipeline

My project's Github repo - https://github.com/areai51/my-india-elm

The JSON response - https://data.gov.in/node/85987/datastore/export/json

Code

 type alias Leader =
    { attendance : Float      <------- Logic = (Sessions Attended / Total Sessions) * 100
    , name : String
    , state : String
    }

type alias Model =
    { leaders : WebData (List Leader)
    }

initialModel : Model
initialModel =
    { leaders = RemoteData.Loading
    }

JSON
Note that there aren't keys I can directly map to inside the "data" array.

{
   "fields":[   // Definitions for the "data" key
      {
         "id":"a",
         "label":"S.No.",
         "type":"string"
      },
      {
         "id":"b",
         "label":"Division\/Seat No.",
         "type":"string"
      },....
    ],
   "data":[      <------- Leaders
      [
         1,
         3,
         "Smt.  Sonia  Gandhi",      <------- Name
         15,
         12,
         "Uttar Pradesh",      <------- State
         "Rae Barelii",
         20,      <------- Total Sessions (Attendance)
         9      <------- Sessions Attended (Attendance)
      ],
      [
         2,
         15,
         "Shri  Dayanidhi  Maran",      <------- Name
         15,
         12,
         "Tamil Nadu",      <------- State
         "Chennai Central",
         20,      <------- Total Sessions (Attendance)
         7      <------- Sessions Attended (Attendance)
      ],
      [
         3,
         16,
         "Shri  A.  Raja",      <------- Name
         15,
         12,
         "Tamil Nadu ",      <------- State
         "Nilgiris",
         20,      <------- Total Sessions (Attendance)
         16      <------- Sessions Attended (Attendance)
      ],.....
    ]
}

UPDATED SOLUTION

leadersDecoder : Decode.Decoder (List Leader)
leadersDecoder =
    Decode.at [ "data" ] (Decode.list leaderDecoder)

leaderDecoder : Decode.Decoder Leader
leaderDecoder =
    let
        sessionsAttendedDecoder =
            Decode.index 7 Decode.float
                |> Decode.andThen (\total -> attendanceDecoder
                |> Decode.map (\attended -> (attended / total) * 100))
    in
        Decode.map3 Leader
            sessionsAttendedDecoder
            (Decode.index 2 Decode.string)
            (Decode.index 5 Decode.string)

attendanceDecoder : Decode.Decoder Float
attendanceDecoder =
    (Decode.oneOf
        [ Decode.index 8 Decode.float
        , Decode.succeed 0
        ]
    )