问:
How could i display the items from 3 tables joined
How could i display the items from 3 tables below joining using the product_tbl id.

and using foreach. or if there is any alternative way to display it.

The tables

I couldn't get the 3rd table or pictures table.
using my existing code below.
still error.

```<code>$product_list = DB::table('product_tbl')

        ->leftjoin('brand_tbl', 'product_tbl.id', '=', 'brand_tbl.product_id')

        ->select('*')

        ->get();

return vehicles_list;

    $prod_list = array();
    foreach ($product_list as $key => $value) {

        $prod_list [$value->products_name][] = $value;

    }

print_r($prod_list);
</code>```

please help me thank you.

答:
If your table structure isn't set in stone you might try the following structure for a more normalized and indexable structure.  I made some changes - changing product to category, and brand to product.  These labels made more sense to me as I worked with this. I also do full namespaced field names to make joining possible without aliasing all field names.

see the bottom of this post for the SQL to generate and populate these tables

Then a different query will definitely help.  You're not joining on the picture table in your code.

select * from so_category
left outer join so_product on ( product_category_id = category_id)
left outer join so_picture on ( picture_category_id = category_id )
```
<p>But this will probably not return your data like you want to consume it.</p>
<p><img src="https://i.stack.imgur.com/7ZWhX.png" alt="Full Query Result" /></p>
<p>In which case the Mysql Group Concat Function might help.</p>
<pre class="lang-sql prettyprint-override"><code>SELET
so_category.*,
so_product.*,
(select GROUP_CONCAT( DISTINCT picture_url order by picture_url asc separator "," )) AS images
FROM so_category
LEFT OUTER JOIN so_product ON ( product_category_id = category_id)
LEFT OUTER JOIN so_picture ON ( picture_category_id = category_id )
GROUP BY product_id
</code>```

Which yields results that do not duplicate data.

SQL to create and populate tables.

