问:
c# WinForms - Pass main window's style to dialog boxes
I was just wondering if there was a simpler way of passing style values from the main form to dialog boxes.

My application has user-settable style properties for all the different control types; ForeColor, BackColor, Button ForeColor, Button BackColor, Button FlatStyle etc. I want the dialog boxes to share the same, consistent style.

At the moment, I pass each of these properties to a dialog boxes like this;

(this example shows one of the more simple dialog forms, some have more control types and a lot more style properties)

```<code>using System;
using System.Drawing;
using System.Windows.Forms;

namespace MyApplication
{
    public partial class ConfirmDialog : Form
    {
        public Color ButtonBackColour { private get; set; }
        public Color ButtonForeColour { private get; set; }
        public FlatStyle ButtonFlatStyle { private get; set; }

        public string Message { private get; set; }
        public ConfirmDialog()
        {
            InitializeComponent();
        }

        private void ConfirmDialog_Load(object sender, EventArgs e)
        {
            buttonYES.ForeColor = ButtonForeColour;
            buttonCancel.ForeColor = ButtonForeColour;

            buttonYES.BackColor = ButtonBackColour;
            buttonCancel.BackColor = ButtonBackColour;

            buttonYES.FlatStyle = ButtonFlatStyle;
            buttonCancel.FlatStyle = ButtonFlatStyle;

            lblMsg.Text = Message;
        }
    }
}
</code>```

Ok, now I have a static class which I use to hold the dialog  Initializers;

```<code>using System.Drawing;
using System.Windows.Forms;

namespace MyApplication
{
    public static class ShowDialog
    {
        public static bool ConfirmDialog(string message, Color foreColour, Color backColour, Color buttonBackColour, Color buttonForeColour, FlatStyle buttonFlatStyle)// more style properties to come later on(flatstyle style props etc)
        {
            bool confirm = false;
            using (ConfirmDialog Dialog = new ConfirmDialog()
            {
                Message = message,
                ForeColor = foreColour,
                BackColor = backColour,
                ButtonBackColour = buttonBackColour,
                ButtonForeColour = buttonForeColour,
                ButtonFlatStyle = buttonFlatStyle
            })
            {
                DialogResult dr = Dialog.ShowDialog();
                if (dr == DialogResult.Yes)
                {
                    confirm = true;
                }
                else
                {
                    confirm = false;
                }
            }
            return confirm;
        }
    }
}
</code>```

And finally, this is the mess of arguments I have to include...

```<code>private void buttonDelete_Click(object sender, EventArgs e)
{
    if (ShowDialog.ConfirmDialog("Are you sure you want to delete...?", this.ForeColour, this.BackColour, buttonDelete.BackColour, buttonDelete.ForeColour, buttonDelete.FlatStyle))// any button from main form will do
    {
        // Delete stuff...
    }
}
</code>```

I am unsure if the static class is redundant, but it will make things a lot easier when the dialog boxes start to mount up.

So instead of having to pass all of these individual style properties around, I was wondering if there is a cleaner way. I know there is no Form.Style property. I suppose I could create one. But I wanted to check first with the Gurus to see if I am missing anything.

答:
Since you already have a static class defined for this purpose, you can host your style properties there, and reference them from both your forms and your dialogs.  To implement this, your static class becomes more like this:

```<code>using System.Drawing;
using System.Windows.Forms;

namespace MyApplication
{
    public static class ShowDialog
    {
        public static Color ForeColour { get; set; }
        public static Color BackColour { get; set; }
        public static Color ButtonBackColour { get; set; }
        public static Color ButtonForeColour { get; set; }
        public static FlatStyle ButtonFlatStyle { get; set; }

        public static bool ConfirmDialog(string message)
        {
            bool confirm = false;
            using (ConfirmDialog Dialog = new ConfirmDialog()
            {
                Message = message,
                ForeColor = this.ForeColour,
                BackColor = this.BackColour,
                ButtonBackColour = this.ButtonBackColour,
                ButtonForeColour = this.ButtonForeColour,
                ButtonFlatStyle = this.ButtonFlatStyle
            })
            {
                DialogResult dr = Dialog.ShowDialog();
                if (dr == DialogResult.Yes)
                {
                    confirm = true;
                }
                else
                {
                    confirm = false;
                }
            }
            return confirm;
        }
    }
}
</code>```

You can set these properties when your app launches, and not only will you not have to pass all these extra parameters into your ConfirmDialog method, but you can also reference them from all of your forms, instead of having to define them individually in each form.  This makes it easy to manage your styles in a single place as well if you want to apply skins or need to make changes later.

Body:
I was just wondering if there was a simpler way of passing style values from the main form to dialog boxes.

My application has user-settable style properties for all the different control types; ForeColor, BackColor, Button ForeColor, Button BackColor, Button FlatStyle etc. I want the dialog boxes to share the same, consistent style.

At the moment, I pass each of these properties to a dialog boxes like this;

(this example shows one of the more simple dialog forms, some have more control types and a lot more style properties)

using System;
using System.Drawing;
using System.Windows.Forms;

namespace MyApplication
{
    public partial class ConfirmDialog : Form
    {
        public Color ButtonBackColour { private get; set; }
        public Color ButtonForeColour { private get; set; }
        public FlatStyle ButtonFlatStyle { private get; set; }

        public string Message { private get; set; }
        public ConfirmDialog()
        {
            InitializeComponent();
        }

        private void ConfirmDialog_Load(object sender, EventArgs e)
        {
            buttonYES.ForeColor = ButtonForeColour;
            buttonCancel.ForeColor = ButtonForeColour;

            buttonYES.BackColor = ButtonBackColour;
            buttonCancel.BackColor = ButtonBackColour;

            buttonYES.FlatStyle = ButtonFlatStyle;
            buttonCancel.FlatStyle = ButtonFlatStyle;

            lblMsg.Text = Message;
        }
    }
}

Ok, now I have a static class which I use to hold the dialog  Initializers;

using System.Drawing;
using System.Windows.Forms;

namespace MyApplication
{
    public static class ShowDialog
    {
        public static bool ConfirmDialog(string message, Color foreColour, Color backColour, Color buttonBackColour, Color buttonForeColour, FlatStyle buttonFlatStyle)// more style properties to come later on(flatstyle style props etc)
        {
            bool confirm = false;
            using (ConfirmDialog Dialog = new ConfirmDialog()
            {
                Message = message,
                ForeColor = foreColour,
                BackColor = backColour,
                ButtonBackColour = buttonBackColour,
                ButtonForeColour = buttonForeColour,
                ButtonFlatStyle = buttonFlatStyle
            })
            {
                DialogResult dr = Dialog.ShowDialog();
                if (dr == DialogResult.Yes)
                {
                    confirm = true;
                }
                else
                {
                    confirm = false;
                }
            }
            return confirm;
        }
    }
}

And finally, this is the mess of arguments I have to include...

private void buttonDelete_Click(object sender, EventArgs e)
{
    if (ShowDialog.ConfirmDialog("Are you sure you want to delete...?", this.ForeColour, this.BackColour, buttonDelete.BackColour, buttonDelete.ForeColour, buttonDelete.FlatStyle))// any button from main form will do
    {
        // Delete stuff...
    }
}

I am unsure if the static class is redundant, but it will make things a lot easier when the dialog boxes start to mount up.

So instead of having to pass all of these individual style properties around, I was wondering if there is a cleaner way. I know there is no Form.Style property. I suppose I could create one. But I wanted to check first with the Gurus to see if I am missing anything.

Body:
Since you already have a static class defined for this purpose, you can host your style properties there, and reference them from both your forms and your dialogs.  To implement this, your static class becomes more like this:

using System.Drawing;
using System.Windows.Forms;

namespace MyApplication
{
    public static class ShowDialog
    {
        public static Color ForeColour { get; set; }
        public static Color BackColour { get; set; }
        public static Color ButtonBackColour { get; set; }
        public static Color ButtonForeColour { get; set; }
        public static FlatStyle ButtonFlatStyle { get; set; }

        public static bool ConfirmDialog(string message)
        {
            bool confirm = false;
            using (ConfirmDialog Dialog = new ConfirmDialog()
            {
                Message = message,
                ForeColor = this.ForeColour,
                BackColor = this.BackColour,
                ButtonBackColour = this.ButtonBackColour,
                ButtonForeColour = this.ButtonForeColour,
                ButtonFlatStyle = this.ButtonFlatStyle
            })
            {
                DialogResult dr = Dialog.ShowDialog();
                if (dr == DialogResult.Yes)
                {
                    confirm = true;
                }
                else
                {
                    confirm = false;
                }
            }
            return confirm;
        }
    }
}

You can set these properties when your app launches, and not only will you not have to pass all these extra parameters into your ConfirmDialog method, but you can also reference them from all of your forms, instead of having to define them individually in each form.  This makes it easy to manage your styles in a single place as well if you want to apply skins or need to make changes later.


来源: stackexchange

问:
Grabbing specific sections of a txt file via Powershell
I am new to Powershell scripting, but I feel I am overlooking a simple answer, hopefully some of you can help.

My company exports files from all of our computers with a section around the middle of Mapped Network Printers. It looks like this:

```<code>-------------------------------------------------------------------------
Mapped Network Printers:
NetworkAddress\HP425DN    [DEFAULT PRINTER]
-------------------------------------------------------------------------
Local Printers:
</code>```

What I have been asked to do is copy just the Mapped Network Printers to a new text file.

I tried using Select-String with a context parameter, but I have no way of knowing how many network printers there are, so I can't guess.

I also tried using the following code which I found on this site, but it returns nothing:

```<code>$MapPrint  = gc C:\Users\User1\Documents\Config.txt

$from =  ($MapPrint | Select-String -pattern "Mapped Network Printers:" |
Select-Object LineNumber).LineNumber
$to =  ($MapPrint  | Select-String -pattern "-------------------------------
--------------------------------------------" | Select-Object
LineNumber).LineNumber

$i = 0
$array = @()
foreach ($line in $MapPrint)
{
foreach-object { $i++ }
    if (($i -gt $from) -and ($i -lt $to))
    {
    $array += $line
    }
}
$array
</code>```

I basically want to start the search at "Mapped Network Printers" and end it at the next row of "------"

Any help would be greatly appreciated.

答:
You can do what you are attempting with the foreach-object command and a few additional test conditions. Simply setting a flag when you encounter the Mapped Network Printers: line and then terminating output on the next line -like "---*" will work, e.g.