-- Create syntax for TABLE 'so_category'
CREATE TABLE `so_category` (
  `category_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `category_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB CHARSET=utf8;

-- Create syntax for TABLE 'so_picture'
CREATE TABLE `so_picture` (
  `picture_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `picture_url` varchar(100) DEFAULT NULL,
  `picture_category_id` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`picture_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- Create syntax for TABLE 'so_product'
CREATE TABLE `so_product` (
  `product_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `product_name` varchar(100) DEFAULT NULL,
  `product_brand_id` int(11) unsigned DEFAULT NULL,
  `product_category_id` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `so_category` (`category_id`, `category_name`)
VALUES
    (1, 'chocolate'),
    (2, 'flower');

INSERT INTO `so_picture` (`picture_id`, `picture_url`, `picture_category_id`)
VALUES
    (1, 'dmc1', 1),
    (2, 'dmc2', 1),
    (3, 'dmc3', 2),
    (4, 'dmc4', 2),
    (5, 'dmc5', 2);

INSERT INTO `so_product` (`product_id`, `product_name`, `product_brand_id`, `product_category_id`)
VALUES
    (1, 'hershey', NULL, 1),
    (2, 'tobleron', NULL, 1),
    (3, 'oreo', NULL, 1),
    (4, 'roses', NULL, 2),
    (5, 'sunflower', NULL, 2);
```

Body:
How could i display the items from 3 tables below joining using the product_tbl id.

and using foreach. or if there is any alternative way to display it.

The tables

I couldn't get the 3rd table or pictures table.
using my existing code below.
still error.

$product_list = DB::table('product_tbl')

        ->leftjoin('brand_tbl', 'product_tbl.id', '=', 'brand_tbl.product_id')

        ->select('*')

        ->get();

return vehicles_list;

    $prod_list = array();
    foreach ($product_list as $key => $value) {

        $prod_list [$value->products_name][] = $value;

    }

print_r($prod_list);

please help me thank you.

Body:
If your table structure isn't set in stone you might try the following structure for a more normalized and indexable structure.  I made some changes - changing product to category, and brand to product.  These labels made more sense to me as I worked with this. I also do full namespaced field names to make joining possible without aliasing all field names.

see the bottom of this post for the SQL to generate and populate these tables

Then a different query will definitely help.  You're not joining on the picture table in your code.

select * from so_category
left outer join so_product on ( product_category_id = category_id)
left outer join so_picture on ( picture_category_id = category_id )

But this will probably not return your data like you want to consume it.

In which case the Mysql Group Concat Function might help.

SELET
so_category.*,
so_product.*,
(select GROUP_CONCAT( DISTINCT picture_url order by picture_url asc separator "," )) AS images
FROM so_category
LEFT OUTER JOIN so_product ON ( product_category_id = category_id)
LEFT OUTER JOIN so_picture ON ( picture_category_id = category_id )
GROUP BY product_id

Which yields results that do not duplicate data.

SQL to create and populate tables.

-- Create syntax for TABLE 'so_category'
CREATE TABLE `so_category` (
  `category_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `category_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB CHARSET=utf8;

-- Create syntax for TABLE 'so_picture'
CREATE TABLE `so_picture` (
  `picture_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `picture_url` varchar(100) DEFAULT NULL,
  `picture_category_id` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`picture_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- Create syntax for TABLE 'so_product'
CREATE TABLE `so_product` (
  `product_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `product_name` varchar(100) DEFAULT NULL,
  `product_brand_id` int(11) unsigned DEFAULT NULL,
  `product_category_id` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `so_category` (`category_id`, `category_name`)
VALUES
    (1, 'chocolate'),
    (2, 'flower');

INSERT INTO `so_picture` (`picture_id`, `picture_url`, `picture_category_id`)
VALUES
    (1, 'dmc1', 1),
    (2, 'dmc2', 1),
    (3, 'dmc3', 2),
    (4, 'dmc4', 2),
    (5, 'dmc5', 2);

INSERT INTO `so_product` (`product_id`, `product_name`, `product_brand_id`, `product_category_id`)
VALUES
    (1, 'hershey', NULL, 1),
    (2, 'tobleron', NULL, 1),
    (3, 'oreo', NULL, 1),
    (4, 'roses', NULL, 2),
    (5, 'sunflower', NULL, 2);


来源: stackexchange

问:
How do I access a public page variable of the only page from the master page?
I have a page - only ONE page for the entire site:

```<code>using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class CMSPageViewer : System.Web.UI.Page
{
    public int myPageID;

    protected void Page_PreInit(object sender, EventArgs e)
    {
         // Get stuff from the database

         myPageID = 1;

         // Set the Page.MasterPageFile
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Fill in the page contents
        // This looks for and fills in asp:ContentPlaceHolder controls based on ID
    }
}
</code>```

And the master page:

```<code>using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Standard_Page : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int myID = (this.Page as CMSPageViewer).myPageID;
    }
}
</code>```

How can I access ID from the MasterPage that is used?

Casting the page doesn't seem to work. I get the following error:

```<code>Compiler Error Message: CS0246: The type or namespace name 'CMSPageViewer' could not be found (are you missing a using directive or an assembly reference?)
</code>```

答:
I dislike the design, but if there is only a single page in the application, then this begins to make more sense.

In fact, this is not what master pages are for. This is what themes are for.

ContentLicense: CC BY-SA 2.5

Body:
I have a page - only ONE page for the entire site:

using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class CMSPageViewer : System.Web.UI.Page
{
    public int myPageID;

    protected void Page_PreInit(object sender, EventArgs e)
    {
         // Get stuff from the database

         myPageID = 1;

         // Set the Page.MasterPageFile
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Fill in the page contents
        // This looks for and fills in asp:ContentPlaceHolder controls based on ID
    }
}

And the master page:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Standard_Page : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int myID = (this.Page as CMSPageViewer).myPageID;
    }
}

How can I access ID from the MasterPage that is used?

Casting the page doesn't seem to work. I get the following error:

Compiler Error Message: CS0246: The type or namespace name 'CMSPageViewer' could not be found (are you missing a using directive or an assembly reference?)


问:
matlab colormap in python
I need the orignal image once again but its returning greyscale
my teacher said do colormap at the beginning and said that it happens in matlab. so i want to do similar task in python too
Here is my code have a look
please help

ENCRYPTION:

```<code>import numpy as np
from PIL import Image
x = Image.open('1.jpg', 'r')
x = x.convert('L')

y = np.asarray(x.getdata(), dtype=np.int).reshape((x.size[1], x.size[0]))#changed image to matrix getdata for matrix value                                                              # dtype is int type reshape used to break  1d array into 2d array
y = np.asarray(y, dtype=np.uint8)#if values still in range 0-255!
#print(y)
z = y
w = Image.fromarray(y, mode='L')
w.save('grey_scale.bmp')
for i in range(len(z)):
    for j in range(len(z[i])):
        a = z[i][j]
        p = int(bin(a)[2:])
        p = '%08d' % p
        p = p[::-1]
        z[i][j] = int(p, 2)
#print(z)

C = Image.fromarray(z)
C.save('decryption.bmp')
print("DONE")
</code>```

DECRYPTION:

```<code>import numpy as np
from PIL import Image
x = Image.open('decryption.bmp', 'r')

y = np.asarray(x.getdata(), dtype=np.int).reshape((x.size[1], x.size[0]))#changed image to matrix getdata for matrix value
#print(y)                                                             # dtype is int type reshape used to break  1d array into 2d array
y = np.asarray(y, dtype=np.uint8)#if values still in range 0-255!
#print(y)
z = y
for i in range(len(z)):
    for j in range(len(z[i])):
        a = z[i][j]
        p = int(bin(a)[2:])
        p = '%08d' % p
        p = p[::-1]
        z[i][j] = int(p, 2)
#print(z)

C = Image.fromarray(z)
C.save('Final.bmp')
print("DONE")
</code>```

答:
I think(?) what you're looking for is a Colour Mapping function like:

```<code>def create_colourmap(colour, grey):
    c_map = numpy.zeros((256,4), dtype=numpy.float64)
    for i in range(colour.shape[0]):
        for j in range(colour.shape[1]):
            tone = grey[i,j]
            c_map[tone,3] +=1
            count = c_map[tone, 3]
            c_map[tone,:3]  = (c_map[tone,:3] * (count-1)  + colour[i,j])/count
    return c_map.astype(numpy.uint8)[:,:3]
</code>```

Which would give you ONE colour value for each Greyscale value (or Tone).

Your 'bit reversal' procedure could be simplified by another function:

```<code>def reverse_bits(arr):
    for i in range(arr.shape[0]):
        for j in range(arr.shape[1]):
            arr[i][j] = int('{0:08b}'.format(arr[i][j])[::-1], 2)
    return arr
</code>```

Putting this all together, your encrypt function would be:

```<code>def encrypt(infile, outfile):

    with Image.open(infile, 'r') as colour_img:
        colour_arr = numpy.array(colour_img)
        grey_img = colour_img.convert('L')

    grey_arr = numpy.array(grey_img)
    c_map = create_colourmap(colour_arr, grey_arr)

    with Image.fromarray(c_map) as cmap_img:
        cmap_img.save(outfile[:-4]+'_cmap.bmp')

    grey_arr = reverse_bits(grey_arr)

    with Image.fromarray(grey_arr) as c:
        c.save(outfile)
    print("Encryption DONE")
</code>```

And your decrypt function:

```<code>def decrypt(infile, outfile):
    with Image.open(infile, 'r') as x:
        y = numpy.array(x)
    y = reverse_bits(y)

    colour_arr = numpy.zeros((y.shape[0], y.shape[1], 3), dtype=numpy.uint8)

    with Image.open(infile[:-4]+'_cmap.bmp') as cmap_img:
        cmap = numpy.array(cmap_img)

    for i in range(256):
        colour_arr[y==i] = cmap[i]

    with Image.fromarray(colour_arr) as c:
        c.save(outfile)
    print("Decryption DONE")
</code>```

You'll notice that the Colour Mapping will not completely restore the image colour, but will give the image some hue.  I don't know what your assignment is about, but you may want to send the Colour Map along with the encrypted image, or give them another image with similar colouring.

I hope this helps you, but you will need to lean how this works, and comment where necessary to explain whats going on.

Good luck!

ContentLicense: CC BY-SA 3.0

Title: matlab colormap in python

Body:
I need the orignal image once again but its returning greyscale
my teacher said do colormap at the beginning and said that it happens in matlab. so i want to do similar task in python too
Here is my code have a look
please help

ENCRYPTION:

import numpy as np
from PIL import Image
x = Image.open('1.jpg', 'r')
x = x.convert('L')

y = np.asarray(x.getdata(), dtype=np.int).reshape((x.size[1], x.size[0]))#changed image to matrix getdata for matrix value                                                              # dtype is int type reshape used to break  1d array into 2d array
y = np.asarray(y, dtype=np.uint8)#if values still in range 0-255!
#print(y)
z = y
w = Image.fromarray(y, mode='L')
w.save('grey_scale.bmp')
for i in range(len(z)):
    for j in range(len(z[i])):
        a = z[i][j]
        p = int(bin(a)[2:])
        p = '%08d' % p
        p = p[::-1]
        z[i][j] = int(p, 2)
#print(z)

C = Image.fromarray(z)
C.save('decryption.bmp')
print("DONE")

DECRYPTION:

import numpy as np
from PIL import Image
x = Image.open('decryption.bmp', 'r')

y = np.asarray(x.getdata(), dtype=np.int).reshape((x.size[1], x.size[0]))#changed image to matrix getdata for matrix value
#print(y)                                                             # dtype is int type reshape used to break  1d array into 2d array
y = np.asarray(y, dtype=np.uint8)#if values still in range 0-255!
#print(y)
z = y
for i in range(len(z)):
    for j in range(len(z[i])):
        a = z[i][j]
        p = int(bin(a)[2:])
        p = '%08d' % p
        p = p[::-1]
        z[i][j] = int(p, 2)
#print(z)

C = Image.fromarray(z)
C.save('Final.bmp')
print("DONE")

Body:
I think(?) what you're looking for is a Colour Mapping function like:

def create_colourmap(colour, grey):
    c_map = numpy.zeros((256,4), dtype=numpy.float64)
    for i in range(colour.shape[0]):
        for j in range(colour.shape[1]):
            tone = grey[i,j]
            c_map[tone,3] +=1
            count = c_map[tone, 3]
            c_map[tone,:3]  = (c_map[tone,:3] * (count-1)  + colour[i,j])/count
    return c_map.astype(numpy.uint8)[:,:3]

Which would give you ONE colour value for each Greyscale value (or Tone).

Your 'bit reversal' procedure could be simplified by another function:

def reverse_bits(arr):
    for i in range(arr.shape[0]):
        for j in range(arr.shape[1]):
            arr[i][j] = int('{0:08b}'.format(arr[i][j])[::-1], 2)
    return arr

Putting this all together, your encrypt function would be:

def encrypt(infile, outfile):

    with Image.open(infile, 'r') as colour_img:
        colour_arr = numpy.array(colour_img)
        grey_img = colour_img.convert('L')

    grey_arr = numpy.array(grey_img)
    c_map = create_colourmap(colour_arr, grey_arr)

    with Image.fromarray(c_map) as cmap_img:
        cmap_img.save(outfile[:-4]+'_cmap.bmp')

    grey_arr = reverse_bits(grey_arr)

    with Image.fromarray(grey_arr) as c:
        c.save(outfile)
    print("Encryption DONE")

And your decrypt function:

def decrypt(infile, outfile):
    with Image.open(infile, 'r') as x:
        y = numpy.array(x)
    y = reverse_bits(y)

    colour_arr = numpy.zeros((y.shape[0], y.shape[1], 3), dtype=numpy.uint8)

    with Image.open(infile[:-4]+'_cmap.bmp') as cmap_img:
        cmap = numpy.array(cmap_img)

    for i in range(256):
        colour_arr[y==i] = cmap[i]

    with Image.fromarray(colour_arr) as c:
        c.save(outfile)
    print("Decryption DONE")

You'll notice that the Colour Mapping will not completely restore the image colour, but will give the image some hue.  I don't know what your assignment is about, but you may want to send the Colour Map along with the encrypted image, or give them another image with similar colouring.

I hope this helps you, but you will need to lean how this works, and comment where necessary to explain whats going on.

Good luck!


问:
Can we call the button using select(A single selection widget) in bokeh?
https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html (You can see select)

I want to call a button, text input and slider in using select.

```<code>plot_button = Button(label="plot")
color_button = Button(label="Color", disabled=True)
axis_start_value_text = TextInput(title=" Start value=", value="270")
axis_slider = Slider(value=0, start=0, end=100, step=1, title="Title")

button_map = {
    "plot": plot_button,
    "Color": color_button,
    "Start value": axis_start_value_text,
    "Slider": axis_slider
}
button_call = Select(title="Button call", options=sorted(button_map.keys()),
value="plot")
</code>```

In the Select button, when I click on a button, text_input and slider the button appears on the screen that I clicked. İs it possible?

答:
I put up an example app on bitbucket.

You can give css_classes to your widgets, or widgetbox, and then access the div elements contaning the widgets in a CustomJS callback.

I have not found a way to set the display to None from the start, couldn't do it with customm css. So I use a timeout function, you'd need to tweak the timing of the timeout function if you don't want the widgets to appear before they are made invisible.

EDIT:
I updated the code, in fact there is a clean way to hide the widgets initially without using a timeout callback. I use a custom css for that with display:none for all objects with class "hidden". Then in the CustomJS you just need to add or remove the "hidden" to the class name of the widgetboxes.

ContentLicense: CC BY-SA 4.0

Body:
https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html (You can see select)

I want to call a button, text input and slider in using select.

plot_button = Button(label="plot")
color_button = Button(label="Color", disabled=True)
axis_start_value_text = TextInput(title=" Start value=", value="270")
axis_slider = Slider(value=0, start=0, end=100, step=1, title="Title")

button_map = {
    "plot": plot_button,
    "Color": color_button,
    "Start value": axis_start_value_text,
    "Slider": axis_slider
}
button_call = Select(title="Button call", options=sorted(button_map.keys()),
value="plot")

In the Select button, when I click on a button, text_input and slider the button appears on the screen that I clicked. İs it possible?


问:
How convert input type="date" in a timestamp?
I need to convert an <input type="date"> value in a timestamp. This is my HTML code:

```<code> <input type="date" name="date_end" id="date_end">
</code>```

This field has a value that I have put like 25/10/2017

My jQuery code is:

```<code>var dataEnd = $('[name="date_end"]').val();
        if (!dataEnd) {
            return false;
        } else {
            var timestamp_end=$('[name="date_start"]').val().getTime();
            console.log("TIMESTAMP END "+timestamp_end);
.....
}
</code>```

But this is not working... why not?

答:
do this

```<code>var dateEnd = $('#date_end').val()
var var timestamp_end = Date.parse(date_end)
</code>```

or
in a single line

```<code>var timestamp_end = Date.parse($('#date_end').val())
</code>```

it works and it's clean

Body:
I need to convert an <input type="date"> value in a timestamp. This is my HTML code:

 <input type="date" name="date_end" id="date_end">

This field has a value that I have put like 25/10/2017

My jQuery code is:

var dataEnd = $('[name="date_end"]').val();
        if (!dataEnd) {
            return false;
        } else {
            var timestamp_end=$('[name="date_start"]').val().getTime();
            console.log("TIMESTAMP END "+timestamp_end);
.....
}

But this is not working... why not?

Body:
do this

var dateEnd = $('#date_end').val()
var var timestamp_end = Date.parse(date_end)

or
in a single line

var timestamp_end = Date.parse($('#date_end').val())

it works and it's clean


问:
MySQL limit & in wont work together
I have 3 tables and I am trying to get 10 most common languages and number of countries which use this language. My tables are:

```<code>City:           Name|Population|CountryCode
Country:        Name|Code
CoutryLanguage: Language|CountryCode
</code>```

To get the top 10 languages I use the population in each city and join it with country language:

```<code>SELECT cl.language
FROM City ci INNER JOIN CountryLanguage cl ON ci.CountryCode = cl.CountryCode
GROUP BY cl.Language
order by sum(ci.population) desc limit 10
</code>```

My next logic is to join country with language where language is in my new created table:

```<code>select co.Name, cl.Language
from Country co Inner join CountryLanguage cl on co.Code = cl.CountryCode
where cl.Language in (SELECT cl.language
FROM City ci INNER JOIN CountryLanguage cl ON ci.CountryCode = cl.CountryCode
GROUP BY cl.Language
order by sum(ci.population) desc limit 10)
</code>```

This gives me a weird error, I can use it just fine without LIMIT 10 but that just lists all countries and all languages. Is there a way to fix this?? I saw few questions about this but none of them is really clear. Would you mind explaining this error to me?? I can't upgrade my version of sql. Thanks in advance

 I am limiting the number of languages to 10, not the whole table

答:
Try this one please, sorry for all the back and forward but I dont have mysql installed, just writing the SQL here....

```<code>select co.Name, cl.Language
from Country co
Inner join CountryLanguage cl on co.Code = cl.CountryCode
inner join (
  SELECT language from (
    SELECT DISTINCT cl.language
    FROM City ci INNER JOIN CountryLanguage cl ON ci.CountryCode = cl.CountryCode
    GROUP BY cl.Language
    order by sum(ci.population) desc
  ) as lng_tbl
  limit 10
) aux_tbl
on aux_tbl.Language = cl.Language
</code>```

Look at a sub query as it is a table created in runtime/memory, in such case you get the following table:

```<code>SELECT language from (
    SELECT DISTINCT cl.language
    FROM City ci
    INNER JOIN CountryLanguage cl
    ON ci.CountryCode = cl.CountryCode
    GROUP BY cl.Language
    order by sum(ci.population) desc
  ) as lng_tbl
  limit 10

>>> | language |
>>> | English |
>>> | Portuguese |
>>> | ... |
</code>```

After this just wrap it in () and give it a name aux_tbl, then you can use it in the join and a normal table. As an exercise, try to get rid of the outer
select language from () as lng_tbl.

Title: MySQL limit & in wont work together

Body:
I have 3 tables and I am trying to get 10 most common languages and number of countries which use this language. My tables are:

City:           Name|Population|CountryCode
Country:        Name|Code
CoutryLanguage: Language|CountryCode

To get the top 10 languages I use the population in each city and join it with country language:

SELECT cl.language
FROM City ci INNER JOIN CountryLanguage cl ON ci.CountryCode = cl.CountryCode
GROUP BY cl.Language
order by sum(ci.population) desc limit 10

My next logic is to join country with language where language is in my new created table:

select co.Name, cl.Language
from Country co Inner join CountryLanguage cl on co.Code = cl.CountryCode
where cl.Language in (SELECT cl.language
FROM City ci INNER JOIN CountryLanguage cl ON ci.CountryCode = cl.CountryCode
GROUP BY cl.Language
order by sum(ci.population) desc limit 10)

This gives me a weird error, I can use it just fine without LIMIT 10 but that just lists all countries and all languages. Is there a way to fix this?? I saw few questions about this but none of them is really clear. Would you mind explaining this error to me?? I can't upgrade my version of sql. Thanks in advance

 I am limiting the number of languages to 10, not the whole table

Body:
Try this one please, sorry for all the back and forward but I dont have mysql installed, just writing the SQL here....

select co.Name, cl.Language
from Country co
Inner join CountryLanguage cl on co.Code = cl.CountryCode
inner join (
  SELECT language from (
    SELECT DISTINCT cl.language
    FROM City ci INNER JOIN CountryLanguage cl ON ci.CountryCode = cl.CountryCode
    GROUP BY cl.Language
    order by sum(ci.population) desc
  ) as lng_tbl
  limit 10
) aux_tbl
on aux_tbl.Language = cl.Language

Look at a sub query as it is a table created in runtime/memory, in such case you get the following table:

SELECT language from (
    SELECT DISTINCT cl.language
    FROM City ci
    INNER JOIN CountryLanguage cl
    ON ci.CountryCode = cl.CountryCode
    GROUP BY cl.Language
    order by sum(ci.population) desc
  ) as lng_tbl
  limit 10

>>> | language |
>>> | English |
>>> | Portuguese |
>>> | ... |

After this just wrap it in () and give it a name aux_tbl, then you can use it in the join and a normal table. As an exercise, try to get rid of the outer
select language from () as lng_tbl.


问:
Is this the fastest way to parse my XML into JavaScript objects using jQuery?
I have an XML file like this:

```<code><content>
    <box>
        <var1>A1</var1>
        <var2>B1</var2>
        <var3>C1</var3>
        <var4>D1</var4>
    </box>
    <box>
        <var1>A2</var1>
        <var2>B2</var2>
        <var3>C2</var3>
        <var4>D2</var4>
    </box>
    <box>
        <var1>A3</var1>
        <var2>B3</var2>
        <var3>C3</var3>
        <var4>D3</var4>
    </box>
</content>
</code>```

It has 500 box elements which I need to parse into JavaScript objects. I am using this code which works fine but I am a newbie and maybe I am missing something and would like to get suggestions if there is a better/faster way to do it:

```<code>var app = {
    //...
    box: [],

    init: function (file) {
        var that = this;

        $.ajax({
            type: "GET",
            url: file,
            dataType: "xml",
            success: function (xml) {
                $("box", xml).each(function (i) {
                    var e = $(this);
                    that.box[i] = new Box(i, {
                        var1: e.children("var1").text(),
                        var2: e.children("var2").text(),
                        var3: e.children("var3").text(),
                        var4: e.children("var4").text()
                    });
                });
            }
        });
    },
    //...
};
</code>```

Thanks in advance.

答:
You can use browser native XML support which I guess would be fast. However this is varied amongst browsers  e.g.(Firefox : DOMParser, IE: XMLDOM ..).

So instead of just going on and manually handling all browsers, you could make use of something like this https://sites.google.com/a/van-steenbeek.net/archive/explorer_domparser_parsefromstring

Body:
I have an XML file like this:

<content>
    <box>
        <var1>A1</var1>
        <var2>B1</var2>
        <var3>C1</var3>
        <var4>D1</var4>
    </box>
    <box>
        <var1>A2</var1>
        <var2>B2</var2>
        <var3>C2</var3>
        <var4>D2</var4>
    </box>
    <box>
        <var1>A3</var1>
        <var2>B3</var2>
        <var3>C3</var3>
        <var4>D3</var4>
    </box>
</content>

It has 500 box elements which I need to parse into JavaScript objects. I am using this code which works fine but I am a newbie and maybe I am missing something and would like to get suggestions if there is a better/faster way to do it:

var app = {
    //...
    box: [],

    init: function (file) {
        var that = this;

        $.ajax({
            type: "GET",
            url: file,
            dataType: "xml",
            success: function (xml) {
                $("box", xml).each(function (i) {
                    var e = $(this);
                    that.box[i] = new Box(i, {
                        var1: e.children("var1").text(),
                        var2: e.children("var2").text(),
                        var3: e.children("var3").text(),
                        var4: e.children("var4").text()
                    });
                });
            }
        });
    },
    //...
};

Thanks in advance.


问:
When validating data in Laravel 5.5, Update returns "unknown column in field list" error where Create does not
Laravel 5.5 introduces a new streamlined request validation. The idea being that:

```<code>$validData = $request->validate($rules)
</code>```

will return only those fields that are present in the $rules. This is beneficial so that one can then simply User::create($validData) or User::update($validData).

However, I noticed that when I have additional data, which I do validate, but that doesn't exist in the model's (this case User) table, the create method inserts the record, but that the update method returns this error:

```<code>Column not found: 1054 Unknown column 'column_name' in 'field list'
</code>```

I can of course write the relevant field lists out, or use other workaround, but I wonder why are the two methods are behaving differently?

e.g. passing

```<code>array:4 [▼
  "first_name" => "Pedro"
  "last_name" => "Taco"
  "email" => "taco@example.org"
  "operators" => array:1 [▼
    0 => "1"
  ]
]
</code>```

to User::create() inserts the record. Passing the same to User::update() returns an error.
User has $fillable = 'first_name', 'last_name', 'email'

答:
If you want to update specific data use where

```<code>User::where('id',1)->update($validData);
</code>```

If you want to update all rows try something like this

```<code>User::where('id','!=',-1)->update($validData);
</code>```

OR

```<code>User::query()->update($validData);
</code>```

Body:
Laravel 5.5 introduces a new streamlined request validation. The idea being that:

$validData = $request->validate($rules)

will return only those fields that are present in the $rules. This is beneficial so that one can then simply User::create($validData) or User::update($validData).

However, I noticed that when I have additional data, which I do validate, but that doesn't exist in the model's (this case User) table, the create method inserts the record, but that the update method returns this error:

Column not found: 1054 Unknown column 'column_name' in 'field list'

I can of course write the relevant field lists out, or use other workaround, but I wonder why are the two methods are behaving differently?

e.g. passing

array:4 [▼
  "first_name" => "Pedro"
  "last_name" => "Taco"
  "email" => "taco@example.org"
  "operators" => array:1 [▼
    0 => "1"
  ]
]

to User::create() inserts the record. Passing the same to User::update() returns an error.
User has $fillable = 'first_name', 'last_name', 'email'

Body:
If you want to update specific data use where

User::where('id',1)->update($validData);

If you want to update all rows try something like this

User::where('id','!=',-1)->update($validData);

OR

User::query()->update($validData);


问:
Java, How to get number of messages in a topic in apache kafka
I am using apache kafka for messaging. I have implemented the producer and consumer in Java.  How can we get the number of messages in a topic?</p>

答:
Using the Java client of Kafka 2.11-1.0.0, you can do the following thing :

```<code>    KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
    consumer.subscribe(Collections.singletonList("test"));
    while(true) {
        ConsumerRecords<String, String> records = consumer.poll(100);
        for (ConsumerRecord<String, String> record : records) {
            System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());

            // after each message, query the number of messages of the topic
            Set<TopicPartition> partitions = consumer.assignment();
            Map<TopicPartition, Long> offsets = consumer.endOffsets(partitions);
            for(TopicPartition partition : offsets.keySet()) {
                System.out.printf("partition %s is at %d\n", partition.topic(), offsets.get(partition));
            }
        }
    }
</code>```

Output is something like this :

```<code>offset = 10, key = null, value = un
partition test is at 13
offset = 11, key = null, value = deux
partition test is at 13
offset = 12, key = null, value = trois
partition test is at 13
</code>```

Body:
Using the Java client of Kafka 2.11-1.0.0, you can do the following thing :

    KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
    consumer.subscribe(Collections.singletonList("test"));
    while(true) {
        ConsumerRecords<String, String> records = consumer.poll(100);
        for (ConsumerRecord<String, String> record : records) {
            System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());

            // after each message, query the number of messages of the topic
            Set<TopicPartition> partitions = consumer.assignment();
            Map<TopicPartition, Long> offsets = consumer.endOffsets(partitions);
            for(TopicPartition partition : offsets.keySet()) {
                System.out.printf("partition %s is at %d\n", partition.topic(), offsets.get(partition));
            }
        }
    }

Output is something like this :

offset = 10, key = null, value = un
partition test is at 13
offset = 11, key = null, value = deux
partition test is at 13
offset = 12, key = null, value = trois
partition test is at 13


问:
Configuration 'compile' in is deprecated, but all configurations are 'implementation'
I receive following warning while executing gradle in android:

```<code>Configuration 'compile' in project ':app' is deprecated.
</code>```

But all my dependencies included via implementation configuration. (And modules too)
Are there any "invisible" dependencies in gradle?

Here is my main build gradle file: https://pastebin.com/ZJe7zrwn

答:
Are there any "invisible" dependencies in gradle?

I don't know whether it's responsible for this problem, but plugins can add dependencies, and in particular com.google.gms.google-services does:

The google-services plugin has two main functions: ...

Add dependencies for basic libraries required for the services you have enabled.

Body:
I receive following warning while executing gradle in android:

Configuration 'compile' in project ':app' is deprecated.

But all my dependencies included via implementation configuration. (And modules too)
Are there any "invisible" dependencies in gradle?

Here is my main build gradle file: https://pastebin.com/ZJe7zrwn


问:
How to seamlessly convert one similar objects to another both compliant to similar interfaces in typescript?
I have two interfaces. One from backend:

```<code>interface IPrescriptionInfo {
    budget?: BenefitBudget;
    discount?: string;
    prescriprionDate?: number;
    prescriptionAPU?: string;
    prescriptionAmount?: number;
    prescriptionMedicine?: string;
    prescriptionMethod?: string;
    prescriptionMode?: PrescriptionMode;
    prescriptionNumber?: string;
    prescriptionRecordID?: string;
    prescriptionRole?: string;
    prescriptionSpeciality?: string;
    prescriptionState?: PrescriptionStatus;
    prescriptionType?: string;
    prescriptionUserUID?: string;
    protocolID?: string;
    recipeEhrID?: string;
}
</code>```

and another one for internal data model:

```<code>interface IPrescription {
  budget?: string;
  discount: number;
  precriptionControl?: string;
  prescriprionDate: Moment;
  prescriptionAmount: number;
  prescriptionAPU: string;
  prescriptionMedicine: string;
  prescriptionMethod: string;
  prescriptionMode?: string;
  prescriptionNumber: string;
  prescriptionRecordID: string;
  prescriptionRole: string;
  prescriptionSpeciality: string;
  prescriptionState?: string;
  prescriptionType: string;
  prescriptionUserUID: string;
  protocolID: string;
  recipeEhrID: string;
}
</code>```

How to seamlessly convert an object compliant to IPrescriptionInfo to IPrescription using Typescript powers without 'manually' assigning properties one by one?

UPDATE

Just to be clear. Ima looking for the way to avoid junior-style code like:

```<code>const prescription: IPrescription;
const prescriptionInfo: IPrescriptionInfo;
...
prescription.discount = prescriptionInfo.discount;
prescription.prescriprionDate = prescriptionInfo.prescriprionDate;
prescription.prescriptionAPU = prescriptionInfo.prescriptionAPU;
prescription.prescriptionAmount = prescriptionInfo.prescriptionAmount;
...
prescription.recipeEhrID = prescriptionInfo.recipeEhrID;
</code>```

答:
TypeScript is structurally typed, so if the types have all the same members, you can assign them directly:

```<code>let info: IPrescriptionInfo;

let prescription: IPrescription = info;
</code>```

In your case, you face two problems. The first is that the IPrescriptionInfo is a weaker type than IPrescription (all of the members of IPrescriptionInfo are optional, so it could be a completely empty object). The second is that you require type conversions (for example from number to Moment).

This means that you aren't simply mapping the members (if you were, you could use the code at the top of this answer), you actively need to handle undefined members in the source object, and you need to convert values too.

```<code>prescription.prescriprionDate = (info.prescriprionDate)
    ? new Moment(info.prescriprionDate)
    : new Moment(0);
</code>```

If you can make your source object more robust than a possibly empty object, you could reduce or remove the need to write code to map the data.

Body:
I have two interfaces. One from backend:

interface IPrescriptionInfo {
    budget?: BenefitBudget;
    discount?: string;
    prescriprionDate?: number;
    prescriptionAPU?: string;
    prescriptionAmount?: number;
    prescriptionMedicine?: string;
    prescriptionMethod?: string;
    prescriptionMode?: PrescriptionMode;
    prescriptionNumber?: string;
    prescriptionRecordID?: string;
    prescriptionRole?: string;
    prescriptionSpeciality?: string;
    prescriptionState?: PrescriptionStatus;
    prescriptionType?: string;
    prescriptionUserUID?: string;
    protocolID?: string;
    recipeEhrID?: string;
}

and another one for internal data model:

interface IPrescription {
  budget?: string;
  discount: number;
  precriptionControl?: string;
  prescriprionDate: Moment;
  prescriptionAmount: number;
  prescriptionAPU: string;
  prescriptionMedicine: string;
  prescriptionMethod: string;
  prescriptionMode?: string;
  prescriptionNumber: string;
  prescriptionRecordID: string;
  prescriptionRole: string;
  prescriptionSpeciality: string;
  prescriptionState?: string;
  prescriptionType: string;
  prescriptionUserUID: string;
  protocolID: string;
  recipeEhrID: string;
}

How to seamlessly convert an object compliant to IPrescriptionInfo to IPrescription using Typescript powers without 'manually' assigning properties one by one?

UPDATE

Just to be clear. Ima looking for the way to avoid junior-style code like:

const prescription: IPrescription;
const prescriptionInfo: IPrescriptionInfo;
...
prescription.discount = prescriptionInfo.discount;
prescription.prescriprionDate = prescriptionInfo.prescriprionDate;
prescription.prescriptionAPU = prescriptionInfo.prescriptionAPU;
prescription.prescriptionAmount = prescriptionInfo.prescriptionAmount;
...
prescription.recipeEhrID = prescriptionInfo.recipeEhrID;

Body:
TypeScript is structurally typed, so if the types have all the same members, you can assign them directly:

let info: IPrescriptionInfo;

let prescription: IPrescription = info;

In your case, you face two problems. The first is that the IPrescriptionInfo is a weaker type than IPrescription (all of the members of IPrescriptionInfo are optional, so it could be a completely empty object). The second is that you require type conversions (for example from number to Moment).

This means that you aren't simply mapping the members (if you were, you could use the code at the top of this answer), you actively need to handle undefined members in the source object, and you need to convert values too.

prescription.prescriprionDate = (info.prescriprionDate)
    ? new Moment(info.prescriprionDate)
    : new Moment(0);

If you can make your source object more robust than a possibly empty object, you could reduce or remove the need to write code to map the data.


问:
MySQL Join vs. dot in table name
During the reproduction of the old client script, I encountered a problem.
They have two tables in a database called "content.articles" and "content.categories"

```<code>    SELECT content.articles.*, content.categories.id as category_id
    FROM `content.articles`
    INNER JOIN `content.categories`
    ON content.articles.category=content.articles.id
</code>```

I understand that the problem is the dots in the table name.
How should I select properly?

I tried:

```<code>    SELECT content.articles.*
    SELECT `content.articles`.*
    SELECT `content.articles.*`
</code>```

None of these options work.

Thank you very much for your help.

答:
Having dots or other punctuation or even whitespace in table names is permitted by SQL, but you have to "delimit" the identifiers whenever you use them in a query.

It's unusual and not recommended to use a dot in the table name, because it's easy to confuse that with the databasename.tablename syntax for qualified tables.

It would be like if you had a variable in C++ called Foo::Bar. People reading the code would be like: Wait, is that Bar in the class Foo? Or is it a variable that is literally called Foo::Bar? Why in the world would you do such a thing!?!

You can resolve strange table names like this by using identifier delimiters. And you must use the delimiters every time you reference that sort of table name.

Title: MySQL Join vs. dot in table name

Body:
During the reproduction of the old client script, I encountered a problem.
They have two tables in a database called "content.articles" and "content.categories"

    SELECT content.articles.*, content.categories.id as category_id
    FROM `content.articles`
    INNER JOIN `content.categories`
    ON content.articles.category=content.articles.id

I understand that the problem is the dots in the table name.
How should I select properly?

I tried:

    SELECT content.articles.*
    SELECT `content.articles`.*
    SELECT `content.articles.*`

None of these options work.

Thank you very much for your help.


问:
Calculate distance between two objects not located together with identical transforms?

Image link (for those who don't see the inline image)

I am trying to calculate the distance between objects, (trying both position and localPosition using the Vector3.Distance method) but, it would seem there is a problem.

As you can see in the image, the two objects in the scene are not located at the same position however, their transforms tell a different story - they have the exact same transform info (position, rotation, and scale).

Assured it is something simple being missed here but, how to calculate the distance between two objects which are not located at the same location yet have identical transforms?

答:
The following solutions applies to the problem described in the original post, not to programmatically generated meshes

I see that one of them doesn't have its pivot centered.

Make both of your objects child of an empty gameobject, this way you can move them relative to their parent. This will be like changing their pivot.

Calculate the distance based on the parent gameobjects.

Example:

Parent object1 to an empty gameobject. Move object1. Notice the transform of the parent doesn't change. So, you just have to move object1 so that its center aligns with the parent transform. Then, from there, create a prefab. This is your new object1.

Do this for any objects you want to have control on their pivot.

ALTERNATIVE:
If the preceding solution doesn't suit your needs, an easy way to achieve what you want would be to calculate the distance based on the transform.renderer.bounds.center

Your calculation would then be based on the center of the bounds of the object, not its actual position, eliminating the pivot problem.


问:
non-responsive close button in winform
I'm trying to make an Option dialog in Visual Studio. I hid the default ControlBox and made a close button. The dialog work, but the close button isn't. Here's the code:

```<code>    public static class dialog
    {
        static Form gotoBox = new Form();

        public static void showDialog()
        {
            Button closeButton = new Button() { Text = "Close" };

            gotoBox.Controls.Add(closeButton);
            gotoBox.ControlBox = false;
            gotoBox.ShowDialog();

            closeButton.Click += new System.EventHandler(gotoBox_close);
        }

        static void gotoBox_close(object sender, EventArgs e)
        {
            gotoBox.Close();
        }

    }
</code>```

When I click the button, nothing happen. So what did I do wrong?

答:
```<code>gotoBox.ShowDialog(); //This line shows the dialog

//The rest doesn't execute until ShowDialog returns
closeButton.Click += new System.EventHandler(gotoBox_close);
</code>```

<p>You need to move the event registration before the show dialog or else it will not have any effect until dialog is closed          </p>

Title: non-responsive close button in winform

Body:
I'm trying to make an Option dialog in Visual Studio. I hid the default ControlBox and made a close button. The dialog work, but the close button isn't. Here's the code:

    public static class dialog
    {
        static Form gotoBox = new Form();

        public static void showDialog()
        {
            Button closeButton = new Button() { Text = "Close" };

            gotoBox.Controls.Add(closeButton);
            gotoBox.ControlBox = false;
            gotoBox.ShowDialog();

            closeButton.Click += new System.EventHandler(gotoBox_close);
        }

        static void gotoBox_close(object sender, EventArgs e)
        {
            gotoBox.Close();
        }

    }

When I click the button, nothing happen. So what did I do wrong?

Body:
gotoBox.ShowDialog(); //This line shows the dialog

//The rest doesn't execute until ShowDialog returns
closeButton.Click += new System.EventHandler(gotoBox_close);

You need to move the event registration before the show dialog or else it will not have any effect until dialog is closed


问:
Bootstrap 3 Datepicker Months View Only
I have an ASP.NET MVC web app and trying to use Bootstrap 3 Datepicker for my "month/year" field like the one in demo here:
https://eonasdan.github.io/bootstrap-datetimepicker/#min-view-mode

In that demo, it only allows users to select "year" and "month". Not "days". I want the same functionality in my app. However, in my app, it works the same on first click but on succeeding clicks it shows the "days" selection view. Setting the viewMode to 'years' doesn't fix the problem.

My model is as follows:

```<code>public class FilterViewModel
{
    public DateTime? StartMonthYear { get; set; }
    ...
</code>```

My view is as follows:

```<code><div class="col-sm-3">
    @Html.TextBoxFor(model => model.StartMonthYear, new { @class = "month-picker" })
    ...
<script type="text/javascript">
    $(function () {
        $('.month-picker').datetimepicker({
            viewMode: 'months',
            format: 'MM/YYYY',
            useCurrent: false
        });
    });
</script>
</code>```

答: This was a bug in the library and solved. I faced same problem and solved by simply downloading latest version. </p>

Title: Bootstrap 3 Datepicker Months View Only

Body:
I have an ASP.NET MVC web app and trying to use Bootstrap 3 Datepicker for my "month/year" field like the one in demo here:
https://eonasdan.github.io/bootstrap-datetimepicker/#min-view-mode

In that demo, it only allows users to select "year" and "month". Not "days". I want the same functionality in my app. However, in my app, it works the same on first click but on succeeding clicks it shows the "days" selection view. Setting the viewMode to 'years' doesn't fix the problem.

My model is as follows:

public class FilterViewModel
{
    public DateTime? StartMonthYear { get; set; }
    ...

My view is as follows:

    @Html.TextBoxFor(model => model.StartMonthYear, new { @class = "month-picker" })
    ...


问:
AttributeError:'LinearSVC' object has no attribute 'predict_proba'
I am trying to use LinearSVC classifier

Update: Added imports

```<code>import nltk
from nltk.tokenize import word_tokenize
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.svm import LinearSVC, SVC

LinearSVC_classifier = SklearnClassifier(LinearSVC())
LinearSVC_classifier.train(featuresets)
</code>```

But when I am trying to classify it with probabilities

```<code>LinearSVC_classifier.prob_classify(feats)
</code>```

AttributeError occurs:

```<code>AttributeError:'LinearSVC' object has no attribute 'predict_proba'
</code>```

I checked sklearn documentation, it tells that this function exist.

How to fix that?

答:
According to sklearn documentation , the method 'predict_proba' is not defined for 'LinearSVC'

Workaround:

```<code>LinearSVC_classifier = SklearnClassifier(SVC(kernel='linear',probability=True))
</code>```

Use SVC with linear kernel, with probability argument set to True.
Just as explained in here .

Body:
I am trying to use LinearSVC classifier

Update: Added imports

import nltk
from nltk.tokenize import word_tokenize
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.svm import LinearSVC, SVC

LinearSVC_classifier = SklearnClassifier(LinearSVC())
LinearSVC_classifier.train(featuresets)

But when I am trying to classify it with probabilities

LinearSVC_classifier.prob_classify(feats)

AttributeError occurs:

AttributeError:'LinearSVC' object has no attribute 'predict_proba'

I checked sklearn documentation, it tells that this function exist.

How to fix that?

Body:
According to sklearn documentation , the method 'predict_proba' is not defined for 'LinearSVC'

Workaround:

LinearSVC_classifier = SklearnClassifier(SVC(kernel='linear',probability=True))

Use SVC with linear kernel, with probability argument set to True.
Just as explained in here .


问:
Regex: mask all but the last 5 digits, ignoring non-digits
I want to match a number containing 17-23 digits interspersed with spaces or hyphens, then replace all but the last five digits with asterisks. I can match with the following regex:

```<code>((?:(?:\d)([\s-]*)){12,18})(\d[\s-]*){5}
</code>```

My problem is that I can't get the regex to group all instances of [\s-] in the first section, and I have no idea how to get it to replace the initial 12-18 digits with asterisks (*).

Body:
I want to match a number containing 17-23 digits interspersed with spaces or hyphens, then replace all but the last five digits with asterisks. I can match with the following regex:

((?:(?:\d)([\s-]*)){12,18})(\d[\s-]*){5}

My problem is that I can't get the regex to group all instances of [\s-] in the first section, and I have no idea how to get it to replace the initial 12-18 digits with asterisks (*).

Body:
To give a java regex variant to Alan Moore's answer and using all word characters [a-zA-Z0-9] as \w instead of just digits \d.
This will also work with any length string.

public String maskNumber(String number){
    String regex = "\\w(?=(?:\\W*\\w){4,}(?!\\W*\\w))";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(number);
    while(m.find()){
        number = number.replaceFirst(m.group(),"*");
    }
    return number;
}

This example

String[] numbers = {
        "F4546-6565-55654-5457",
        "F4546-6565-55654-54-D57",
        "F4546-6565-55654-54-D;5.7",
        "F4546-6565-55654-54-g5.37",
        "hd6g83g.duj7*ndjd.(njdhg75){7dh i8}",
        "####.####.####.675D-45",
        "****.****.****.675D-45",
        "**",
        "12"
};

for (String number : numbers){
    System.out.println(maskNumber(number));
}

Gives:

*****-****-*****-5457
*****-****-*****-*4-D57
*****-****-*****-*4-D;5.7
*****-****-*****-**-g5.37
*******.*********.(*******){*dh i8}
####.####.####.**5D-45
****.****.****.**5D-45
**
12


问:
Spring Data: Can't Autowire @Repository JpaRepository Interface: "expected at least 1 bean which qualifies as autowire candidate"
My question is almost identical to this one but not the same, because I'm NOT using Spring Boot.
Can't Autowire @Repository annotated interface in Spring Boot
So I can't do @EnableJpaRepositories there's no Spring Boot Runner in my case. I have SpringMVC Controllers inside a Web app.

I'm using Spring Data independently, in a regular old-school SpringMVC application.

I'm getting the error

```<code>Caused by: No qualifying bean of type 'com.myapp.dao.QuestionsDAO' available:
expected at least 1 bean which qualifies as autowire candidate.
</code>```

DAO Interface for Spring Data, note @Repository:

```<code>@Repository
public interface QuestionsDAO extends JpaRepository<Question, Long> {

    public String findById(Long id);

}
</code>```

A Service should then use this DAO, autowired:

Component

```<code>public class SchedulingService {

    @Autowired
    QuestionsDAO questionsDAO;

    public String findLabelById(Long id) {

        return questionsDAO.findById(id);

    }

}
</code>```

Component Scan is enabled, works for everything else.

```<code><context:component-scan base-package="com.myapp" />
</code>```

Is Spring Data only allowed with Spring Boot?

答:
The annotation @EnableJpaRepositories comes from Spring Data, it has nothing to do with Spring Boot. So it would be enough, to have one class annotated with @Configuration and @EnableJpaRepositories.

If you want to do it in XML, you have to add

```<code><jpa:repositories base-package="com.acme.repositories" />
</code>```

You also don't need the @Repository annotation on your interfaces, that annotation has another purpose.

Body:
My question is almost identical to this one but not the same, because I'm NOT using Spring Boot.
Can't Autowire @Repository annotated interface in Spring Boot
So I can't do @EnableJpaRepositories there's no Spring Boot Runner in my case. I have SpringMVC Controllers inside a Web app.

I'm using Spring Data independently, in a regular old-school SpringMVC application.

I'm getting the error

Caused by: No qualifying bean of type 'com.myapp.dao.QuestionsDAO' available:
expected at least 1 bean which qualifies as autowire candidate.

DAO Interface for Spring Data, note @Repository:

@Repository
public interface QuestionsDAO extends JpaRepository<Question, Long> {

    public String findById(Long id);

}

A Service should then use this DAO, autowired:

Component

public class SchedulingService {

    @Autowired
    QuestionsDAO questionsDAO;

    public String findLabelById(Long id) {

        return questionsDAO.findById(id);

    }

}

Component Scan is enabled, works for everything else.

<context:component-scan base-package="com.myapp" />

Is Spring Data only allowed with Spring Boot?

Body:
The annotation @EnableJpaRepositories comes from Spring Data, it has nothing to do with Spring Boot. So it would be enough, to have one class annotated with @Configuration and @EnableJpaRepositories.

If you want to do it in XML, you have to add

<jpa:repositories base-package="com.acme.repositories" />

You also don't need the @Repository annotation on your interfaces, that annotation has another purpose.


问:
angular2 detect changes in ng-content
Is there a way to detect changes in ng-content?

```<code>@Component({
    selector: 'example',
    template: `<ng-content></ng-content>`
})
export class Example {}

@Component({
    selector: 'test',
    template: `
        <example>
            <div *ngFor="let el of elements">{{el}}</div>
        </example>`
})
export class Test {
    elements = [1, 2, 3];

    ngOnInit() {
        setInterval(() => this.elements[0] += 10, 3000);
    }
}
</code>```

I would like to get some information in Example class when my ng-content will change.

Here is plunker

答: If you are trying to complete something every time bound data updates you can use the ngOnChanges() lifecycle hook. Check out the docs, for more info.

Title: angular2 detect changes in ng-content

Body:
Is there a way to detect changes in ng-content?

@Component({
    selector: 'example',
    template: `<ng-content></ng-content>`
})
export class Example {}

@Component({
    selector: 'test',
    template: `
        <example>

{{el}}

        </example>`
})
export class Test {
    elements = [1, 2, 3];

    ngOnInit() {
        setInterval(() => this.elements[0] += 10, 3000);
    }
}

I would like to get some information in Example class when my ng-content will change.

Here is plunker


问:
404 not found error while working with mean stack application
I'm getting the error as 404 not found while trying to post data using postman in chrome.Any kind of help would be highly appreciated.

I'm doing this application from the following link :https://www.youtube.com/watch?v=wtIvu085uU0

here is my code.
app.js

```<code>//importing modules
var express=require('express');
var mongoose=require('mongoose');
var bodyparser=require('body-parser');
var cors=require('cors');
var path=require('path');

var app=express();
const route=require('./router/route');

//connect to mongodb
mongoose.connect('mongodb://localhost:27017/contactlistapp');

//on connection
mongoose.connection.on('connected',()=>{
console.log('successfully connected to database mongodb @27017');

});

mongoose.connection.on('error',()=>{

    if(err)
    {

        console.log('Error in database connection:'+err);
    }

    });

//port number
const port=3000;

//adding middleware-cors
app.use(cors());

//bodyparser
app.use(bodyparser.json());

//adding routes
app.use('/api',route);

//static files
app.use(express.static(path.join(__dirname,'public')));

//testing server
app.get('/',(req,res)=>{
res.send('foobar');
});

app.listen(port,()=>{
console.log('serve started at'+port);

});
</code>```

route.js

```<code>const express=require('express');
const router=express.Router();
const contact=require('../models/contacts');

//retrieving contacts
router.get('/contacts',(req,res,next)=>{
contact.find(function(err,contacts){
    res.json(contacts);
})

});

//retrieving data
router.get('/contacts',(req,res,next)=>{
res.send('Retrieving the contacts list');

});

//add contacts
router.post('./contact',(req,res,next)=>{
let newContact=new contacts({
first_name:req.body.first_name,
last_name:re.body.last_name,
phone:req.body.phone

})

newContact.save((err,contact)=>{
if(err){
res.json({msg: 'Failed to add contact'});

}
else{

    res.json({msg: 'contact added successfully'});

}
})

});

//delete contacts
router.delete('./contact/:id',(req,res,next)=>{
    contact.remove({_id:req.params.id},function(err,result){
if(err)
{
    res.json(err);
}
else{

    res.json(result);
}
    })
    });

module.exports=router;
</code>```

contacts.js

```<code>const mongoose=require('mongoose');

const ContactSchema=mongoose.Schema({
first_name:{
    type:String,
    required:true
},
last_name:{

    type:String,
    required:true
},
phone:{

        type:String,
        required:true
    }

});

const contact=module.exports=mongoose.model('contact',ContactSchema);
</code>```

Getting the following error in postman:

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        ```Cannot POST /api/contacts```
    </body>
</html>

The following is the json data i'm trying to post:

    {
        "first_name":"anand",
        "last_name":"reddy",
        "phone":"1234567813"

    }
</code>```

答: router.post('./contact'  should be router.post('/contacts

Body:
I'm getting the error as 404 not found while trying to post data using postman in chrome.Any kind of help would be highly appreciated.

I'm doing this application from the following link :https://www.youtube.com/watch?v=wtIvu085uU0

here is my code.
app.js

//importing modules
var express=require('express');
var mongoose=require('mongoose');
var bodyparser=require('body-parser');
var cors=require('cors');
var path=require('path');

var app=express();
const route=require('./router/route');

//connect to mongodb
mongoose.connect('mongodb://localhost:27017/contactlistapp');

//on connection
mongoose.connection.on('connected',()=>{
console.log('successfully connected to database mongodb @27017');

});

mongoose.connection.on('error',()=>{

    if(err)
    {

        console.log('Error in database connection:'+err);
    }

    });

//port number
const port=3000;

//adding middleware-cors
app.use(cors());

//bodyparser
app.use(bodyparser.json());

//adding routes
app.use('/api',route);

//static files
app.use(express.static(path.join(__dirname,'public')));

//testing server
app.get('/',(req,res)=>{
res.send('foobar');
});

app.listen(port,()=>{
console.log('serve started at'+port);

});

route.js

const express=require('express');
const router=express.Router();
const contact=require('../models/contacts');

//retrieving contacts
router.get('/contacts',(req,res,next)=>{
contact.find(function(err,contacts){
    res.json(contacts);
})

});

//retrieving data
router.get('/contacts',(req,res,next)=>{
res.send('Retrieving the contacts list');

});

//add contacts
router.post('./contact',(req,res,next)=>{
let newContact=new contacts({
first_name:req.body.first_name,
last_name:re.body.last_name,
phone:req.body.phone

})

newContact.save((err,contact)=>{
if(err){
res.json({msg: 'Failed to add contact'});

}
else{

    res.json({msg: 'contact added successfully'});

}
})

});

//delete contacts
router.delete('./contact/:id',(req,res,next)=>{
    contact.remove({_id:req.params.id},function(err,result){
if(err)
{
    res.json(err);
}
else{

    res.json(result);
}
    })
    });

module.exports=router;

contacts.js

const mongoose=require('mongoose');

const ContactSchema=mongoose.Schema({
first_name:{
    type:String,
    required:true
},
last_name:{

    type:String,
    required:true
},
phone:{

        type:String,
        required:true
    }

});

const contact=module.exports=mongoose.model('contact',ContactSchema);

Getting the following error in postman:

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Error</title>

Cannot POST /api/contacts

The following is the json data i'm trying to post:

    {
        "first_name":"anand",
        "last_name":"reddy",
        "phone":"1234567813"

    }


问:
reverse column order and delete lines
assume I have the following hosts file ,

```<code>#hosts entry
No required line
#Start hosts lists

10.0.0.1 Server1
10.0.0.2   Server2
10.0.0.3   Server1
10.0.0.4  Server2
</code>```

I want to delete this line and reverse order the colmun IP1  Servers etc
so the output in 2nd file will

```<code> #hosts entry
#Start hosts lists

Server1 10.0.0.1
Server2  10.0.0.2
Server1  10.0.0.3
Server2   10.0.0.4
</code>```

I used awk '{print $2,$1}'  but it will reverse everything and I want to just to start reverse from IP1 Server1 and move down , plus deleting the line.

答:
awk to the rescue!

```<code>$ awk 'NR==2{next}                         # skip second line
       r {t=$1; $1=$2; $2=t}               # if r (reverse) flag is set, swap fields
       1;                                  # print line
       /^#Start hosts lists/{r=1}' file    # if the line matches set the r flag

#hosts entry
#Start hosts lists

Server1 10.0.0.1
Server2 10.0.0.2
Server1 10.0.0.3
Server2 10.0.0.4
</code>```

Title: reverse column order and delete lines

Body:
assume I have the following hosts file ,

#hosts entry
No required line
#Start hosts lists

10.0.0.1 Server1
10.0.0.2   Server2
10.0.0.3   Server1
10.0.0.4  Server2

I want to delete this line and reverse order the colmun IP1  Servers etc
so the output in 2nd file will

 #hosts entry
#Start hosts lists

Server1 10.0.0.1
Server2  10.0.0.2
Server1  10.0.0.3
Server2   10.0.0.4

I used awk '{print $2,$1}'  but it will reverse everything and I want to just to start reverse from IP1 Server1 and move down , plus deleting the line.

Body:
awk to the rescue!

$ awk 'NR==2{next}                         # skip second line
       r {t=$1; $1=$2; $2=t}               # if r (reverse) flag is set, swap fields
       1;                                  # print line
       /^#Start hosts lists/{r=1}' file    # if the line matches set the r flag

#hosts entry
#Start hosts lists

Server1 10.0.0.1
Server2 10.0.0.2
Server1 10.0.0.3
Server2 10.0.0.4


问:
Forgot Admin Password on Postgres (Windows Installation), can't reset
I have a Windows PostgreSQL installation.

According to some posts, there is no default password set for the 'postgres' user yet I can't connect using an empty password string.

I'm receiving this exception when I try to connect:

```<code>Caused by: org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"
</code>```

The most relevant tip was this:
https://stackoverflow.com/a/25943227/1005607

```<code>Open  pg_hba.conf
Change md5 -> TRUST
then restart PgAdmin.
</code>```

I tried that and restarted PGAdmin but it still asks me for the password when I try to connect:

The task manager in Windows shows some PostgreSQL processes are running. I can't switch them off.

I have tried this and it failed:

```<code>pg_ctl restart

ERROR:
pg_ctl: no database directory specified and environment variable PGDATA unset

psql.exe postgres
Password: (none)
ERROR:
psql: fe_sendauth: no password supplied
</code>```

How can I reset the default password for user 'postgres'?

答:
Based on AK47's answer and some additional info I fixed it by doing the following,

1) Stop Postgres if currently running, command line below. Need to give it the 'data' dir. In my case C:\PostgreSQL\data

```<code>pg_ctl -D C:\PostgreSQL\data stop
</code>```

2) Edit the file pg_hba.conf (it's also in the \data dir) as follows:

As AK40 wrote, change all MD5 references to trust , e.g.

```<code># TYPE  DATABASE        USER            ADDRESS                 METHOD

# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
# IPv6 local connections:
host    all             all             ::1/128                 trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
host    replication     all             127.0.0.1/32            trust
host    replication     all             ::1/128                 trust
</code>```

3) Now run

```<code>psql -U postgres
</code>```

4) In the PG Command Prompt that appears type,

```<code>ALTER USER Postgres WITH PASSWORD '<newpassword>';
</code>```

5) Save this by typing wq enter to exit the PG Prompt

6) Now start Postgres

```<code>pg_ctl -D C:\PostgreSQL\data start
</code>```

7) Might want to revert the MD5 -> Trust change later in the pg_hba.conf.