```<code>## positional parameters
param(
    [Parameter(Mandatory=$true)][string]$infile
)
$beginprn = 0

get-content $infile | foreach-object {
    # terminate condition
    if ([int]$beginprn -eq 1 -and $_ -like "---*") {
        break
    }
    # output Mapped printers
    if ([int]$beginprn -eq 1) {
        write-host $_
    }
    # begin condition
    if ($_ -eq "Mapped Network Printers:") {
        $beginprn = 1
    }
}
</code>```

Example Input File

```<code>-------------------------------------------------------------------------
Mapped Network Printers:
NetworkAddress\HP425DN    [DEFAULT PRINTER]
NetworkAddress\HP4100N
-------------------------------------------------------------------------
Local Printers:
</code>```

Example Use/Output

```<code>PS> parseprn.ps1 .\tmp\prnfile.txt
NetworkAddress\HP425DN    [DEFAULT PRINTER]
NetworkAddress\HP4100N
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to Powershell scripting, but I feel I am overlooking a simple answer, hopefully some of you can help.

My company exports files from all of our computers with a section around the middle of Mapped Network Printers. It looks like this:

-------------------------------------------------------------------------
Mapped Network Printers:
NetworkAddress\HP425DN    [DEFAULT PRINTER]
-------------------------------------------------------------------------
Local Printers:

What I have been asked to do is copy just the Mapped Network Printers to a new text file.

I tried using Select-String with a context parameter, but I have no way of knowing how many network printers there are, so I can't guess.

I also tried using the following code which I found on this site, but it returns nothing:

$MapPrint  = gc C:\Users\User1\Documents\Config.txt

$from =  ($MapPrint | Select-String -pattern "Mapped Network Printers:" |
Select-Object LineNumber).LineNumber
$to =  ($MapPrint  | Select-String -pattern "-------------------------------
--------------------------------------------" | Select-Object
LineNumber).LineNumber

$i = 0
$array = @()
foreach ($line in $MapPrint)
{
foreach-object { $i++ }
    if (($i -gt $from) -and ($i -lt $to))
    {
    $array += $line
    }
}
$array

I basically want to start the search at "Mapped Network Printers" and end it at the next row of "------"

Any help would be greatly appreciated.

Body:
You can do what you are attempting with the foreach-object command and a few additional test conditions. Simply setting a flag when you encounter the Mapped Network Printers: line and then terminating output on the next line -like "---*" will work, e.g.

## positional parameters
param(
    [Parameter(Mandatory=$true)][string]$infile
)
$beginprn = 0

get-content $infile | foreach-object {
    # terminate condition
    if ([int]$beginprn -eq 1 -and $_ -like "---*") {
        break
    }
    # output Mapped printers
    if ([int]$beginprn -eq 1) {
        write-host $_
    }
    # begin condition
    if ($_ -eq "Mapped Network Printers:") {
        $beginprn = 1
    }
}

Example Input File

-------------------------------------------------------------------------
Mapped Network Printers:
NetworkAddress\HP425DN    [DEFAULT PRINTER]
NetworkAddress\HP4100N
-------------------------------------------------------------------------
Local Printers:

Example Use/Output

PS> parseprn.ps1 .\tmp\prnfile.txt
NetworkAddress\HP425DN    [DEFAULT PRINTER]
NetworkAddress\HP4100N


问:
How to format date from mysql to jtextfield
I want to take the date as '07-07-2017' from mysql db to jtextfield.

Error:

Cannot Format Given Object As A Date.

What can I do?

Below is my code.

```<code> public void fisGetir(int fisNo) throws NumberFormatException, ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException{

        String tarih ;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date simdikiZaman = df.parse(ariza.getTarih());
        tarih = new SimpleDateFormat("dd-MM-yyyy").format(simdikiZaman);

        ariza = db.arizaBilgiGetir(fisNo);
        fisNoTextField.setText(String.valueOf(fisNo));
        tarihTextField.setText(ariza.getTarih());
        personelTextField.setText(ariza.getPersonel());
        islemTarihiTextField.setText(ariza.getIslemTarih());
        islemSaatTextField.setText(ariza.getIslemSaat());
    }

     public ArizaBakimListeTableSatirModel arizaBilgiGetir(int fisNo) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException
        {
             if(con == null) con = ConnectionManager.getConnection();
                con.setAutoCommit(true);

             Statement stmt = con.createStatement();
             String yol ="SELECT fisno, tarih, personel, id, islemTarih, islemSaat FROM ariza WHERE fisno= '" + fisNo +"' " ;
             System.out.println(yol);
             ResultSet rs = stmt.executeQuery(yol);
             ArizaBakimListeTableSatirModel ariza = new ArizaBakimListeTableSatirModel();

             while (rs.next()) {
                 ariza.setFisNo(rs.getInt("fisno"));
                 ariza.setTarih(rs.getString("tarih"));
                 ariza.setPersonel(rs.getString("personel"));
                 ariza.setIslemTarihi(rs.getString("islemTarih"));
                 ariza.setIslemSaat(rs.getString("islemSaat"));
                 ariza.setId(rs.getInt("id"));
                 ariza.setKayitDurum(true);  //kayıt durumu var mı kontrol
             }
             return ariza;
        }
</code>```

答:
You have using ariza.getTarih() before you set value to ariza at ariza = db.arizaBilgiGetir(fisNo); so that the value of object you try to parse is can be null or what value you have init in constructor, that's make the error 'can not parse'

```<code>Date simdikiZaman = df.parse(ariza.getTarih());
tarih = new SimpleDateFormat("dd-MM-yyyy").format(simdikiZaman);
ariza = db.arizaBilgiGetir(fisNo);
</code>```

Please change the line ariza = db.arizaBilgiGetir(fisNo); to ahead before using ariza

```<code>ariza = db.arizaBilgiGetir(fisNo);
Date simdikiZaman = df.parse(ariza.getTarih());
tarih = new SimpleDateFormat("dd-MM-yyyy").format(simdikiZaman);
</code>```

Body:
I want to take the date as '07-07-2017' from mysql db to jtextfield.

Error:

Cannot Format Given Object As A Date.

What can I do?

Below is my code.

 public void fisGetir(int fisNo) throws NumberFormatException, ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException{

        String tarih ;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date simdikiZaman = df.parse(ariza.getTarih());
        tarih = new SimpleDateFormat("dd-MM-yyyy").format(simdikiZaman);

        ariza = db.arizaBilgiGetir(fisNo);
        fisNoTextField.setText(String.valueOf(fisNo));
        tarihTextField.setText(ariza.getTarih());
        personelTextField.setText(ariza.getPersonel());
        islemTarihiTextField.setText(ariza.getIslemTarih());
        islemSaatTextField.setText(ariza.getIslemSaat());
    }

     public ArizaBakimListeTableSatirModel arizaBilgiGetir(int fisNo) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException
        {
             if(con == null) con = ConnectionManager.getConnection();
                con.setAutoCommit(true);

             Statement stmt = con.createStatement();
             String yol ="SELECT fisno, tarih, personel, id, islemTarih, islemSaat FROM ariza WHERE fisno= '" + fisNo +"' " ;
             System.out.println(yol);
             ResultSet rs = stmt.executeQuery(yol);
             ArizaBakimListeTableSatirModel ariza = new ArizaBakimListeTableSatirModel();

             while (rs.next()) {
                 ariza.setFisNo(rs.getInt("fisno"));
                 ariza.setTarih(rs.getString("tarih"));
                 ariza.setPersonel(rs.getString("personel"));
                 ariza.setIslemTarihi(rs.getString("islemTarih"));
                 ariza.setIslemSaat(rs.getString("islemSaat"));
                 ariza.setId(rs.getInt("id"));
                 ariza.setKayitDurum(true);  //kayıt durumu var mı kontrol
             }
             return ariza;
        }

Body:
You have using ariza.getTarih() before you set value to ariza at ariza = db.arizaBilgiGetir(fisNo); so that the value of object you try to parse is can be null or what value you have init in constructor, that's make the error 'can not parse'

Date simdikiZaman = df.parse(ariza.getTarih());
tarih = new SimpleDateFormat("dd-MM-yyyy").format(simdikiZaman);
ariza = db.arizaBilgiGetir(fisNo);

Please change the line ariza = db.arizaBilgiGetir(fisNo); to ahead before using ariza

ariza = db.arizaBilgiGetir(fisNo);
Date simdikiZaman = df.parse(ariza.getTarih());
tarih = new SimpleDateFormat("dd-MM-yyyy").format(simdikiZaman);


问:
Is there way to directly reference to a pytest fixture from a simple (non test) function?
Is there a way to reference (and call into) a pytest fixture from a simple function that itself is not either a test_* function or also a fixture?

known examples that can use fixtures:

1)

```<code>def test_mytest( some_cool_pytest_fixture_name, the, rest of, my, args):
    blah
    blah
    some_cool_pytest_fixture_name(args)
    blah

2)
@pytest.fixture()
def my_new_fixture( some_cool_pytest_fixture_name, the, rest of, my, args):
    blah
    blah
    some_cool_pytest_fixture_name(args)
    blah
</code>```

I want to be able to do this:
3)

```<code>def my_simple_function( the, rest of, my, args):
    blah
    blah
    outright.reference.this.pytest.fixture.some_cool_pytest_fixture_name(args)
    blah
</code>```

NOTE:

```<code>from pytest import record_xml_property as property_handler
 ** E ImportError: cannot import name record_xml_property**
</code>```

^^^ This in on a system which does have the record_xml_property

My desire is to be able to do something like this:

```<code>try:
     from pytest import record_xml_property as property_handler
 except:
     @pytest.fixture()
     def property_handler(mykey, myval):
         print('{0}={1}'.format(mykey,myval)
</code>```

^^^ If the above can succeed, then I can always depend on property_handler being there for me as a fixture.

答:
When you use pytest's built in fixture handling, you don't have to worry about how to manage it's availability and memory.

So when you aren't using pytest, you can just import it as a normal function.

```<code>from path.to.cool.pytest.fixture import some_cool_pytest_fixture_name

def my_simple_function(the, rest of, my, args):
    some_cool_pytest_fixture_name(args)
</code>```

Edit

In response to Ken's note, I spent some time trying to access the list of available fixtures defined in pytest.  I've come up with two ways to access the list, but haven't pushed it far enough to get the list in a python list format, only the console output.

From the command line, you can run pytest --fixtures to list all fixtures available.  To do the same thing from a python script, you can run this code

```<code>import pytest
from _pytest import python
from _pytest import config
configs = config._prepareconfig()
python.showfixtures(configs)
</code>```

I think you could access the list if you dig into the pytest Session object and look into its _fixturemanager attribute, but I couldn't figure out a way to create these like the function showfixtures above does.

Body:
Is there a way to reference (and call into) a pytest fixture from a simple function that itself is not either a test_* function or also a fixture?

known examples that can use fixtures:

1)

def test_mytest( some_cool_pytest_fixture_name, the, rest of, my, args):
    blah
    blah
    some_cool_pytest_fixture_name(args)
    blah

2)
@pytest.fixture()
def my_new_fixture( some_cool_pytest_fixture_name, the, rest of, my, args):
    blah
    blah
    some_cool_pytest_fixture_name(args)
    blah

I want to be able to do this:
3)

def my_simple_function( the, rest of, my, args):
    blah
    blah
    outright.reference.this.pytest.fixture.some_cool_pytest_fixture_name(args)
    blah

NOTE:

from pytest import record_xml_property as property_handler
 ** E ImportError: cannot import name record_xml_property**

^^^ This in on a system which does have the record_xml_property

My desire is to be able to do something like this:

try:
     from pytest import record_xml_property as property_handler
 except:
     @pytest.fixture()
     def property_handler(mykey, myval):
         print('{0}={1}'.format(mykey,myval)

^^^ If the above can succeed, then I can always depend on property_handler being there for me as a fixture.

Body:
When you use pytest's built in fixture handling, you don't have to worry about how to manage it's availability and memory.

So when you aren't using pytest, you can just import it as a normal function.

from path.to.cool.pytest.fixture import some_cool_pytest_fixture_name

def my_simple_function(the, rest of, my, args):
    some_cool_pytest_fixture_name(args)

Edit

In response to Ken's note, I spent some time trying to access the list of available fixtures defined in pytest.  I've come up with two ways to access the list, but haven't pushed it far enough to get the list in a python list format, only the console output.

From the command line, you can run pytest --fixtures to list all fixtures available.  To do the same thing from a python script, you can run this code

import pytest
from _pytest import python
from _pytest import config
configs = config._prepareconfig()
python.showfixtures(configs)

I think you could access the list if you dig into the pytest Session object and look into its _fixturemanager attribute, but I couldn't figure out a way to create these like the function showfixtures above does.


问:
Memory Error while using the Binary Opening operation in Sci-Kit Image package for granulometry
I get a memory error when I am using the opening operation in the scikit-image package (it saturates my RAM). This memory error occurs for a 3-D structuring element which is a sphere/ball of radius 16 or larger. I am trying to use granulometry to measure the size distribution of objects in the image (3D array), so I need structuring elements of increasing radii. The memory requirements also increase exponentially and I cannot find a way around it. Is there a simple solution to this problem so that I can use structuring elements of even greater radii? The image size is 200X200X200. TIA </p>

```<code>Traceback (most recent call last):
  File "R3.py", line 124, in <module>
    output_image = skimage.morphology.binary_opening(image, ball)
  File "/usr/lib/python2.7/dist-packages/skimage/morphology/binary.py", line 117, in binary_opening
    eroded = binary_erosion(image, selem)
  File "/usr/lib/python2.7/dist-packages/skimage/morphology/binary.py", line 41, in binary_erosion
    ndimage.convolve(binary, selem, mode='constant', cval=1, output=conv)
  File "/usr/lib/python2.7/dist-packages/scipy/ndimage/filters.py", line 696, in convolve
    origin, True)
  File "/usr/lib/python2.7/dist-packages/scipy/ndimage/filters.py", line 544, in _correlate_or_convolve
    _nd_image.correlate(input, weights, output, mode, cval, origins)
MemoryError
</code>```

答:
A volume of dimensions 200x200x200 is pretty small. A granulometry is made of sequential openings, so you just need 2 more volumes for the computation: one temporary between the erosion and the dilation, and one more for the final results. Which means three volumes total. And the structuring element should be a list of coordinates, so nothing too big.

Consequently, there is absolutely not reason you cannot perform a granulometry on your computer for a volume of such dimensions. The only explanation for the exponential memory use would be that the intermediate results are not erased.

Body:
I get a memory error when I am using the opening operation in the scikit-image package (it saturates my RAM). This memory error occurs for a 3-D structuring element which is a sphere/ball of radius 16 or larger. I am trying to use granulometry to measure the size distribution of objects in the image (3D array), so I need structuring elements of increasing radii. The memory requirements also increase exponentially and I cannot find a way around it. Is there a simple solution to this problem so that I can use structuring elements of even greater radii? The image size is 200X200X200. TIA

Traceback (most recent call last):
  File "R3.py", line 124, in <module>
    output_image = skimage.morphology.binary_opening(image, ball)
  File "/usr/lib/python2.7/dist-packages/skimage/morphology/binary.py", line 117, in binary_opening
    eroded = binary_erosion(image, selem)
  File "/usr/lib/python2.7/dist-packages/skimage/morphology/binary.py", line 41, in binary_erosion
    ndimage.convolve(binary, selem, mode='constant', cval=1, output=conv)
  File "/usr/lib/python2.7/dist-packages/scipy/ndimage/filters.py", line 696, in convolve
    origin, True)
  File "/usr/lib/python2.7/dist-packages/scipy/ndimage/filters.py", line 544, in _correlate_or_convolve
    _nd_image.correlate(input, weights, output, mode, cval, origins)
MemoryError


问:
php select X items from set?
I am using code igniter to retrieve data from a database

What is returned is an array objects

something like

```<code>array(
  [0] = {
    mobile => '027xxxxxx',
    id     => 1
  },
  [1] = {
    mobile => '027xxxxxx',
    id     => 4
  },
  [2] = {
    mobile => '027xxxxxx',
    id     => 5
  },
  [3] = {
    mobile => '027xxxxxx',
    id     => 7
  },
  [4] = {
    mobile => '027xxxxxx',
    id     => 9
  },
  [5] = {
    mobile => '027xxxxxx',
    id     => 10
  },
  [6] = {
    mobile => '027xxxxxx',
    id     => 112
  },
  [7] = {
    mobile => '027xxxxxx',
    id     => 113
  }
)
</code>```

I have a variable called count, this contains an arbitrary number (although always less than the number of objects in the array).

My question is:

Say count = 3,
How would I get an array of 3 random id's from the object?

something like array(4, 9, 1)

I only want to get a single id once

so array(4, 4, 9) would be incorrect.

Note that the id's are not linear.

答:
```<code>$random_keys = array_rand(array_keys($your_array), 3);
</code>```

array_rand

explain -

array_keys only return the key from the original array

array_rand will then pick randomly without repeatability

and the return of array is contains key to your original array

so you can retrieve any information from original array

ContentLicense: CC BY-SA 2.5

Title: php select X items from set?

Body:
I am using code igniter to retrieve data from a database

What is returned is an array objects

something like

array(
  [0] = {
    mobile => '027xxxxxx',
    id     => 1
  },
  [1] = {
    mobile => '027xxxxxx',
    id     => 4
  },
  [2] = {
    mobile => '027xxxxxx',
    id     => 5
  },
  [3] = {
    mobile => '027xxxxxx',
    id     => 7
  },
  [4] = {
    mobile => '027xxxxxx',
    id     => 9
  },
  [5] = {
    mobile => '027xxxxxx',
    id     => 10
  },
  [6] = {
    mobile => '027xxxxxx',
    id     => 112
  },
  [7] = {
    mobile => '027xxxxxx',
    id     => 113
  }
)

I have a variable called count, this contains an arbitrary number (although always less than the number of objects in the array).

My question is:

Say count = 3,
How would I get an array of 3 random id's from the object?

something like array(4, 9, 1)

I only want to get a single id once

so array(4, 4, 9) would be incorrect.

Note that the id's are not linear.

Body:
$random_keys = array_rand(array_keys($your_array), 3);

array_rand

explain -

array_keys only return the key from the original array

array_rand will then pick randomly without repeatability

and the return of array is contains key to your original array

so you can retrieve any information from original array


问:
switch statement always goes to default in javascript
I want to do a simple program that prints out different phrases depending on whether a specific condition is met. We input 2 integer parameters in a function and it evaluates whether one number is greater, less than, or whether both numbers are equal to each other. My code looks like this:

```<code>function CheckNums(num1,num2) {
switch (num1,num2) {
  case (num2>num1):
   console.log('num2 greater than num1');
   break;
  case (num2 === num1):
   console.log('both equal');
   break;
  default:
   console.log('num1 greater than num2');
  }
}
</code>```

Either case, whether I input: CheckNums(4,5) , CheckNums(2,2) , CheckNums(5,4) the program runs default.

IMPORTANT: Im not asking for an alternative solution to this problem. I already managed to solve it using if statements or the ternary operator. What I'm asking is: WHY IS THIS SWITCH NOT WORKING?

Questions that I`ve consulted that didn't solve my problem:

JavaScript switch statement only executes the default case

The sol:This guy had a problem where the Math.random() generator only generated numbers with decimal places, which of course, wouldn't go to either case except default.

JS Switch case not working correctly always default is executed

The sol:This guy was inputing strings as a parameter, and was expecting int values in the cases.

Other notes:

-Maybe the answer lies on using parseint? (Assuming that the parameters are not being inputed as ints.)

-I removed the parenthesis that go in the cases. That didn't solve my problem.

-For the second case, I also experimented using equality operator(==) instead of the Identity operator (===). The second case still did not work.

My best guess for where the problem is hiding:
When I compiled the program in google chrome console, I get the following notification: "undefined". So, I think that's whats not allowing my cases to evaluate the parameters properly. Something is not being defined properly.

答:
WHY IS THIS SWITCH NOT WORKING?

Because what you have written is equivalent to

```<code>const temp = num1,num2; // comma operator evaluates to the second operand
if (temp === (num2>num1)) {
   console.log('num2 greater than num1');
} else if (temp === (num2 === num1)) {
   console.log('both equal');
} else {
   console.log('num1 greater than num2');
}
</code>```

You're comparing a number to booleans, which is never true, so given none of the cases match the default is executed.

Body:
I want to do a simple program that prints out different phrases depending on whether a specific condition is met. We input 2 integer parameters in a function and it evaluates whether one number is greater, less than, or whether both numbers are equal to each other. My code looks like this:

function CheckNums(num1,num2) {
switch (num1,num2) {
  case (num2>num1):
   console.log('num2 greater than num1');
   break;
  case (num2 === num1):
   console.log('both equal');
   break;
  default:
   console.log('num1 greater than num2');
  }
}