Body:
I have a Windows PostgreSQL installation.

According to some posts, there is no default password set for the 'postgres' user yet I can't connect using an empty password string.

I'm receiving this exception when I try to connect:

Caused by: org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"

The most relevant tip was this:
https://stackoverflow.com/a/25943227/1005607

Open  pg_hba.conf
Change md5 -> TRUST
then restart PgAdmin.

I tried that and restarted PGAdmin but it still asks me for the password when I try to connect:

The task manager in Windows shows some PostgreSQL processes are running. I can't switch them off.

I have tried this and it failed:

pg_ctl restart

ERROR:
pg_ctl: no database directory specified and environment variable PGDATA unset

psql.exe postgres
Password: (none)
ERROR:
psql: fe_sendauth: no password supplied

How can I reset the default password for user 'postgres'?

Body:
Based on AK47's answer and some additional info I fixed it by doing the following,

1) Stop Postgres if currently running, command line below. Need to give it the 'data' dir. In my case C:\PostgreSQL\data

pg_ctl -D C:\PostgreSQL\data stop

2) Edit the file pg_hba.conf (it's also in the \data dir) as follows:

As AK40 wrote, change all MD5 references to trust , e.g.

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
# IPv6 local connections:
host    all             all             ::1/128                 trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
host    replication     all             127.0.0.1/32            trust
host    replication     all             ::1/128                 trust

3) Now run

psql -U postgres

4) In the PG Command Prompt that appears type,

ALTER USER Postgres WITH PASSWORD '<newpassword>';

5) Save this by typing wq enter to exit the PG Prompt

6) Now start Postgres

pg_ctl -D C:\PostgreSQL\data start

7) Might want to revert the MD5 -> Trust change later in the pg_hba.conf.


问:
Do you have any good examples of "architecture for architecture's sake"?
Just listening to this week's podcast and thought it would be nice to group together some of your experiences where you've seen the "architecture" side of design dominate things a little more than it should.

Java often gets a bad press in this respect, and an increasingly bad press as the perceived complexity of Java EE increases. My Java experience against time graph nose-dives significantly after 2004 so I don't feel qualified to comment.

My most recent experience is with an architect desperately trying to accurately represent an object model in a set of (relational) database tables (happened to be Oracle). The result is a database schema that's impossible to query efficiently without first pre-joining a bunch of tables (in materialized views).

答: The company I work for produce an application which has a SQL Server backend database. One of the main tables requires joining to itself six times before getting any meaningful data out of it!</p>

OwnerDisplayName: Nick Pierpoint

LastEditorDisplayName: Nick Pierpoint


问:
Display all service names matching a string pattern
I'm trying to display the name (just the name) of all of the installed services that contain the string "SQL". For example, I want to see