Either case, whether I input: CheckNums(4,5) , CheckNums(2,2) , CheckNums(5,4) the program runs default.

IMPORTANT: Im not asking for an alternative solution to this problem. I already managed to solve it using if statements or the ternary operator. What I'm asking is: WHY IS THIS SWITCH NOT WORKING?

Questions that I`ve consulted that didn't solve my problem:

JavaScript switch statement only executes the default case

The sol:This guy had a problem where the Math.random() generator only generated numbers with decimal places, which of course, wouldn't go to either case except default.

JS Switch case not working correctly always default is executed

The sol:This guy was inputing strings as a parameter, and was expecting int values in the cases.

Other notes:

-Maybe the answer lies on using parseint? (Assuming that the parameters are not being inputed as ints.)

-I removed the parenthesis that go in the cases. That didn't solve my problem.

-For the second case, I also experimented using equality operator(==) instead of the Identity operator (===). The second case still did not work.

My best guess for where the problem is hiding:
When I compiled the program in google chrome console, I get the following notification: "undefined". So, I think that's whats not allowing my cases to evaluate the parameters properly. Something is not being defined properly.

Body:
WHY IS THIS SWITCH NOT WORKING?

Because what you have written is equivalent to

const temp = num1,num2; // comma operator evaluates to the second operand
if (temp === (num2>num1)) {
   console.log('num2 greater than num1');
} else if (temp === (num2 === num1)) {
   console.log('both equal');
} else {
   console.log('num1 greater than num2');
}

You're comparing a number to booleans, which is never true, so given none of the cases match the default is executed.


问:
Java @Inject null pointer between modules and ServiceLoader
I have three maven modules:

Commons module: common operations

Provider module: specific implementations to extract data.

Main module: make use of the provider modules.

The sequence works like this:

The main module receives a request, and there's an interface which manages providers (Client) and load providers using ServiceLoader.load(Provider.class).

My Client extracts data (client.retrieveData(request)) selecting the adequate provider.

A provider implements a method buildRequest().

And here's my problem: Support classes from commons module are used in the other two modules. I can use all classes I've injected in my main module, but classes injected in a provider module have a null pointer. For example, this is an implementation of a  provider class:

```<code>public class ScholarProvider extends AbstractProvider {

    @Inject
    private DistanceService distance;
    @Inject
    private final Logger log;
    public static final String URL = "https://scholar.google.com";

    private MapperObjectRDF mapper;

    private String[] domains;
    private Person person;

    public ScholarProvider() {
        person = null;
        mapper = null;
    }
}
</code>```

In ScholarProvider—and in any other provider—distance and log are null. I cannot understand where is the problem. Could it be the problem for loading providers through ServiceLoader? Any suggestions what could be the problem? or is there any possible solution that I could use my DistanceService with a new instantiation?

答: Does your cdi framework know that the provider is a bean to do injection on?  If you are using Spring, you need to annotate the class with either @Named or any spring specific annotation that inherits from @Componenent and then make sure you scan that class.  If your framework does not know about your bean, it won't do any injections.

Body:
I have three maven modules:

Commons module: common operations

Provider module: specific implementations to extract data.

Main module: make use of the provider modules.

The sequence works like this:

The main module receives a request, and there's an interface which manages providers (Client) and load providers using ServiceLoader.load(Provider.class).

My Client extracts data (client.retrieveData(request)) selecting the adequate provider.

A provider implements a method buildRequest().

And here's my problem: Support classes from commons module are used in the other two modules. I can use all classes I've injected in my main module, but classes injected in a provider module have a null pointer. For example, this is an implementation of a  provider class:

public class ScholarProvider extends AbstractProvider {

    @Inject
    private DistanceService distance;
    @Inject
    private final Logger log;
    public static final String URL = "https://scholar.google.com";

    private MapperObjectRDF mapper;

    private String[] domains;
    private Person person;

    public ScholarProvider() {
        person = null;
        mapper = null;
    }
}

In ScholarProvider—and in any other provider—distance and log are null. I cannot understand where is the problem. Could it be the problem for loading providers through ServiceLoader? Any suggestions what could be the problem? or is there any possible solution that I could use my DistanceService with a new instantiation?


问:
Showing newest mysql rows in front end search
Can someone help me show the newest row ids when searching the database. Here is my code, limited to showing 100 results, but it shows the oldest rows first. I would like to show the newest rows. Keep in mind i do not have a time stamp.</p>

```<code>$query_str = "SELECT * FROM puppy_data
              WHERE (`breed` LIKE '%".$query."%')
              OR (`sex` LIKE '%".$query."%')
              LIMIT 100 " ;
</code>```

答:
Try this (assuming you have a row called 'id').</p>

```<code>$query_str = "SELECT * FROM puppy_data
              WHERE (breed LIKE '%".$query."%')
              OR (sex LIKE '%".$query."%')
              ORDER BY id SORT DESC LIMIT 100" ;
</code>```

Body:
Can someone help me show the newest row ids when searching the database. Here is my code, limited to showing 100 results, but it shows the oldest rows first. I would like to show the newest rows. Keep in mind i do not have a time stamp.

$query_str = "SELECT * FROM puppy_data
              WHERE (`breed` LIKE '%".$query."%')
              OR (`sex` LIKE '%".$query."%')
              LIMIT 100 " ;

Body:
Try this (assuming you have a row called 'id').

$query_str = "SELECT * FROM puppy_data
              WHERE (breed LIKE '%".$query."%')
              OR (sex LIKE '%".$query."%')
              ORDER BY id SORT DESC LIMIT 100" ;


问:
How to create summed variables using object values from List of objects in Scala?
I have an class

```<code>class Test(val first: Int, val second: Int, val third: Int)
</code>```

Class Test may have other attributes than first, second, and third.

And I have a list:

```<code>val list: List[Test] = List(new Test(0,1,2), new Test(1,14,2), new Test(7,15,2))
</code>```

How would I use foldLeft here to add together all first`s, second's, third's together to end up with variables:

allFirsts = 8

allSeconds = 30

allThirds = 6

I already have something like this worked out:

```<code>val (totalFirsts, totalSeconds, totalThirds) = list.foldLeft(0, 0, 0){ (sum, l) => (sum._1 + l.first , sum._2 + l.second, sum._3 + l.third) }
</code>```

It seems to work fine, but I don't like the readability of _1, _2, and _3.  Maybe I can use case here to decompose values but I am just not sure how to make it all work together.

答:
You can define another case class to hold the initial and final result, then you can use first, second, third instead of _1, _2, _3:

```<code>case class Test1(val first: Int, val second: Int, val third: Int)

list.foldLeft(Test1(0,0,0))((acc, t) => Test1(acc.first + t.first, acc.second + t.second, acc.third + t.third))
// res0: Test1 = Test1(8,30,6)
</code>```

Body:
I have an class

class Test(val first: Int, val second: Int, val third: Int)

Class Test may have other attributes than first, second, and third.

And I have a list:

val list: List[Test] = List(new Test(0,1,2), new Test(1,14,2), new Test(7,15,2))

How would I use foldLeft here to add together all first`s, second's, third's together to end up with variables:

allFirsts = 8

allSeconds = 30

allThirds = 6

I already have something like this worked out:

val (totalFirsts, totalSeconds, totalThirds) = list.foldLeft(0, 0, 0){ (sum, l) => (sum._1 + l.first , sum._2 + l.second, sum._3 + l.third) }

It seems to work fine, but I don't like the readability of _1, _2, and _3.  Maybe I can use case here to decompose values but I am just not sure how to make it all work together.

Body:
You can define another case class to hold the initial and final result, then you can use first, second, third instead of _1, _2, _3:

case class Test1(val first: Int, val second: Int, val third: Int)

list.foldLeft(Test1(0,0,0))((acc, t) => Test1(acc.first + t.first, acc.second + t.second, acc.third + t.third))
// res0: Test1 = Test1(8,30,6)


问:
Spring cloud config properties not honouring config properties
I wish to use consul strictly as a config source.
I am using spring-cloud-consul-config to get my config.
I am using git2consul to load files into consul and read them.
As per the spring cloud documentation I have added the following to my build.gradle

```<code>compile ("org.springframework.cloud:spring-cloud-starter-consul-config")
</code>```

and have the following in my application.properties

```<code>spring.application.name=test-service
spring.cloud.consul.config.enabled=true
spring.cloud.consul.enabled=true
spring.cloud.consul.config.format=FILES
</code>```

The problem I am facing is that the expected properties are not being loaded into the ConfigurationProperties beans. On further debugging in the ConsulPropertySourceLocator::locate(Environment environment) method, I see that the this.properties object is still loaded with KEY_VALUE enum.

This led me to ConsulConfigBootstrapConfiguration class, where the ConsulConfigProperties bean is being instantiated using a constructor.

Is this the problem or do I have something wrong in my setup.
If someone has a working setup of git2consul and spring cloud config, please can you point me to it for reference.

答:
These values that you have in application.properties

```<code>spring.application.name=test-service
spring.cloud.consul.config.enabled=true
spring.cloud.consul.enabled=true
spring.cloud.consul.config.format=FILES
</code>```

need to be in bootstrap.properties.

Body:
I wish to use consul strictly as a config source.
I am using spring-cloud-consul-config to get my config.
I am using git2consul to load files into consul and read them.
As per the spring cloud documentation I have added the following to my build.gradle

compile ("org.springframework.cloud:spring-cloud-starter-consul-config")

and have the following in my application.properties

spring.application.name=test-service
spring.cloud.consul.config.enabled=true
spring.cloud.consul.enabled=true
spring.cloud.consul.config.format=FILES

The problem I am facing is that the expected properties are not being loaded into the ConfigurationProperties beans. On further debugging in the ConsulPropertySourceLocator::locate(Environment environment) method, I see that the this.properties object is still loaded with KEY_VALUE enum.

This led me to ConsulConfigBootstrapConfiguration class, where the ConsulConfigProperties bean is being instantiated using a constructor.

Is this the problem or do I have something wrong in my setup.
If someone has a working setup of git2consul and spring cloud config, please can you point me to it for reference.

Body:
These values that you have in application.properties

spring.application.name=test-service
spring.cloud.consul.config.enabled=true
spring.cloud.consul.enabled=true
spring.cloud.consul.config.format=FILES

need to be in bootstrap.properties.


问:
Does the founder org of a hyperledger fabric private network have all the orderers?
If BigBank#1 starts a Hyperledger Fabric private network with a couple of peers, an orderer and fabric CA and down the line offers a service to BigBank#2 and invites it to access its network, does that mean that only the founder (i.e. BigBank#1) can have an orderer on its network?

Thanks in advance for any enlightenment!

答:
No:

SmallBank can also create an orderer of its own and have the peers of BigBank join it.

If BigBank uses a Kafka orderer, it can have SmallBank use its own Ordering service nodes to connect to BigBank's existing Kafka service, or they can grow the kafka cluster and connect between the kafka nodes.


问:
Why is the size of this struct 32?
This is the struct.

```<code>//Structure pour communiquer les paramètres de traitement à travers le MMF
struct params_traitement_mmf
{
    int brilliance;
    double contraste;
    char convolution[9];
};
</code>```

This is my code to display the size of this struct :

```<code>    char valeur[10];
    sprintf(valeur, "%d", sizeof(params_traitement_mmf));
    MessageBoxA(NULL, valeur, "rien", MB_OK);