SQLAgent$SQL2008_R2

SQLBrowser

SQLWriter

So I try this:

```<code>Get-WmiObject Win32_Service
</code>```

This displays all of the services, but as a list.

```<code>Exit Code : 0
Name      : ProtectedStorage
ProcessId : 664
StartMode : Manual
State     : Running
Status    : OK

Exit Code : 1077
Name      : QWAVE
ProcessId : 0
StartMode : Manual
State     : Stopped
Status    : OK
(etc...)
</code>```

This is good, but I just want to see the name. So I type:

```<code>Get-WmiObject Win32_Service | select-object Name
</code>```

And I get what I expect:

```<code>sppuinotfy
SQLAgent$SQL2008_RT
SQLBrowser
SQLWriter
SSDPSRV
(etc ..)
</code>```

All is good. I take the next step of filtering the names to only include SQL related ones:

```<code>Get-WmiObject Win32_Service | select-object Name | select-string -pattern 'SQL'
</code>```

And now it's confusing. Here is my output:

```<code>@{Name=BcmSqlStartupSvc}
@{Name=MSOLAP$SQL2008_R2}
@{Name=MSSQL$SQL2008_R2}
(etc ...)
</code>```

Why am I getting this output, instead of just the names?
What should I be typing to get just the names?

答:
The easiest way to achieve that is using -Filter Parameter