</code>```

The MessageBox displays 32.
Thank you!

答:
My Mac lists this as only 24 bytes.

```<code>int - 4 bytes
double - 8 bytes
char[9] - 12 bytes (padding)
</code>```

Windows must be adding extra padding for proper alignment (also depends on your processor).

Title: Why is the size of this struct 32?

Body:
This is the struct.

//Structure pour communiquer les paramètres de traitement à travers le MMF
struct params_traitement_mmf
{
    int brilliance;
    double contraste;
    char convolution[9];
};

This is my code to display the size of this struct :

    char valeur[10];
    sprintf(valeur, "%d", sizeof(params_traitement_mmf));
    MessageBoxA(NULL, valeur, "rien", MB_OK);

The MessageBox displays 32.
Thank you!

Body:
My Mac lists this as only 24 bytes.

int - 4 bytes
double - 8 bytes
char[9] - 12 bytes (padding)

Windows must be adding extra padding for proper alignment (also depends on your processor).


问:
How to rewrite SQL joins into window functions?
Database is HP Vertica 7 or PostgreSQL 9.

```<code>create table test (
id int,
card_id int,
tran_dt date,
amount int
);

insert into test values (1, 1, '2017-07-06', 10);
insert into test values (2, 1, '2017-06-01', 20);
insert into test values (3, 1, '2017-05-01', 30);
insert into test values (4, 1, '2017-04-01', 40);
insert into test values (5, 2, '2017-07-04', 10);
</code>```

Of the payment cards used in the last 1 day, what is the maximum amount charged on that card in the last 90 days.

```<code>select t.card_id, max(t2.amount) max
from test t
join test t2 on t2.card_id=t.card_id and t2.tran_dt>='2017-04-06'
where t.tran_dt>='2017-07-06'
group by t.card_id
order by t.card_id;
</code>```

Results are correct

```<code>card_id    max
-------    ---
1          30
</code>```

I want to rewrite the query into sql window functions.

```<code>select card_id, max(amount) over(partition by card_id order by tran_dt range between '60 days' preceding and current row) max
from test
where card_id in (select card_id from test where tran_dt>='2017-07-06')
order by card_id;
</code>```

But result set does not match, how can this be done?

Test data here:
http://sqlfiddle.com/#!17/db317/1

答:
As far as I know, PostgreSQL Window function doesn't support bounded range preceding thus range between '90 days' preceding won't work.  It does support bounded rows preceding such as rows between 90 preceding, but then you would need to assemble a time-series query similar to the following for the Window function to operate on the time-based rows:

```<code>SELECT c.card_id, t.amount, g.d as d_series
FROM generate_series(
  '2017-04-06'::timestamp, '2017-07-06'::timestamp, '1 day'::interval
) g(d)
CROSS JOIN ( SELECT distinct card_id from test ) c
LEFT JOIN test t ON t.card_id = c.card_id and t.tran_dt = g.d
ORDER BY c.card_id, d_series
</code>```

For what you need (based on your question description), I would stick to using group by.

Body:
Database is HP Vertica 7 or PostgreSQL 9.

create table test (
id int,
card_id int,
tran_dt date,
amount int
);

insert into test values (1, 1, '2017-07-06', 10);
insert into test values (2, 1, '2017-06-01', 20);
insert into test values (3, 1, '2017-05-01', 30);
insert into test values (4, 1, '2017-04-01', 40);
insert into test values (5, 2, '2017-07-04', 10);

Of the payment cards used in the last 1 day, what is the maximum amount charged on that card in the last 90 days.

select t.card_id, max(t2.amount) max
from test t
join test t2 on t2.card_id=t.card_id and t2.tran_dt>='2017-04-06'
where t.tran_dt>='2017-07-06'
group by t.card_id
order by t.card_id;

Results are correct

card_id    max
-------    ---
1          30

I want to rewrite the query into sql window functions.

select card_id, max(amount) over(partition by card_id order by tran_dt range between '60 days' preceding and current row) max
from test
where card_id in (select card_id from test where tran_dt>='2017-07-06')
order by card_id;

But result set does not match, how can this be done?

Test data here:
http://sqlfiddle.com/#!17/db317/1

Body:
As far as I know, PostgreSQL Window function doesn't support bounded range preceding thus range between '90 days' preceding won't work.  It does support bounded rows preceding such as rows between 90 preceding, but then you would need to assemble a time-series query similar to the following for the Window function to operate on the time-based rows:

SELECT c.card_id, t.amount, g.d as d_series
FROM generate_series(
  '2017-04-06'::timestamp, '2017-07-06'::timestamp, '1 day'::interval
) g(d)
CROSS JOIN ( SELECT distinct card_id from test ) c
LEFT JOIN test t ON t.card_id = c.card_id and t.tran_dt = g.d
ORDER BY c.card_id, d_series

For what you need (based on your question description), I would stick to using group by.


问:
RxJava. Initial onNext when subscription starts?
I'm trying to implement a class that emits changes using an Observable.
When a subscription is done to this observable I want to send an starting/initialization event. Then I want to send the usual events.

For example. Lets say I have two different subscribers A and B. A and B starts subscribing at different times. If MyClass.getChanges() emits event no. 1,2,3,4 and 5.

If A starts it subscription between event 1,2 then it should receive the following events:
InitialEvent, 2, 3, 4, 5.

If B starts it subscription between event 4 and 5, then B should receive the following events:
InitialEvent, 5.

How to do this using RxJava?

Thanks!

Edit 1

I think I need to explain that the "InitialEvent" is different each time it's emitted. It's calculated by MyClass each time a new subscriber starts to subscribe from getChanged().

My scenario is that MyClass contains a list. The "initialEvent" contains the list at the moment when the subscription is done. Then each change to this list is emitted from getChanges().

答:
Sorry to post this 2 years later, but I had the same need and found this question unanswered.

What I did is the following:

```<code>public Observable<Event> observe() {
    return Observable.defer(() ->
        subject.startWith(createInitialEvent())
    );
}
</code>```

The idea is the following:

defer() executes the passed-in lambda expression when an observer subscribes to the Observable returned by the method observe(). So basically, it executes subject.startWith(...), which returns an Observable that is the actual source of event for the subscriber.

subject.startWith(...) emits an initial event (specified by startWith(...)) followed by those emitted by the subject.

So, if I come back to the original post:
if an observer starts it subscription between event 1,2 then it should receive the following events: InitialEvent, 2, 3, 4, 5.

Body:
Sorry to post this 2 years later, but I had the same need and found this question unanswered.

What I did is the following:

public Observable<Event> observe() {
    return Observable.defer(() ->
        subject.startWith(createInitialEvent())
    );
}

The idea is the following:

defer() executes the passed-in lambda expression when an observer subscribes to the Observable returned by the method observe(). So basically, it executes subject.startWith(...), which returns an Observable that is the actual source of event for the subscriber.

subject.startWith(...) emits an initial event (specified by startWith(...)) followed by those emitted by the subject.

So, if I come back to the original post:
if an observer starts it subscription between event 1,2 then it should receive the following events: InitialEvent, 2, 3, 4, 5.


问:
How to do aggregate query with accumulators using mongodb driver in java
I'm quite new in MongoDB and its interaction with java.
I'm using this driver

```<code><dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
</code>```

and I want to perform this aggregation query:

```<code>db.getCollection('COLLECTION').aggregate(
[
  {"$match":{"val.elem.0001":{"$exists":true}}},
  {"$project":{"FIELD_PATH":"$val.elem.0001"}},
  {$group:{_id:{"FIELD":{"$literal":"0001"}},
  "PATH":{"$addToSet":"$FIELD_PATH"}}}
]
);
</code>```

The java code I've written is the following (however I'm not sure if I use correctly the addToSet method):

```<code>AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
new Document("$match", new Document("val.elem.0001",new Document("$exists",true))),
new Document("$project", new Document("FIELD_PATH","$val.elem.0001")),
new Document("$group", new Document("_id",new Document("FIELD", new Document("$literal", "0001"))
    .append("PATH",  Accumulators.addToSet("$PATH", "$FIELD_PATH"))))));
</code>```

It is correct? Because I can't print the result on screen if I add the "append" part. The error that returns is
Can't find a codec for class com.mongodb.client.model.BsonField

So, to resume and make more readable and comprehensive what I've asked:

Is the java representation of the query correct?

If so, why I'm not able to print or access the result of the query?

Thanks in advance, if you need more informations, I'm ready to provide them.

答:
Yous usage of api is incorrect.

Change your aggregation to below ( stick with Document for expressions)

```<code>AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
       new Document("$match", new Document("val.elem.0001",new Document("$exists",true))),
       new Document("$project", new Document("FIELD_PATH","$val.elem.0001")),
       new Document("$group", new Document("_id",new Document("FIELD", new Document("$literal", "0001"))).append("PATH", new Document("$addToSet", "$FIELD_PATH")))));
</code>```

BsonField is a helper class primarily built to provide data holder for Accumulators which return key and Bson value pair. So it is not meant to be used as value type. When use with helper methods, it is converted into Document and serialized using document codec.

You can rework your aggregation to use helper methods (Filters, Projections Accumulators & Aggregates)

```<code>AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
       Aggregates.match(Filters.exists("val.elem.0001")),
       Aggregates.project(Projections.computed("FIELD_PATH","$val.elem.0001")),
       Aggregates.group( new Document("FIELD", new Document("$literal", "0001")), Accumulators.addToSet("PATH", "$FIELD_PATH"))));
</code>```

You can further reduce the aggregation by using static imports.

```<code>import static com.mongodb.client.model.Accumulators.addToSet;
import static com.mongodb.client.model.Aggregates.group;
import static com.mongodb.client.model.Aggregates.match;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.computed;
import static java.util.Arrays.*;