```<code>Get-WMIObject Win32_Service -Filter "Name LIKE '%SQL%'" |
Select -ExpandProperty Name
</code>```

In case, you want to go with your code only, here is the way you can modify it:

```<code>Get-WmiObject Win32_Service | Select-Object -ExpandProperty Name |
Select-String -pattern 'SQL'
</code>```

Edit: LIKE operator takes a few meta characters to support matching pattern.

[] - for range matching. For example, Name LIKE '[a-f]%' will list all services starting with any letter from a to f.

^ - not. For example, Name LIKE '[^a-f]%' will list services that do not start with any letter from a to f.

_ - matches one letter. For example, Name LIKE 'S_L%' will list services that start with S and followed by any letter.

Body:
I'm trying to display the name (just the name) of all of the installed services that contain the string "SQL". For example, I want to see

SQLAgent$SQL2008_R2

SQLBrowser

SQLWriter

So I try this:

Get-WmiObject Win32_Service

This displays all of the services, but as a list.

Exit Code : 0
Name      : ProtectedStorage
ProcessId : 664
StartMode : Manual
State     : Running
Status    : OK

Exit Code : 1077
Name      : QWAVE
ProcessId : 0
StartMode : Manual
State     : Stopped
Status    : OK
(etc...)

This is good, but I just want to see the name. So I type:

Get-WmiObject Win32_Service | select-object Name

And I get what I expect:

sppuinotfy
SQLAgent$SQL2008_RT
SQLBrowser
SQLWriter
SSDPSRV
(etc ..)

All is good. I take the next step of filtering the names to only include SQL related ones:

Get-WmiObject Win32_Service | select-object Name | select-string -pattern 'SQL'

And now it's confusing. Here is my output:

@{Name=BcmSqlStartupSvc}
@{Name=MSOLAP$SQL2008_R2}
@{Name=MSSQL$SQL2008_R2}
(etc ...)

Why am I getting this output, instead of just the names?
What should I be typing to get just the names?

Body:
The easiest way to achieve that is using -Filter Parameter

Get-WMIObject Win32_Service -Filter "Name LIKE '%SQL%'" |
Select -ExpandProperty Name

In case, you want to go with your code only, here is the way you can modify it:

Get-WmiObject Win32_Service | Select-Object -ExpandProperty Name |
Select-String -pattern 'SQL'

Edit: LIKE operator takes a few meta characters to support matching pattern.

[] - for range matching. For example, Name LIKE '[a-f]%' will list all services starting with any letter from a to f.

^ - not. For example, Name LIKE '[^a-f]%' will list services that do not start with any letter from a to f.

_ - matches one letter. For example, Name LIKE 'S_L%' will list services that start with S and followed by any letter.