AggregateIterable<Document> output = collection.aggregate(asList(
       match(Filters.exists("val.elem.0001")),
       project(computed("FIELD_PATH","$val.elem.0001")),
       group( new Document("FIELD", new Document("$literal", "0001")), addToSet("PATH", "$FIELD_PATH"))));
</code>```

For more information

http://mongodb.github.io/mongo-java-driver/3.4/driver/tutorials/aggregation/

Body:
I'm quite new in MongoDB and its interaction with java.
I'm using this driver

<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>

and I want to perform this aggregation query:

db.getCollection('COLLECTION').aggregate(
[
  {"$match":{"val.elem.0001":{"$exists":true}}},
  {"$project":{"FIELD_PATH":"$val.elem.0001"}},
  {$group:{_id:{"FIELD":{"$literal":"0001"}},
  "PATH":{"$addToSet":"$FIELD_PATH"}}}
]
);

The java code I've written is the following (however I'm not sure if I use correctly the addToSet method):

AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
new Document("$match", new Document("val.elem.0001",new Document("$exists",true))),
new Document("$project", new Document("FIELD_PATH","$val.elem.0001")),
new Document("$group", new Document("_id",new Document("FIELD", new Document("$literal", "0001"))
    .append("PATH",  Accumulators.addToSet("$PATH", "$FIELD_PATH"))))));

It is correct? Because I can't print the result on screen if I add the "append" part. The error that returns is
Can't find a codec for class com.mongodb.client.model.BsonField

So, to resume and make more readable and comprehensive what I've asked:

Is the java representation of the query correct?

If so, why I'm not able to print or access the result of the query?

Thanks in advance, if you need more informations, I'm ready to provide them.

Body:
Yous usage of api is incorrect.

Change your aggregation to below ( stick with Document for expressions)

AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
       new Document("$match", new Document("val.elem.0001",new Document("$exists",true))),
       new Document("$project", new Document("FIELD_PATH","$val.elem.0001")),
       new Document("$group", new Document("_id",new Document("FIELD", new Document("$literal", "0001"))).append("PATH", new Document("$addToSet", "$FIELD_PATH")))));

BsonField is a helper class primarily built to provide data holder for Accumulators which return key and Bson value pair. So it is not meant to be used as value type. When use with helper methods, it is converted into Document and serialized using document codec.

You can rework your aggregation to use helper methods (Filters, Projections Accumulators & Aggregates)

AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
       Aggregates.match(Filters.exists("val.elem.0001")),
       Aggregates.project(Projections.computed("FIELD_PATH","$val.elem.0001")),
       Aggregates.group( new Document("FIELD", new Document("$literal", "0001")), Accumulators.addToSet("PATH", "$FIELD_PATH"))));

You can further reduce the aggregation by using static imports.

import static com.mongodb.client.model.Accumulators.addToSet;
import static com.mongodb.client.model.Aggregates.group;
import static com.mongodb.client.model.Aggregates.match;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.computed;
import static java.util.Arrays.*;

AggregateIterable<Document> output = collection.aggregate(asList(
       match(Filters.exists("val.elem.0001")),
       project(computed("FIELD_PATH","$val.elem.0001")),
       group( new Document("FIELD", new Document("$literal", "0001")), addToSet("PATH", "$FIELD_PATH"))));

For more information

http://mongodb.github.io/mongo-java-driver/3.4/driver/tutorials/aggregation/


问:
How can i add a static library of type .a to a visual studio project?
I am trying to use MathGL in my project. When i go through the package contents i can only find .a static library files, how can i use those to include that library in my Visual Studio project?

I have tried to include all the .a files by going to Project Properties->Configuration Properties->Linker->Input

and link all the .a files using "additional dependencies". But then i still get a ton of errors when i include the mgl.h file.

I guess my question is: is the way to use a library in your program is to include the needed .a files? and if yes, what is the correct way to do it?

答:
According with the documentation of MathGL, the libraries are into the directory mathgl/lib, and they are dinamic link libraries(dlls):

The same documentation says:

Use a precompiled binary. There are binaries for MinGW (platform Win32). For
  a precompiled variant one needs only to unpack the archive to the location of the
  Chapter 1: Overview 3
  compiler (i.e. mathgl/lib in mingw/lib, mathgl/include in mingw/include and so on)
  or in arbitrary other folder and setup paths in compiler. By default, precompiled
  versions include the support of GSL (www.gsl.org) and PNG. So, one needs to have
  these libraries installed on system (it can be found, for example, at http://gnuwin32.
  sourceforge.net/packages.html).

So, you need to link the Dll instead of a static library, check this asnwer to see how to link a dll: Linking dll in Visual Studio


问:
Fortran error 5082
I'm very new at Fortran. I'm trying to compile this Fortran, I think 90??? Code. I'm using visual studio with the intel compiler. </p>

<p>The following code is giving me an error 5082. I have absolutely no idea why. Like literally no clue. Please, please help. </p>

```<code> integer function Dub(n)
 integer n
 Dub = 2*n
 return
 end

program Subroutines

implicit none

! Variables
integer n
n = 5

! Body of Subroutines
write(*,*) n
Dub(n)

write(*,*) 'Press Enter to Exit'
read(*,*)
stop
end program Subroutines
</code>```

答:
In Fortran a call to a function, or a subroutine, must be part of a statement (or an initialization expression, but that's more advanced). name(argument[s]) by itself is not a statement, unlike some other languages such as C, C++ and Java. A function call must be in an expression, and a subroutine call must use the call keyword. See https://en.wikibooks.org/wiki/Fortran/Fortran_procedures_and_functions for examples.

Changing that line of your program to n = Dub(n) would make it legal, but rather useless. That function does nothing except return a value, and your main program does nothing useful with the value returned. Generally you call a function because you want either a side effect from executing the function, or to use the returned value, or both.

Title: Fortran error 5082

Body:
I'm very new at Fortran. I'm trying to compile this Fortran, I think 90??? Code. I'm using visual studio with the intel compiler.

The following code is giving me an error 5082. I have absolutely no idea why. Like literally no clue. Please, please help.

 integer function Dub(n)
 integer n
 Dub = 2*n
 return
 end

program Subroutines

implicit none

! Variables
integer n
n = 5

! Body of Subroutines
write(*,*) n
Dub(n)

write(*,*) 'Press Enter to Exit'
read(*,*)
stop
end program Subroutines


问:
How to debug npm? Why it stopped working after reinstalling all dependencies?
I have been running a project with npm for about 4 months without big issues.

Until today, when I had the terrible idea to try to update the react-redux lib to the last version.

Turned out that it didn't work and I just discarded the changes I've made to the package.json and installed everything again:

git checkout package.json
rm -rf node_modules
npm install

But now, when I run the server I get this error:

Error: Cannot find module 'bootstrap' from '/Users/rodrigora/Projects/PROJ/node_modules/react-bootstrap-multiselect/dist'

This doesn't make sense, because I discarded all changes.

Why it stopped to work?
What can I do to try to identify what is causing this?

Thanks

Edit:

npm version: 5.1.0

Solution

After about 2 hours I did this:

```<code>rm -rf node_modules/react-bootstrap-multiselect
npm install bootstrap
npm install react-bootstrap-multiselect
</code>```

and it worked! Yah, NPM is a great dependency manager!

Thank you all!

答: It sounds like you just need to import the bootstrap library, try looking through http://getbootstrap.com/ for what you need.</p>

Body:
I have been running a project with npm for about 4 months without big issues.

Until today, when I had the terrible idea to try to update the react-redux lib to the last version.

Turned out that it didn't work and I just discarded the changes I've made to the package.json and installed everything again:

git checkout package.json
rm -rf node_modules
npm install

But now, when I run the server I get this error:

Error: Cannot find module 'bootstrap' from '/Users/rodrigora/Projects/PROJ/node_modules/react-bootstrap-multiselect/dist'

This doesn't make sense, because I discarded all changes.

Why it stopped to work?
What can I do to try to identify what is causing this?

Thanks

Edit:

npm version: 5.1.0

Solution

After about 2 hours I did this:

rm -rf node_modules/react-bootstrap-multiselect
npm install bootstrap
npm install react-bootstrap-multiselect

and it worked! Yah, NPM is a great dependency manager!

Thank you all!


问:
Converting Java LinkedHashMap to C++ std::map
I'm trying to port a program from Java to C++ and I can't seem to figure out how to go about converting a LinkedHashMap into a std::map. I can't change the LinkedHashMap but I'm not restricted to std::map. I need it to produce the same key/value pair but ordering/hashing/whatever else doesn't really matter.

Java code to be converted:

```<code>List<Face> faces = new ArrayList<Face>(modelFull.faces.length);
Map<Point3D, Integer> map = new LinkedHashMap<Point3D, Integer>();
for (int i = 0; i < modelFull.faces.length; i++) {
    Face f = new Face(modelFull.faces[i]);
    faces.add(f);
    for (int k = 0; k < 3; k++) {
        Point3D p = f.pts[k];
        Integer v = map.get(p);
        if (v == null) {
            v = 0;
        }
        map.put(p, v + 1);
    }
}
</code>```

My attempt:

```<code>std::map<RVPoint3D, int> pointMap;
auto modelFaces = modelFull.getFaces();
for (const auto &face : modelFaces)
{
    Face newFace = Face(face);
    for (int k = 0; k < 3; ++k)
    {
        RVPoint3D pt = newFace.getPts()[k];
        ++pointMap[pt];
    }
    faces.push_back(newFace);
}
</code>```

The Java implementation creates a map of size 7523 and the C++ one is 7967. There are 45234 elements inspected total for both so it seems to be iterating correctly through the potential keys.

I'm not sure where to go from here. I've tried overloading operators, custom comparators, custom hash functions, etc. and I must be missing something.

答:
In the java version for new map items you set v to 0 then add 1 to it when you put it in the map. \in the C++ version you put it in as just 0.

Java

```<code>Integer v = map.get(p);
if (v == null) {
    v = 0;
}
map.put(p, v + 1); // new map entries go in as 1
</code>```

C++

```<code>if (pointMap.count(pt))
{
    pointMap[pt] += 1;
} else {
    pointMap[pt] = 0; // new map entries go in as 0
}
</code>```

Also can you set a null Iteger to 0 in Java? Don't you need to do something like:

```<code>v = new Integer(0); // ?
</code>```

Side Note:

The C++ code can be rewritten as:

```<code>for (const auto &face : modelFaces)
{
    Face newFace(face); // Value, no need for Java-like syntax
    for (int k = 0; k < 3; ++k)
    {
        RVPoint3D pt = newFace.getPts()[k];
        ++pointMap[pt]; // auto sets to 1 on new entry
    }
    faces.push_back(newFace);
}
</code>```

This works because if a key does not exist in a std::map one is created automatically (with the corresponding value 0) when you access it using pointMap[pt]. So you can just increment and new values will start at 1 just as in the Java code.

Body:
I'm trying to port a program from Java to C++ and I can't seem to figure out how to go about converting a LinkedHashMap into a std::map. I can't change the LinkedHashMap but I'm not restricted to std::map. I need it to produce the same key/value pair but ordering/hashing/whatever else doesn't really matter.

Java code to be converted:

List<Face> faces = new ArrayList<Face>(modelFull.faces.length);
Map<Point3D, Integer> map = new LinkedHashMap<Point3D, Integer>();
for (int i = 0; i < modelFull.faces.length; i++) {
    Face f = new Face(modelFull.faces[i]);
    faces.add(f);
    for (int k = 0; k < 3; k++) {
        Point3D p = f.pts[k];
        Integer v = map.get(p);
        if (v == null) {
            v = 0;
        }
        map.put(p, v + 1);
    }
}

My attempt:

std::map<RVPoint3D, int> pointMap;
auto modelFaces = modelFull.getFaces();
for (const auto &face : modelFaces)
{
    Face newFace = Face(face);
    for (int k = 0; k < 3; ++k)
    {
        RVPoint3D pt = newFace.getPts()[k];
        ++pointMap[pt];
    }
    faces.push_back(newFace);
}

The Java implementation creates a map of size 7523 and the C++ one is 7967. There are 45234 elements inspected total for both so it seems to be iterating correctly through the potential keys.

I'm not sure where to go from here. I've tried overloading operators, custom comparators, custom hash functions, etc. and I must be missing something.

Body:
In the java version for new map items you set v to 0 then add 1 to it when you put it in the map. \in the C++ version you put it in as just 0.

Java

Integer v = map.get(p);
if (v == null) {
    v = 0;
}
map.put(p, v + 1); // new map entries go in as 1

C++

if (pointMap.count(pt))
{
    pointMap[pt] += 1;
} else {
    pointMap[pt] = 0; // new map entries go in as 0
}

Also can you set a null Iteger to 0 in Java? Don't you need to do something like:

v = new Integer(0); // ?

Side Note:

The C++ code can be rewritten as:

for (const auto &face : modelFaces)
{
    Face newFace(face); // Value, no need for Java-like syntax
    for (int k = 0; k < 3; ++k)
    {
        RVPoint3D pt = newFace.getPts()[k];
        ++pointMap[pt]; // auto sets to 1 on new entry
    }
    faces.push_back(newFace);
}

This works because if a key does not exist in a std::map one is created automatically (with the corresponding value 0) when you access it using pointMap[pt]. So you can just increment and new values will start at 1 just as in the Java code.


问:
Enum Class in ES6 - Sintax Error
I was looking for a good solution to use Enumeration in ES6. I've found the following JS library below. But I'm getting some error related to the ES6 syntax for this code.

Source Code:
https://gist.github.com/xmlking/e86e4f15ec32b12c4689

"SyntaxError: Unexpected token (2:8)"

export class EnumSymbol {
    sym **=** Symbol.for(name);
    value: number;
    description: string;
```

Does anybody have a clue about is code?

答:
As commented by Bergi. This is a Typescript code. Description in the source code seems to be incorrect.

Thanks for the heads up @Bergi!

Title: Enum Class in ES6 - Sintax Error

Body:
I was looking for a good solution to use Enumeration in ES6. I've found the following JS library below. But I'm getting some error related to the ES6 syntax for this code.

Source Code:
https://gist.github.com/xmlking/e86e4f15ec32b12c4689

"SyntaxError: Unexpected token (2:8)"

export class EnumSymbol {
    sym **=** Symbol.for(name);
    value: number;
    description: string;

Does anybody have a clue about is code?


问:
MySql count(*) super slow with concurrent queries
I have a script that tries to read all the rows from a table like this:

```<code>select count(*) from table where col1 = 'Y' or col1 is null;
</code>```

col1 and col2 are not indexed and this query usually takes ~20 seconds but if someone is already running this query, it takes ages and gets blocked.

We just have around 100k rows in the table and I tried it without the where clause and it causes the same issue.

The table uses InnoDB so, it doesn't store the exact count but I am curious if there is any concurrency parameter I should look into. I am not sure if absence of indexes on the table causes the issue but it doesn't make sense to me.

Thanks!

答: If they are not indexed, then it is required to read the entire disk files of your tables to find your data. A single hard disk cannot perform very well concurrent read intensive operations. You have to index.</p>

Body:
I have a script that tries to read all the rows from a table like this:

select count(*) from table where col1 = 'Y' or col1 is null;

col1 and col2 are not indexed and this query usually takes ~20 seconds but if someone is already running this query, it takes ages and gets blocked.

We just have around 100k rows in the table and I tried it without the where clause and it causes the same issue.

The table uses InnoDB so, it doesn't store the exact count but I am curious if there is any concurrency parameter I should look into. I am not sure if absence of indexes on the table causes the issue but it doesn't make sense to me.

Thanks!


问:
How to run Express and Mongo using docker-compose
How to run Express and MongoDB using docker-compose?

My docker-compose.yml looks like this:

```<code>version: '3'

services:
    express:
         image: node:7.7.2-alpine
         container_name: express-container
         ports:
            - 3000:3000
         volumes:
            - .:/application/
            - /application/node_modules
         links:
            - mongodb
         command: npm start

    mongodb:
        image: mongo:3.4.4
        container_name: mongo-container
        ports:
            - 27017:27017
</code>```

After run docker-compose up mongo looks work fine:

```<code>mongo-container | 2017-07-06T22:17:53.939+0000 I NETWORK  [thread1] waiting for connections on port 27017
</code>```

But express give me this:

```<code>express-container | npm info it worked if it ends with ok
express-container | npm info using npm@4.1.2
express-container | npm info using node@v7.7.2
express-container | npm ERR! Linux 4.9.27-moby
express-container | npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
express-container | npm ERR! node v7.7.2
express-container | npm ERR! npm  v4.1.2
express-container | npm ERR! path /package.json
express-container | npm ERR! code ENOENT
express-container | npm ERR! errno -2
express-container | npm ERR! syscall open
express-container |
express-container | npm ERR! enoent ENOENT: no such file or directory, open '/package.json'
express-container | npm ERR! enoent ENOENT: no such file or directory, open '/package.json'
express-container | npm ERR! enoent This is most likely not a problem with npm itself
express-container | npm ERR! enoent and is related to npm not being able to find a file.
express-container | npm ERR! enoent
express-container |
express-container | npm ERR! Please include the following file with any support request:
express-container | npm ERR!     /npm-debug.log
express-container exited with code 254
</code>```

Can someone tell me what's wrong with my compose file?

答:
You lack to specify the WORKDIR. As this in Dockerfile:

```<code>WORKDIR /application
</code>```

Or just in docker-compose.yml in the corresponding service:

```<code>working_dir: /application
</code>```

npm will look there for the package.json file.

Body:
How to run Express and MongoDB using docker-compose?

My docker-compose.yml looks like this:

version: '3'

services:
    express:
         image: node:7.7.2-alpine
         container_name: express-container
         ports:
            - 3000:3000
         volumes:
            - .:/application/
            - /application/node_modules
         links:
            - mongodb
         command: npm start

    mongodb:
        image: mongo:3.4.4
        container_name: mongo-container
        ports:
            - 27017:27017

After run docker-compose up mongo looks work fine:

mongo-container | 2017-07-06T22:17:53.939+0000 I NETWORK  [thread1] waiting for connections on port 27017

But express give me this:

express-container | npm info it worked if it ends with ok
express-container | npm info using npm@4.1.2
express-container | npm info using node@v7.7.2
express-container | npm ERR! Linux 4.9.27-moby
express-container | npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
express-container | npm ERR! node v7.7.2
express-container | npm ERR! npm  v4.1.2
express-container | npm ERR! path /package.json
express-container | npm ERR! code ENOENT
express-container | npm ERR! errno -2
express-container | npm ERR! syscall open
express-container |
express-container | npm ERR! enoent ENOENT: no such file or directory, open '/package.json'
express-container | npm ERR! enoent ENOENT: no such file or directory, open '/package.json'
express-container | npm ERR! enoent This is most likely not a problem with npm itself
express-container | npm ERR! enoent and is related to npm not being able to find a file.
express-container | npm ERR! enoent
express-container |
express-container | npm ERR! Please include the following file with any support request:
express-container | npm ERR!     /npm-debug.log
express-container exited with code 254

Can someone tell me what's wrong with my compose file?

Body:
You lack to specify the WORKDIR. As this in Dockerfile:

WORKDIR /application

Or just in docker-compose.yml in the corresponding service:

working_dir: /application

npm will look there for the package.json file.


问:
Symfony One-To-Many unidirectional relation without JOIN table
I have the following tables:

```<code>strings
------
"id" int not null primary key

string_texts
------
"id"          int not null primary key
"string_id"   int not null fk(strings.id)
"language_id" int not null fk(languages.id)
"text"        text

"countries"
------
"id"      int not null primary key,
"name_id" int not null fk(strings.id)
</code>```

All localizable text stored in a single table, and every other table connected to that table.

What I dont know is how to write the Country model? This is how I got so far.

```<code>namespace LoginHood\HoodBundle\Entity\Geo;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

class Country
{
    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     */
    protected $id;

    /**
     * @var Collection
     *
     * @ORM\OneToMany(targetEntity="StringText", mappedBy="")
     */
    protected $names;

    /*
    ...
    */

    public function __construct()
    {
        $this->names = new ArrayCollection();
    }
}
</code>```

Because of the structure you can't get the Country or any Entity from the StringText entity. But I don't want to make a join table, because its kind of an overkill, and totally meaningless.

答:
You are reinventing the wheel, you have to use the DoctrineExtensions / Translatable behavior that will do the whole job for you:

Deal with model modifications, almost like what you are doing

Get directly the string in the correct language, when getting it

...

Body:
I have the following tables:

strings
------
"id" int not null primary key

string_texts
------
"id"          int not null primary key
"string_id"   int not null fk(strings.id)
"language_id" int not null fk(languages.id)
"text"        text

"countries"
------
"id"      int not null primary key,
"name_id" int not null fk(strings.id)

All localizable text stored in a single table, and every other table connected to that table.

What I dont know is how to write the Country model? This is how I got so far.

namespace LoginHood\HoodBundle\Entity\Geo;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

class Country
{
    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     */
    protected $id;