问:
How does the GC works with DI in .Net Core 2
Usually when using entity framework I'm using a "using" clause:

```<code>using (var db = new dbcontext())
{
    var blabla = db.table.tolist();
}
</code>```

Now, we have migrated our platform into .Net Core (2) and since there is a great DI mechanism we have decided to use it. Now, instead of using the above way, now we are getting the dbcontext as a parameter in the constructor:

```<code>public MeaningfullNameController(dbcontext db)
{
    this.db = db;
}
</code>```

And when another class needs to use the dbcontext we just pass the above dbcontext in the constructor of the second class.

```<code>public class NewClass(dbcontext db)
{
    this.db = db;
}
</code>```

This situation got me thinking, how does the garbage collector handle this situation?
Is there a difference from the first approach in terms of performance? memory leaks? etc.

Thanks,
Shaul

答:
There is definitely a difference in terms of lifecycle.

In the first approach, you create the object (and allocate memory, and any other resources it needs) via new. The end of the using block will call Dispose on it, freeing any non-memory resources. When the object goes out of scope, the GC can see it is not being used and reclaim it at any time.

In the DI approach, the lifecycle is being managed by the DI-framework. The DI-framework will allocate it and Dispose it. The DI-framework may allocate it once for the entire lifetime of the application, once per invocation of the DI-supporting-method or anything in between. Thus, the lifetime is probably longer and might be substantially longer. If the object lives for a longer time, that means the .NET Core runtime system has allocate it less often and reclaim it less often. It does less work. But it means the objects resources stay used for longer: a connection to the database and any handles will be kept around longer. If you are not using the db only once, for example, during the lifetime of the application and you keep it active for the entire lifetime, you are just wasting resources that you dont need.

In other words, there isn't a simple answer. For resources that are being used frequently, using DI with a lifecycle of per-method-call compared to explicitly calling new + Dispose will involve similar amounts of work. For other types of uses, it will depend on what you are doing and what will "better" for your use case.

In general though, this isn't something you should try and optimize for, unless you know this is causing performance issues. Optimize for the developer first.

Body:
Usually when using entity framework I'm using a "using" clause:

using (var db = new dbcontext())
{
    var blabla = db.table.tolist();
}

Now, we have migrated our platform into .Net Core (2) and since there is a great DI mechanism we have decided to use it. Now, instead of using the above way, now we are getting the dbcontext as a parameter in the constructor:

public MeaningfullNameController(dbcontext db)
{
    this.db = db;
}

And when another class needs to use the dbcontext we just pass the above dbcontext in the constructor of the second class.

public class NewClass(dbcontext db)
{
    this.db = db;
}

This situation got me thinking, how does the garbage collector handle this situation?
Is there a difference from the first approach in terms of performance? memory leaks? etc.

Thanks,
Shaul