    /**
     * @var Collection
     *
     * @ORM\OneToMany(targetEntity="StringText", mappedBy="")
     */
    protected $names;

    /*
    ...
    */

    public function __construct()
    {
        $this->names = new ArrayCollection();
    }
}

Because of the structure you can't get the Country or any Entity from the StringText entity. But I don't want to make a join table, because its kind of an overkill, and totally meaningless.


问:
Get list of user email addresses with AngularFire
My web application uses Firebase JS + AngularFire to display a report of users in the application (visible only to admins). How can I retrieve a user's email address using AngularFire?

Looking at the AngularFire API Reference, I don't see an available method for doing this in the $firebaseAuth section: https://github.com/firebase/angularfire/blob/master/docs/reference.md

答:
You can't easily access that unless you go to the firebase console and do a manual check.
In firebase it is advised that you create another node called Users in your database to be used in storing Users info. This will help you to easily get the info when you need them.

Check my sample code on how to create a new user.

```<code>  signUp() {

    if (this.signupForm.valid) {
     //grab login form values
          let email = this.signupForm.get('email').value;
          let password = this.signupForm.get('password').value;
          let confirmpassword = this.signupForm.get('confirmpassword').value;
          let petname = this.signupForm.get('petname').value;
          let full_name = this.signupForm.get('full_name').value;
          let address = this.signupForm.get('address').value;
          let phone = this.signupForm.get('phone').value;
          let default_role = this.signupForm.get('default_role').value;

          //signup new user
          this.security.signup(email, password).then((response) => {

            //userid
            let userid = response.auth.uid;

            //create a new user using form values
            let newUser: User = {
              full_name: full_name,
              password: password,
              petname: petname,
              email: email,
              phone: phone,
              default_role: default_role,
              usercode: newusercode
            };

            //add new user to database table section
            this.af.database.object("/Users/" + userid).set(newUser).then(() => {

              //prepare userinfo for cache
              let userInfo = {
                uid: userid,
                petname: petname,
                default_role: default_role
              }
});
}
</code>```

Body:
You can't easily access that unless you go to the firebase console and do a manual check.
In firebase it is advised that you create another node called Users in your database to be used in storing Users info. This will help you to easily get the info when you need them.

Check my sample code on how to create a new user.

  signUp() {

    if (this.signupForm.valid) {
     //grab login form values
          let email = this.signupForm.get('email').value;
          let password = this.signupForm.get('password').value;
          let confirmpassword = this.signupForm.get('confirmpassword').value;
          let petname = this.signupForm.get('petname').value;
          let full_name = this.signupForm.get('full_name').value;
          let address = this.signupForm.get('address').value;
          let phone = this.signupForm.get('phone').value;
          let default_role = this.signupForm.get('default_role').value;

          //signup new user
          this.security.signup(email, password).then((response) => {

            //userid
            let userid = response.auth.uid;

            //create a new user using form values
            let newUser: User = {
              full_name: full_name,
              password: password,
              petname: petname,
              email: email,
              phone: phone,
              default_role: default_role,
              usercode: newusercode
            };

            //add new user to database table section
            this.af.database.object("/Users/" + userid).set(newUser).then(() => {

              //prepare userinfo for cache
              let userInfo = {
                uid: userid,
                petname: petname,
                default_role: default_role
              }
});
}


问:
Under what circumstances is an SqlConnection automatically enlisted in an ambient TransactionScope Transaction?
What does it mean for an SqlConnection to be "enlisted" in a transaction?  Does it simply mean that commands I execute on the connection will participate in the transaction?

If so, under what circumstances is an SqlConnection automatically enlisted in an ambient TransactionScope Transaction?

See questions in code comments.  My guess to each question's answer follows each question in parenthesis.

Scenario 1: Opening connections INSIDE a transaction scope

```<code>using (TransactionScope scope = new TransactionScope())
using (SqlConnection conn = ConnectToDB())
{
    // Q1: Is connection automatically enlisted in transaction? (Yes?)
    //
    // Q2: If I open (and run commands on) a second connection now,
    // with an identical connection string,
    // what, if any, is the relationship of this second connection to the first?
    //
    // Q3: Will this second connection's automatic enlistment
    // in the current transaction scope cause the transaction to be
    // escalated to a distributed transaction? (Yes?)
}
</code>```

Scenario 2: Using connections INSIDE a transaction scope that were opened OUTSIDE of it

```<code>//Assume no ambient transaction active now
SqlConnection new_or_existing_connection = ConnectToDB(); //or passed in as method parameter
using (TransactionScope scope = new TransactionScope())
{
    // Connection was opened before transaction scope was created
    // Q4: If I start executing commands on the connection now,
    // will it automatically become enlisted in the current transaction scope? (No?)
    //
    // Q5: If not enlisted, will commands I execute on the connection now
    // participate in the ambient transaction? (No?)
    //
    // Q6: If commands on this connection are
    // not participating in the current transaction, will they be committed
    // even if rollback the current transaction scope? (Yes?)
    //
    // If my thoughts are correct, all of the above is disturbing,
    // because it would look like I'm executing commands
    // in a transaction scope, when in fact I'm not at all,
    // until I do the following...
    //
    // Now enlisting existing connection in current transaction
    conn.EnlistTransaction( Transaction.Current );
    //
    // Q7: Does the above method explicitly enlist the pre-existing connection
    // in the current ambient transaction, so that commands I
    // execute on the connection now participate in the
    // ambient transaction? (Yes?)
    //
    // Q8: If the existing connection was already enlisted in a transaction
    // when I called the above method, what would happen?  Might an error be thrown? (Probably?)
    //
    // Q9: If the existing connection was already enlisted in a transaction
    // and I did NOT call the above method to enlist it, would any commands
    // I execute on it participate in it's existing transaction rather than
    // the current transaction scope. (Yes?)
}
</code>```

答:
One other bizarre situation we've seen is that if you construct an EntityConnectionStringBuilder it will muck with TransactionScope.Current and (we think) enlist in the transaction. We've observed this in the debugger, where TransactionScope.Current's current.TransactionInformation.internalTransaction shows enlistmentCount == 1 before constructing, and enlistmentCount == 2 afterward.

To avoid this, construct it inside

using (new TransactionScope(TransactionScopeOption.Suppress))

and possibly outside the scope of your operation (we were constructing it every time we needed a connection).

Body:
What does it mean for an SqlConnection to be "enlisted" in a transaction?  Does it simply mean that commands I execute on the connection will participate in the transaction?

If so, under what circumstances is an SqlConnection automatically enlisted in an ambient TransactionScope Transaction?

See questions in code comments.  My guess to each question's answer follows each question in parenthesis.

Scenario 1: Opening connections INSIDE a transaction scope

using (TransactionScope scope = new TransactionScope())
using (SqlConnection conn = ConnectToDB())
{
    // Q1: Is connection automatically enlisted in transaction? (Yes?)
    //
    // Q2: If I open (and run commands on) a second connection now,
    // with an identical connection string,
    // what, if any, is the relationship of this second connection to the first?
    //
    // Q3: Will this second connection's automatic enlistment
    // in the current transaction scope cause the transaction to be
    // escalated to a distributed transaction? (Yes?)
}

Scenario 2: Using connections INSIDE a transaction scope that were opened OUTSIDE of it

//Assume no ambient transaction active now
SqlConnection new_or_existing_connection = ConnectToDB(); //or passed in as method parameter
using (TransactionScope scope = new TransactionScope())
{
    // Connection was opened before transaction scope was created
    // Q4: If I start executing commands on the connection now,
    // will it automatically become enlisted in the current transaction scope? (No?)
    //
    // Q5: If not enlisted, will commands I execute on the connection now
    // participate in the ambient transaction? (No?)
    //
    // Q6: If commands on this connection are
    // not participating in the current transaction, will they be committed
    // even if rollback the current transaction scope? (Yes?)
    //
    // If my thoughts are correct, all of the above is disturbing,
    // because it would look like I'm executing commands
    // in a transaction scope, when in fact I'm not at all,
    // until I do the following...
    //
    // Now enlisting existing connection in current transaction
    conn.EnlistTransaction( Transaction.Current );
    //
    // Q7: Does the above method explicitly enlist the pre-existing connection
    // in the current ambient transaction, so that commands I
    // execute on the connection now participate in the
    // ambient transaction? (Yes?)
    //
    // Q8: If the existing connection was already enlisted in a transaction
    // when I called the above method, what would happen?  Might an error be thrown? (Probably?)
    //
    // Q9: If the existing connection was already enlisted in a transaction
    // and I did NOT call the above method to enlist it, would any commands
    // I execute on it participate in it's existing transaction rather than
    // the current transaction scope. (Yes?)
}


问:
Override a Method from a Stateless Spring Service with Additional Parameter
I'm trying to improve the structure of some code I wrote. I want to override a method of a service, but need another parameter/object for the new functionality. In plain Java, I would solve this by making the needed object an attribute of the class and initialized in the constructor. But because this is a bean, the constructor has no arguments.

```<code>@Service("testService")
public class TestService extends AbstractService {
    @Override
    public String perform(String original) {
        return original + extra; //<-- What's the best way to get
                                 //    'extra' here from the controller
                                 //    without going stateful?
    }
}

######

public abstract class AbstractService {
    public String perform(String original);
}
</code>```

I think my problem is best described by the code and comments above. How would I get the object to be accessible from that method without adding attributes to the class?

I'm very new to Spring, so feel free to tell me I'm way off track.

答:
You're way off track. Beans can (and should) have constructor arguments for all the classes they depend on.

You should put @Autowired or @Inject before the constructor method which will make spring inject it's parameters from the beans that it knows about. Of course, you'll have to make this 'extra' object a spring bean too.

Body:
I'm trying to improve the structure of some code I wrote. I want to override a method of a service, but need another parameter/object for the new functionality. In plain Java, I would solve this by making the needed object an attribute of the class and initialized in the constructor. But because this is a bean, the constructor has no arguments.

@Service("testService")
public class TestService extends AbstractService {
    @Override
    public String perform(String original) {
        return original + extra; //<-- What's the best way to get
                                 //    'extra' here from the controller
                                 //    without going stateful?
    }
}

######

public abstract class AbstractService {
    public String perform(String original);
}

I think my problem is best described by the code and comments above. How would I get the object to be accessible from that method without adding attributes to the class?

I'm very new to Spring, so feel free to tell me I'm way off track.