问:
Docker cannot start on Windows
Executing docker version command on Windows returns the following results:

```<code>C:\Projects> docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/version: open //./pipe/docker_engine: The system cannot find the file
specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
</code>```

Running the diagnostics produces the following:

```<code>C:\Projects> wget https://github.com/Microsoft/Virtualization-
Documentation/raw/master/windows-server-container-tools/Debug-
ContainerHost/Debug-ContainerHost.ps1 -UseBasicParsin | iex

Checking for common problems
Describing Windows Version and Prerequisites
 [+] Is Windows 10 Anniversary Update or Windows Server 2016 608ms
 [+] Has KB3192366, KB3194496, or later installed if running Windows build 14393 141ms
 [+] Is not a build with blocking issues 29ms
Describing Docker is installed
 [-] A Docker service is installed - 'Docker' or 'com.Docker.Service'  134ms
   Expected: value to not be empty
   27:         $services | Should Not BeNullOrEmpty
   at <ScriptBlock>, <No file>: line 27
 [+] Service is running 127ms
 [+] Docker.exe is in path 2.14s
Describing User has permissions to use Docker daemon
 [+] docker.exe should not return access denied 42ms
Describing Windows container settings are correct
 [-] Do not have DisableVSmbOplock set to 1 53ms
   Expected: {0}
   But was:  {1}
   66:              $regvalue.VSmbDisableOplocks | Should Be 0
   at <ScriptBlock>, <No file>: line 66
 [+] Do not have zz values set 42ms
Describing The right container base images are installed
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/images/json: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
 [-] At least one of 'microsoft/windowsservercore' or 'microsoft/nanoserver' should be installed 129ms
   ValidationMetadataException: The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
   ParameterBindingValidationException: Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
   at <ScriptBlock>, <No file>: line 90
Describing Container network is created
 [-] Error occurred in Describe block 1.08s
   RuntimeException: Cannot index into a null array.
   at <ScriptBlock>, <No file>: line 119
Showing output from: docker info

Showing output from: docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64

Showing output from: docker network ls

Warnings & errors from the last 24 hours
Logs saved to C:\Projects\logs_20161107-084122.csv
C:\Projects>
</code>```

答:
I am using Windows 7 with Docker Toolbox and to fix it just open
Docker Quickstart Terminal.

$ docker version Client:  Version:      17.05.0-ce  API version:  1.29
  Go version:   go1.7.5  Git commit:   89658be  Built:        Fri May  5
  15:36:11 2017  OS/Arch:      windows/amd64

Server:  Version:      17.05.0-ce  API version:  1.29 (minimum version
  1.12)  Go version:   go1.7.5  Git commit:   89658be  Built:        Thu May  4 21:43:09 2017  OS/Arch:      linux/amd64  Experimental: false

Title: Docker cannot start on Windows

Body:
Executing docker version command on Windows returns the following results:

C:\Projects> docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/version: open //./pipe/docker_engine: The system cannot find the file
specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.

Running the diagnostics produces the following:

C:\Projects> wget https://github.com/Microsoft/Virtualization-
Documentation/raw/master/windows-server-container-tools/Debug-
ContainerHost/Debug-ContainerHost.ps1 -UseBasicParsin | iex

Checking for common problems
Describing Windows Version and Prerequisites
 [+] Is Windows 10 Anniversary Update or Windows Server 2016 608ms
 [+] Has KB3192366, KB3194496, or later installed if running Windows build 14393 141ms
 [+] Is not a build with blocking issues 29ms
Describing Docker is installed
 [-] A Docker service is installed - 'Docker' or 'com.Docker.Service'  134ms
   Expected: value to not be empty
   27:         $services | Should Not BeNullOrEmpty
   at


来源: stackexchange

问:
How to make QTableWidget adjust to minimal space
Using PyQt5 with Python, I am trying to create a grid of QTableWidgets with various numbers of cells. I make the tables adjustable in size so that they fit nicely to the available size of the window. I am able to adjust the tables correctly while increasing the window size, that is, the cells maintain equal sizes and the QTableWidgets adjust their sizes to the free space. This adjustment is done by overwriting the resizeEvent of QTableWidget class and by setting row and column stretches for QGridLayout. This is illustrated in the figure below.

However, while making the QMainWindow smaller, the QTableWidgets at some point become unable to adjust their sizes smaller.

Is it possible to enable the QTableWidgets to get smaller in sizes when making the window smaller? Clearly, the values in the cells would enable this.

A code with which I have implemented the above table grids is given below.

```<code>import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QGridLayout
from PyQt5.QtWidgets import QTableWidget, QWidget

class MyTable(QTableWidget):
    def __init__(self, r, c):
        super().__init__(r, c)
        self.horizontalHeader().hide()
        self.verticalHeader().hide()
    def resizeEvent(self, event):
        eh          = event.size().height()
        ew          = event.size().width()
        ehremain    = eh
        eqremain    = ew
        rh          = int(eh // self.rowCount())
        cw          = int(ew // self.columnCount())
        for i in range(self.rowCount()-1):
            self.setRowHeight(i, rh)
            ehremain -= rh
        self.setRowHeight(self.rowCount()-1, ehremain)
        for j in range(self.columnCount()-1):
            self.setColumnWidth(j, cw)
            eqremain -= cw
        self.setColumnWidth(self.columnCount()-1, eqremain)

class TableGrid(QWidget):
    def __init__(self):
        super().__init__()
        self.table1 = MyTable(1,1)
        self.table2 = MyTable(1,3)
        self.table3 = MyTable(3,1)
        self.table4 = MyTable(3,3)
        grid_layout = QGridLayout()
        grid_layout.addWidget(self.table1, 0,0)
        grid_layout.addWidget(self.table2, 0,1)
        grid_layout.addWidget(self.table3, 1,0)
        grid_layout.addWidget(self.table4, 1,1)
        grid_layout.setRowStretch(0,1)
        grid_layout.setRowStretch(1,3)
        grid_layout.setColumnStretch(0,1)
        grid_layout.setColumnStretch(1,3)
        self.setLayout(grid_layout)
        self.show()

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.table_grid = TableGrid()
        self.setCentralWidget(self.table_grid)
        self.show()

if __name__ =="__main__":
    app     = QApplication.instance() # checks if QApplication already exists
    if not app: # create QApplication if it doesnt exist
        app    = QApplication(sys.argv)
    app.aboutToQuit.connect(app.deleteLater)
    sheet   = Window()
    app.exec_()
    #sys.exit(0)
</code>```

答:
The tables won't resize smaller than their default minimum size. So just choose a more appropriate value, like this:</p>

```<code>class MyTable(QTableWidget):
    def __init__(self, r, c):
        ...
        self.setMinimumSize(40, 40)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using PyQt5 with Python, I am trying to create a grid of QTableWidgets with various numbers of cells. I make the tables adjustable in size so that they fit nicely to the available size of the window. I am able to adjust the tables correctly while increasing the window size, that is, the cells maintain equal sizes and the QTableWidgets adjust their sizes to the free space. This adjustment is done by overwriting the resizeEvent of QTableWidget class and by setting row and column stretches for QGridLayout. This is illustrated in the figure below.

However, while making the QMainWindow smaller, the QTableWidgets at some point become unable to adjust their sizes smaller.

Is it possible to enable the QTableWidgets to get smaller in sizes when making the window smaller? Clearly, the values in the cells would enable this.

A code with which I have implemented the above table grids is given below.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QGridLayout
from PyQt5.QtWidgets import QTableWidget, QWidget

class MyTable(QTableWidget):
    def __init__(self, r, c):
        super().__init__(r, c)
        self.horizontalHeader().hide()
        self.verticalHeader().hide()
    def resizeEvent(self, event):
        eh          = event.size().height()
        ew          = event.size().width()
        ehremain    = eh
        eqremain    = ew
        rh          = int(eh // self.rowCount())
        cw          = int(ew // self.columnCount())
        for i in range(self.rowCount()-1):
            self.setRowHeight(i, rh)
            ehremain -= rh
        self.setRowHeight(self.rowCount()-1, ehremain)
        for j in range(self.columnCount()-1):
            self.setColumnWidth(j, cw)
            eqremain -= cw
        self.setColumnWidth(self.columnCount()-1, eqremain)

class TableGrid(QWidget):
    def __init__(self):
        super().__init__()
        self.table1 = MyTable(1,1)
        self.table2 = MyTable(1,3)
        self.table3 = MyTable(3,1)
        self.table4 = MyTable(3,3)
        grid_layout = QGridLayout()
        grid_layout.addWidget(self.table1, 0,0)
        grid_layout.addWidget(self.table2, 0,1)
        grid_layout.addWidget(self.table3, 1,0)
        grid_layout.addWidget(self.table4, 1,1)
        grid_layout.setRowStretch(0,1)
        grid_layout.setRowStretch(1,3)
        grid_layout.setColumnStretch(0,1)
        grid_layout.setColumnStretch(1,3)
        self.setLayout(grid_layout)
        self.show()

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.table_grid = TableGrid()
        self.setCentralWidget(self.table_grid)
        self.show()

if __name__ =="__main__":
    app     = QApplication.instance() # checks if QApplication already exists
    if not app: # create QApplication if it doesnt exist
        app    = QApplication(sys.argv)
    app.aboutToQuit.connect(app.deleteLater)
    sheet   = Window()
    app.exec_()
    #sys.exit(0)

Body:
The tables won't resize smaller than their default minimum size. So just choose a more appropriate value, like this:

class MyTable(QTableWidget):
    def __init__(self, r, c):
        ...
        self.setMinimumSize(40, 40)


问:
Group By Error in SQL Server SQL Server 2016
I am trying to run the following query:

```<code>select en.NAME as ClusterName, ds.NAME ,
ROUND((CAST(ds.capacity as float))/1024/1024/1024,2) as
Total_Allocated_GB,
ROUND((CAST(ds.FREE_SPACE as float))/1024/1024/1024,2)as Free_Space_GB
from dbo.VPXV_DATASTORE DS, dbo.VPXV_HOST_DATASTORE HSDS, VPXV_ENTITY
en, VPXV_HOSTS hs
where
HSDS.DS_ID = DS.ID  and
hs.HOSTID  = hsds.HOST_ID and
en.id = hs.FARMID
GROUP BY en.NAME
</code>```

I get the following error:

```<code>Msg 8120, Level 16, State 1, Line 1
Column 'dbo.VPXV_DATASTORE.NAME' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
</code>```

How can I get these to group by en.NAME?

答:
You have to group by columns that are not being aggregated. I am guessing you want the sum() those two calculations and also group by en.name and ds.name.

```<code>select
    ClusterName = en.name
  , ds.name
  , Total_Allocated_gb = sum(round((cast(ds.capacity as float)) / 1024 / 1024 / 1024, 2))
  , Free_Space_gb = sum(round((cast(ds.free_space as float)) / 1024 / 1024 / 1024, 2))
from dbo.vpxv_datastore ds
  inner join dbo.vpxv_host_datastore hsds
    on hsds.ds_id = ds.id
  inner join vpxv_hosts hs
    on hs.hostid = hsds.host_id
  inner join vpxv_entity en
    on en.id = hs.farmid
group by
    en.name
  , ds.name
</code>```

Body:
I am trying to run the following query:

select en.NAME as ClusterName, ds.NAME ,
ROUND((CAST(ds.capacity as float))/1024/1024/1024,2) as
Total_Allocated_GB,
ROUND((CAST(ds.FREE_SPACE as float))/1024/1024/1024,2)as Free_Space_GB
from dbo.VPXV_DATASTORE DS, dbo.VPXV_HOST_DATASTORE HSDS, VPXV_ENTITY
en, VPXV_HOSTS hs
where
HSDS.DS_ID = DS.ID  and
hs.HOSTID  = hsds.HOST_ID and
en.id = hs.FARMID
GROUP BY en.NAME

I get the following error:

Msg 8120, Level 16, State 1, Line 1
Column 'dbo.VPXV_DATASTORE.NAME' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

How can I get these to group by en.NAME?

Body:
You have to group by columns that are not being aggregated. I am guessing you want the sum() those two calculations and also group by en.name and ds.name.

select
    ClusterName = en.name
  , ds.name
  , Total_Allocated_gb = sum(round((cast(ds.capacity as float)) / 1024 / 1024 / 1024, 2))
  , Free_Space_gb = sum(round((cast(ds.free_space as float)) / 1024 / 1024 / 1024, 2))
from dbo.vpxv_datastore ds
  inner join dbo.vpxv_host_datastore hsds
    on hsds.ds_id = ds.id
  inner join vpxv_hosts hs
    on hs.hostid = hsds.host_id
  inner join vpxv_entity en
    on en.id = hs.farmid
group by
    en.name
  , ds.name


问:
Move a button by setting CSS using Javascript

 <!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

     <link rel="stylesheet" href="./files/font-awesome.min.css">

Do you love KWEB?

   <button onclick="alertKWEB()">I do</button>
   <button class="button2" onclick="alertKWEB2()" onmouseover="moveButtonRand()">.....</button>

 ```

I want to make the second button move to a random position when I put the cursor over it. I don't understand why this does not work; please help! This is my school homework which entails using the JS DOM, so please do not suggest other ways.

答:
document.getElementsByClassName() returns an HTMLCollection not an individual element. You can solve this by referencing the first element in the HTMLCollection:

```<code>var buttonTag = document.getElementsByClassName('button2')[0];
</code>```

Or use document.querySelector():

```<code>var buttonTag = document.querySelector('.button2');
</code>```

Body:
 <!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

     <link rel="stylesheet" href="./files/font-awesome.min.css">

Do you love KWEB?

   <button onclick="alertKWEB()">I do</button>
   <button class="button2" onclick="alertKWEB2()" onmouseover="moveButtonRand()">.....</button>

I want to make the second button move to a random position when I put the cursor over it. I don't understand why this does not work; please help! This is my school homework which entails using the JS DOM, so please do not suggest other ways.

Body:
document.getElementsByClassName() returns an HTMLCollection not an individual element. You can solve this by referencing the first element in the HTMLCollection:

var buttonTag = document.getElementsByClassName('button2')[0];

Or use document.querySelector():

var buttonTag = document.querySelector('.button2');


问:
NetBSD build failing due to .DS_Store file Macintosh
I am trying to build the NetBSD kernel using

```<code>$ ./build.sh -O ../obj.amd64 -U -u -m amd64 -j4 tools release iso-image
</code>```

It fails with the output

```<code>=======  1 extra files in DESTDIR  =========
Files in DESTDIR but missing from flist.
File is obsolete or flist is out of date ?
------------------------------------------
./.DS_Store
=========  end of 1 extra files  ===========
*** [checkflist] Error code 1

nbmake[2]: stopped in /Volumes/NetBSDImage/src/distrib/sets
1 error
</code>```

Even when I do an
rm .DS_Store in /Volumes/NetBSDImage/src/distrib/sets, it fails with the same message.
Earlier, when I compiled the kernel without the iso-image option, it build successfully, but now, even that fails. Some help?

答: I can crosscompile NetBSD-current fine from OS X without those files getting in the way. Did you do some manual work in destdir? Try removing the bad files then retry.</p>

Body:
I am trying to build the NetBSD kernel using

$ ./build.sh -O ../obj.amd64 -U -u -m amd64 -j4 tools release iso-image

It fails with the output

=======  1 extra files in DESTDIR  =========
Files in DESTDIR but missing from flist.
File is obsolete or flist is out of date ?
------------------------------------------
./.DS_Store
=========  end of 1 extra files  ===========
*** [checkflist] Error code 1

nbmake[2]: stopped in /Volumes/NetBSDImage/src/distrib/sets
1 error

Even when I do an
rm .DS_Store in /Volumes/NetBSDImage/src/distrib/sets, it fails with the same message.
Earlier, when I compiled the kernel without the iso-image option, it build successfully, but now, even that fails. Some help?


问:
Copying 15 million records to a new table/server
Good day. I need to move 15 Million Records from one MySQL table to a new table on other schemas. This is a live system and time is a problem. The table I need to move is a history table and isn't important for day to day business. I can't leave the table as it is part of a bigger upgrade I am doing.

I tried just moving the data with basic sql in a test environment but this doesn't work; the server kicks me out after 20min.

What would be the best way of moving the data?

I am a C# programmer  if someone has a coding solution

答:
Well, it is important to know how you connect the two. Is they reside inside single MSSQL instance or different? Because it seems like you try to download entire history into memory of your application...

Either way, you can always move your data in batches. For example, you can do it in Entity Framework like this:

```<code>using(var src = new MyFirstContext())
using(var tr = src.DataBase.BeginTransaction(IsolationLevel.ReadUncommited)) //this will speed up read of history
{
    int i = 0;
    const int batchSize = 100000;
    try
    {
        while(true)
        {
            var batch = src.History.AsNoTracking().Skip(i*batchSize).Take(batchSize).ToList();
            if(!batch.Any())
            {
                break;
            }
            using(var dst = new MySecondContext())
            {
                dst.Configuration.AutoDetectChangesEnabled = false;
                foreach(var ent1 in batch)
                {
                    var ent2 = Map(ent1); //here you can perform map of one history type of row to another.
                    dst.Set<HistoryRowFromSecondDatabase>().Add(ent2);
                }
                dst.SaveChanges();
            }
            i++;
        }
    }
    finally
    {
        //this is really helpful scope in case of exception.
        //save variable 'i', so you can start from the point you left last time.
        //Because by default your data is commited under ReadCommited transaction, it is pretty safe to rely only on
        //single 'i' variable. Even if you add some new data in source table.
    }
}
</code>```

I have not tested this, but I think you get the idea.

Body:
Well, it is important to know how you connect the two. Is they reside inside single MSSQL instance or different? Because it seems like you try to download entire history into memory of your application...

Either way, you can always move your data in batches. For example, you can do it in Entity Framework like this:

using(var src = new MyFirstContext())
using(var tr = src.DataBase.BeginTransaction(IsolationLevel.ReadUncommited)) //this will speed up read of history
{
    int i = 0;
    const int batchSize = 100000;
    try
    {
        while(true)
        {
            var batch = src.History.AsNoTracking().Skip(i*batchSize).Take(batchSize).ToList();
            if(!batch.Any())
            {
                break;
            }
            using(var dst = new MySecondContext())
            {
                dst.Configuration.AutoDetectChangesEnabled = false;
                foreach(var ent1 in batch)
                {
                    var ent2 = Map(ent1); //here you can perform map of one history type of row to another.
                    dst.Set<HistoryRowFromSecondDatabase>().Add(ent2);
                }
                dst.SaveChanges();
            }
            i++;
        }
    }
    finally
    {
        //this is really helpful scope in case of exception.
        //save variable 'i', so you can start from the point you left last time.
        //Because by default your data is commited under ReadCommited transaction, it is pretty safe to rely only on
        //single 'i' variable. Even if you add some new data in source table.
    }
}

I have not tested this, but I think you get the idea.


问:
Why does the compiler not give an ambiguous reference error?
With reference to the following code

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

using std::cout;
using std::endl;
using std::string;

template <typename... Args>
void bar(Args&&...) {}

int change(const string&) { return 1; }
double change(int) { return 1.0; }

int main() {
    // bar(1, 2.0, static_cast<int(*)(const string&)>(&change));
    bar(1, 2.0, &change);
    return 0;
}
</code>```

I understand that the error in the above code is that the reference to the change function is ambiguous (which is why the commented line works), but then why does the compiler give this error message?

```<code>test.cpp:17:5: error: no matching function for call to 'bar'
    bar(1, 2.0, &change);
    ^~~
test.cpp:11:6: note: candidate function not viable: requires 2 arguments, but 3 were
      provided
void bar(Args&&...) {}
     ^
1 error generated.
</code>```

This happens both on gcc (>5) as well as clang (Apple LLVM version 8.0.0 (clang-800.0.42.1))

I am just curious as to why both the compilers do not just say that the reference is ambiguous.  I feel like it has something to do with how template instantiations work in C++ but I am not sure of the exact reason.

答:
I think the compiler is right, however weird it may be. Template argument deduction rules are different from substitution. The ambiguity in overloaded function resolution in a template parameter pack context does not necessarily mean failure.

See [temp.deduct.call]/p6:

When P is a function type, function pointer type, or pointer to member
  function type:

...

-- If the argument is an overload set (not containing function templates), trial argument deduction is attempted using each of the
  members of the set.
      If deduction succeeds for only one of the overload set members, that member is used as the argument value for the deduction.
      If deduction succeeds for more than one member of the overload set the parameter is treated as a non-deduced context.

So for the last argument of the parameter pack we're in a non-deduced context (not an error).

And [temp.arg.explicit]/p3:

... A trailing template parameter pack not otherwise deduced will be deduced to an empty sequence of template arguments. ...

So it seems to me (although this last bit doesn't say it explicitly for partially deduced parameter packs) the ambiguous function pointer is simply thrown away at deduction phase, and subsequently the substitution fails because it is trying to substitute 3 arguments into a deduced 2-argument function. It never gets to a point when it needs to resolve ambiguity.

Body:
With reference to the following code

#include <iostream>
#include <tuple>
#include <string>
#include <type_traits>

using std::cout;
using std::endl;
using std::string;

template <typename... Args>
void bar(Args&&...) {}

int change(const string&) { return 1; }
double change(int) { return 1.0; }

int main() {
    // bar(1, 2.0, static_cast<int(*)(const string&)>(&change));
    bar(1, 2.0, &change);
    return 0;
}

I understand that the error in the above code is that the reference to the change function is ambiguous (which is why the commented line works), but then why does the compiler give this error message?

test.cpp:17:5: error: no matching function for call to 'bar'
    bar(1, 2.0, &change);
    ^~~
test.cpp:11:6: note: candidate function not viable: requires 2 arguments, but 3 were
      provided
void bar(Args&&...) {}
     ^
1 error generated.

This happens both on gcc (>5) as well as clang (Apple LLVM version 8.0.0 (clang-800.0.42.1))

I am just curious as to why both the compilers do not just say that the reference is ambiguous.  I feel like it has something to do with how template instantiations work in C++ but I am not sure of the exact reason.


问:
Excel: Counting number of male and female employees
It might be a basic question but I'm struggling to come up with a function. I have two columns on a spreadsheet: Employee ID and Sex (Male=1). A sample data is as follows: CAPTURE IMAGE

Each data entry is an unique observation, and I want to count the number of males and females. For example, there are 2 females and 1 male employee out of 32 observations. What forumula can I use to calculate the numbers?

答: If you are willing to add another column to hold whether or not the row is a duplicate or not, you can use the SUMIF function to add up the total number in your sex column (number of males) and compare it to your total duplicates.</p>


问:
Django Admin override displayed field value
I have following model:

```<code>class Model(models.Model):

    creator = models.ForeignKey(User,related_name='com_creator',on_delete=models.SET_NULL, blank=True, null=True)
    username = models.CharField(max_length=60,default="")
    created = models.DateTimeField(auto_now_add=True)
    body = models.TextField(max_length=10000,default=" ")
    subtype = models.CharField(_("SubType"),max_length=100)
    typ = models.CharField(_("Type"),max_length=50)
    plus = models.ManyToManyField(User,related_name='com_plus', verbose_name=_('Plus'), blank=True)
    is_anonymous = models.BooleanField(_('Stay Anonymous'), blank=True, default=False)
</code>```

The values in typ and subtype are codes, like: "6_0_p", (because the original values are ridiculosly long, so I use codes and a dict to translate to human readable form).

QUESTION: How can I intercept these values in django admin and translate them to human readable form?

This is what i tried so far:

```<code>class ModelAdmin(admin.ModelAdmin):
    model = Model
    extra = 1
    exclude = ("username","creator","plus" )
    readonly_fields = ('subtype','typ','is_anonymous','created')
    fields = ('body','subtype','typ')

    def typ(self, obj):
        self.typ = "ppp"
        obj.typ = "ppp"
        return "pppp"
</code>```

I tried returning the object, self, some other value. I also tried to set the value without using a callable just declaring "typ='xxx'". Nothing. I probably don't understand how this whole thing works ...

Any ideas will be appreciated.

答:
You need to create a readonly_field which corresponds to your method name, then return anything from that method.

Documentation here:
https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields

```<code>class MyAdmin(admin.ModelAdmin):
    readonly_fields = ('my_custom_field',)

    def my_custom_field(self, obj):
        return 'Return Anything Here'
</code>```

Body:
I have following model:

class Model(models.Model):

    creator = models.ForeignKey(User,related_name='com_creator',on_delete=models.SET_NULL, blank=True, null=True)
    username = models.CharField(max_length=60,default="")
    created = models.DateTimeField(auto_now_add=True)
    body = models.TextField(max_length=10000,default=" ")
    subtype = models.CharField(_("SubType"),max_length=100)
    typ = models.CharField(_("Type"),max_length=50)
    plus = models.ManyToManyField(User,related_name='com_plus', verbose_name=_('Plus'), blank=True)
    is_anonymous = models.BooleanField(_('Stay Anonymous'), blank=True, default=False)

The values in typ and subtype are codes, like: "6_0_p", (because the original values are ridiculosly long, so I use codes and a dict to translate to human readable form).

QUESTION: How can I intercept these values in django admin and translate them to human readable form?

This is what i tried so far:

class ModelAdmin(admin.ModelAdmin):
    model = Model
    extra = 1
    exclude = ("username","creator","plus" )
    readonly_fields = ('subtype','typ','is_anonymous','created')
    fields = ('body','subtype','typ')

    def typ(self, obj):
        self.typ = "ppp"
        obj.typ = "ppp"
        return "pppp"

I tried returning the object, self, some other value. I also tried to set the value without using a callable just declaring "typ='xxx'". Nothing. I probably don't understand how this whole thing works ...

Any ideas will be appreciated.

Body:
You need to create a readonly_field which corresponds to your method name, then return anything from that method.

Documentation here:
https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields

class MyAdmin(admin.ModelAdmin):
    readonly_fields = ('my_custom_field',)

    def my_custom_field(self, obj):
        return 'Return Anything Here'


问:
Is there any way of obtaining Developer Disk Image of iOS 11 for Xcode?
Currently I'm using macOS Sierra with Xcode 8 installed. I just updated my device to iOS 11, which is my main development device. I can't build the apps I'm working on anymore because Xcode 8 has no iOS 11 Development Disk Image. Is there any way of obtaining the image (without installing Xcode 9) or I'll have to go back to iOS 10 in order to build to my device?</p>

答:
This may solve your problem: https://stackoverflow.com/a/44383054/4146322

On another note, it is nearly impossible to revert to iOS 10 once you install iOS 11. Apple has incorporated checks for this at a deep level to prevent people installing older and possibly unsecured versions. You can read up on this at Apple's iOS10 Security Documentation in the second paragraph of page 6.


问:
(Kivy/Python) Store text from textinput widget when user hits enter
I've been playing around with the kivy library and have been trying to create a GUI for the game hangman [1]. I'm trying to create a TextField that a user enters a single letter and it changes the button text ONLY when they press return/enter, instead of the constant stream that textinput.text gives .

I've looked at the docs and other stackoverflow Q&A's and it seems the solution lies with either the on_text_validate event or changing my Clock.schedule.interval setup, but I can't figure out how to implement it in my code.

My python file:

```<code>from kivy.app import App
from kivy.clock import Clock
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput

class HangmanBoard(BoxLayout):
    word = 'hangman'
    empty = ["_"]*len(word)

    def update(self, *args):
        empty_word = self.ids['labelA']
        letter_input = self.ids['labelB']

        guess = letter_input.text
        empty_word.text = ' '.join(self.empty)

        if guess in self.word:
            for i in range(len(self.word)):
                if guess == self.word[i]:
                    self.empty[i] = guess

        print(guess)

class HangmanApp(App):

    def build(self):
        game = HangmanBoard()
        Clock.schedule_interval(game.update, 1)
        return game

if __name__ == '__main__':
    HangmanApp().run() here
</code>```

My Kv file:

```<code><HangmanBoard>:
orientation: 'vertical'

Button:
    id: labelA
    font_size: 60
    size_hint: 1, 0.5
TextInput:
    id: labelB
    font_size: 60
    pos_hint: {'center_x':0.5}
    size_hint: 1, 0.5
    focus: True
    multiline: False
</code>```

答:
Yes, you can either have a "when user stopped typing for 1 second" mechanic with Clock events or just have an on_text_validate update the button's text, the latter being simpler and more straight-forward:

```<code>TextInput:
    on_text_validate:
        labelA.text = self.text
    # ...
</code>```

Body:
I've been playing around with the kivy library and have been trying to create a GUI for the game hangman [1]. I'm trying to create a TextField that a user enters a single letter and it changes the button text ONLY when they press return/enter, instead of the constant stream that textinput.text gives .

I've looked at the docs and other stackoverflow Q&A's and it seems the solution lies with either the on_text_validate event or changing my Clock.schedule.interval setup, but I can't figure out how to implement it in my code.

My python file:

from kivy.app import App
from kivy.clock import Clock
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput

class HangmanBoard(BoxLayout):
    word = 'hangman'
    empty = ["_"]*len(word)

    def update(self, *args):
        empty_word = self.ids['labelA']
        letter_input = self.ids['labelB']

        guess = letter_input.text
        empty_word.text = ' '.join(self.empty)

        if guess in self.word:
            for i in range(len(self.word)):
                if guess == self.word[i]:
                    self.empty[i] = guess

        print(guess)

class HangmanApp(App):

    def build(self):
        game = HangmanBoard()
        Clock.schedule_interval(game.update, 1)
        return game

if __name__ == '__main__':
    HangmanApp().run() here

My Kv file:

<HangmanBoard>:
orientation: 'vertical'

Button:
    id: labelA
    font_size: 60
    size_hint: 1, 0.5
TextInput:
    id: labelB
    font_size: 60
    pos_hint: {'center_x':0.5}
    size_hint: 1, 0.5
    focus: True
    multiline: False

Body:
Yes, you can either have a "when user stopped typing for 1 second" mechanic with Clock events or just have an on_text_validate update the button's text, the latter being simpler and more straight-forward:

TextInput:
    on_text_validate:
        labelA.text = self.text
    # ...


问:
PHP look through every root directory for keyword
So I tried for some days to get this done. But I still don't have a single clue how i could build this code so it works. Maybe someone has an idea.

Goal: Automaticely iterate through the root-directory and any of it's subdirectories. If there's a directory, which matches the keyword it should be stored into an array.

I am only looking for directories, that's why there's a regex to exclude every object with a dot in it's name. Not perfect yet, but that's not a problem.

I ll post the first version of my code. Now it's just scanning the directory your handling to the function when calling it. Because all my other attempts are trash and this one at least works

```<code>searchformigration('/');

/* Check for related folders, that could be used for a migration */
function searchformigration($dir)
{
    $scanned_elements = scandir($dir);

    for($c = 0; $c <= (count($scanned_elements) - 1); $c++)
    {
        /* Anything but files containing a dot (hidden files, files) */
        if(preg_match('/^[^.]+$/', $scanned_elements[$c]))
        {
            /* Checking for the keyword "Project" */
            if($scanned_elements[$c] == '*Project*')
            {
                echo $scanned_elements[$c];
                echo '</br>';
            }
            else
            {
                continue;
            }
        }
        else
        {
            continue;
        }
    }
}
</code>```

答:
You can recursively retrieve files and folders with RecursiveDirectoryIterator, this will search in / for directories with 'project' in the foldername.</p>

```<code>print_r(get_dirs('/','project'));

function get_dirs($path = '.', $search='') {

$dirs = array();

$iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($path),
            RecursiveIteratorIterator::SELF_FIRST);

    foreach ($iterator as $file) {
        if ($file->isDir())
        {

            if (strpos($file->getFileName(), $search) !== false)
            {
                $dirs[] = $file->getRealPath();
            }
        }
    }

    return $dirs;
}
</code>```

Body:
So I tried for some days to get this done. But I still don't have a single clue how i could build this code so it works. Maybe someone has an idea.

Goal: Automaticely iterate through the root-directory and any of it's subdirectories. If there's a directory, which matches the keyword it should be stored into an array.

I am only looking for directories, that's why there's a regex to exclude every object with a dot in it's name. Not perfect yet, but that's not a problem.

I ll post the first version of my code. Now it's just scanning the directory your handling to the function when calling it. Because all my other attempts are trash and this one at least works

searchformigration('/');

/* Check for related folders, that could be used for a migration */
function searchformigration($dir)
{
    $scanned_elements = scandir($dir);

    for($c = 0; $c <= (count($scanned_elements) - 1); $c++)
    {
        /* Anything but files containing a dot (hidden files, files) */
        if(preg_match('/^[^.]+$/', $scanned_elements[$c]))
        {
            /* Checking for the keyword "Project" */
            if($scanned_elements[$c] == '*Project*')
            {
                echo $scanned_elements[$c];
                echo '
';
            }
            else
            {
                continue;
            }
        }
        else
        {
            continue;
        }
    }
}

Body:
You can recursively retrieve files and folders with RecursiveDirectoryIterator, this will search in / for directories with 'project' in the foldername.

print_r(get_dirs('/','project'));

function get_dirs($path = '.', $search='') {

$dirs = array();

$iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($path),
            RecursiveIteratorIterator::SELF_FIRST);

    foreach ($iterator as $file) {
        if ($file->isDir())
        {

            if (strpos($file->getFileName(), $search) !== false)
            {
                $dirs[] = $file->getRealPath();
            }
        }
    }

    return $dirs;
}


问:
Spring XD unable to find class definition for RabbitMQ ConnectionFactory
I am in the process of switching from xd-singlenode mode to distributed, using version 1.3.1-RELEASE.

I am running Spring XD in a docker container, with a Dockerfile similar to the one here. According to the XD guide, if I want to use RabbitMQ as my data transport, then I need to configure a servers.yml file.  I have RabbitMQ running in a separate docker container, and I link these two containers together as part of a docker composition.

In short, I have configured everything (I believe correctly), but when I go to run multiple streams in Spring XD (which is when RabbitMQ would come into play, since it will act as a message transport between containers) Spring XD throws the following exception:

```<code>java.lang.NoClassDefFoundError: org/springframework/amqp/rabbit/connection/ConnectionFactory
    at java.lang.Class.getDeclaredConstructors0(Native Method) ~[na:1.8.0_131]
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671) ~[na:1.8.0_131]
    at java.lang.Class.getConstructors(Class.java:1651) ~[na:1.8.0_131]
    at org.springframework.boot.BeanDefinitionLoader.isComponent(BeanDefinitionLoader.java:276) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.boot.BeanDefinitionLoader.load(BeanDefinitionLoader.java:158) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.boot.BeanDefinitionLoader.load(BeanDefinitionLoader.java:135) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.boot.BeanDefinitionLoader.load(BeanDefinitionLoader.java:127) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.boot.SpringApplication.load(SpringApplication.java:615) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:139) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.xd.dirt.plugins.spark.streaming.MessageBusConfiguration.createApplicationContext(MessageBusConfiguration.java:86) [spring-xd-dirt-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.xd.dirt.plugins.spark.streaming.MessageBusSender.start(MessageBusSender.java:105) [spring-xd-dirt-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.xd.spark.streaming.java.ModuleExecutor$1$1.call(ModuleExecutor.java:58) [spring-xd-spark-streaming-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.xd.spark.streaming.java.ModuleExecutor$1$1.call(ModuleExecutor.java:53) [spring-xd-spark-streaming-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.apache.spark.api.java.JavaRDDLike$$anonfun$foreachPartition$1.apply(JavaRDDLike.scala:206) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.api.java.JavaRDDLike$$anonfun$foreachPartition$1.apply(JavaRDDLike.scala:206) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.rdd.RDD$$anonfun$foreachPartition$1.apply(RDD.scala:806) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.rdd.RDD$$anonfun$foreachPartition$1.apply(RDD.scala:806) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1498) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1498) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:61) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.scheduler.Task.run(Task.scala:64) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:203) [spark-core_2.10-1.3.1.jar:1.3.1]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
Caused by: java.lang.ClassNotFoundException: org.springframework.amqp.rabbit.connection.ConnectionFactory
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_131]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_131]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_131]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_131]
    ... 26 common frames omitted
</code>```

So, what gives?  Does Spring XD not come with the necessary RabbitMQ dependencies?

I've even tried manually adding the spring-messaging jar into /opt/spring-xd/xd/lib which contains the dependency without success.  What's going on here?

Edit:  I'll throw in my servers.yml file for extra context.  Maybe someone can see where I may have done something wrong:

```<code>spring:
  profiles: container
xd:
  transport: rabbit
  messagebus:
    local:
      queueSize:                   2147483647
      polling:                     1000
      executor:
        corePoolSize:              0
        maxPoolSize:               200
        queueSize:                 2147483647
        keepAliveSeconds:          60
    rabbit:
      compressionLevel:            1
            # bus-level property, applies only when 'compress=true' for a stream module
            # See java.util.zip.Deflater; 1=BEST_SPEED, 9=BEST_COMPRESSION, ...
      longStringLimit:             8192
            # Headers longer than this will not be converted to String and will be a
            # DataInputStream - such headers will NOT be properly converted back on output.
      default:
        ackMode:                   AUTO
             # Valid: AUTO (container acks), NONE (broker acks), MANUAL (consumer acks).
             # Upper case only.
             # Note: MANUAL requires specialized code in the consuming module and is unlikely to be
             # used in an XD application. For more information, see
             # http://docs.spring.io/spring-integration/reference/html/amqp.html#amqp-inbound-ack
        autoBindDLQ:               false
        backOffInitialInterval:    1000
        backOffMaxInterval:        10000
        backOffMultiplier:         2.0
        batchBufferLimit:          10000
        batchingEnabled:           false
        batchSize:                 100
        batchTimeout:              5000
        compress:                  false
        concurrency:               1
        deliveryMode:              PERSISTENT
        durableSubscription:       false
        maxAttempts:               3
        maxConcurrency:            1
        prefix:                    xdbus.
             # prefix for queue/exchange names so policies (ha, dle etc.) can be applied
        prefetch:                  1
        replyHeaderPatterns:       STANDARD_REPLY_HEADERS,*
        republishToDLQ:            false
             # When false, normal rabbitmq dlq processing; when true, republish to the DLQ with stack trace
        requestHeaderPatterns:     STANDARD_REQUEST_HEADERS,*
        requeue:                   true
        transacted:                false
        txSize:                    1

#    redis:
#      headers:
            # comma-delimited list of additional header names to transport
#      default:
            # default bus properties, if not specified at the module level
#        backOffInitialInterval:    1000
#        backOffMaxInterval:        10000
#        backOffMultiplier:         2.0
#        concurrency:               1
#        maxAttempts:               3
    kafka:
      brokers:                                 kafka:9092
      zkAddress:                               zookeeper:2181
      mode:                                    embeddedHeaders
      offsetManagement:                        kafkaTopic
      headers:
             # comma-delimited list of additional header names to transport
      socketBufferSize:                        2097152
      offsetStoreTopic:                        SpringXdOffsets
      offsetStoreSegmentSize:                  25000000
      offsetStoreRetentionTime:                60000
      offsetStoreRequiredAcks:                 1
      offsetStoreMaxFetchSize:                 1048576
      offsetStoreBatchBytes:                   16384
      offsetStoreBatchTime:                    1000
      offsetUpdateTimeWindow:                  10000
      offsetUpdateCount:                       0
      offsetUpdateShutdownTimeout:             2000
      default:
        batchSize:                 16384
        batchTimeout:              0
        replicationFactor:         1
        concurrency:               1
        requiredAcks:              1
        compressionCodec:          none
        queueSize:                 8192 # must be a power of 2
        maxWait:                   100
        fetchSize:                 1048576
        minPartitionCount:         1
        durableSubscription:       false
        syncProducer:              false
        syncProducerTimeout:       5000
---
#Config for admin
spring:
  profiles: admin
xd:
  transport: rabbit
  messagebus:
    local:
      queueSize:                   2147483647
      polling:                     1000
      executor:
        corePoolSize:              0
        maxPoolSize:               200
        queueSize:                 2147483647
        keepAliveSeconds:          60
    rabbit:
      compressionLevel:            1
            # bus-level property, applies only when 'compress=true' for a stream module
            # See java.util.zip.Deflater; 1=BEST_SPEED, 9=BEST_COMPRESSION, ...
      longStringLimit:             8192
            # Headers longer than this will not be converted to String and will be a
            # DataInputStream - such headers will NOT be properly converted back on output.
      default:
        ackMode:                   AUTO
             # Valid: AUTO (container acks), NONE (broker acks), MANUAL (consumer acks).
             # Upper case only.
             # Note: MANUAL requires specialized code in the consuming module and is unlikely to be
             # used in an XD application. For more information, see
             # http://docs.spring.io/spring-integration/reference/html/amqp.html#amqp-inbound-ack
        autoBindDLQ:               false
        backOffInitialInterval:    1000
        backOffMaxInterval:        10000
        backOffMultiplier:         2.0
        batchBufferLimit:          10000
        batchingEnabled:           false
        batchSize:                 100
        batchTimeout:              5000
        compress:                  false
        concurrency:               1
        deliveryMode:              PERSISTENT
        durableSubscription:       false
        maxAttempts:               3
        maxConcurrency:            1
        prefix:                    xdbus.
             # prefix for queue/exchange names so policies (ha, dle etc.) can be applied
        prefetch:                  1
        replyHeaderPatterns:       STANDARD_REPLY_HEADERS,*
        republishToDLQ:            false
             # When false, normal rabbitmq dlq processing; when true, republish to the DLQ with stack trace
        requestHeaderPatterns:     STANDARD_REQUEST_HEADERS,*
        requeue:                   true
        transacted:                false
        txSize:                    1

#    redis:
#      headers:
            # comma-delimited list of additional header names to transport
#      default:
            # default bus properties, if not specified at the module level
#        backOffInitialInterval:    1000
#        backOffMaxInterval:        10000
#        backOffMultiplier:         2.0
#        concurrency:               1
#        maxAttempts:               3
    kafka:
      brokers:                                 kafka:9092
      zkAddress:                               zookeeper:2181
      mode:                                    embeddedHeaders
      offsetManagement:                        kafkaTopic
      headers:
             # comma-delimited list of additional header names to transport
      socketBufferSize:                        2097152
      offsetStoreTopic:                        SpringXdOffsets
      offsetStoreSegmentSize:                  25000000
      offsetStoreRetentionTime:                60000
      offsetStoreRequiredAcks:                 1
      offsetStoreMaxFetchSize:                 1048576
      offsetStoreBatchBytes:                   16384
      offsetStoreBatchTime:                    1000
      offsetUpdateTimeWindow:                  10000
      offsetUpdateCount:                       0
      offsetUpdateShutdownTimeout:             2000
      default:
        batchSize:                 16384
        batchTimeout:              0
        replicationFactor:         1
        concurrency:               1
        requiredAcks:              1
        compressionCodec:          none
        queueSize:                 8192 # must be a power of 2
        maxWait:                   100
        fetchSize:                 1048576
        minPartitionCount:         1
        durableSubscription:       false
        syncProducer:              false
        syncProducerTimeout:       5000

---
#  Rabbit MQ Properties
#
#  NOTE: sslProperties is mutually exclusive with keyStore, keyStorePassphrase, trustStore, trustStorePassphrase.
#  if you set inline properties, values in the properties file location given by 'sslProperties' will be ignored.
#
spring:
  rabbitmq:
   addresses: my-domain:5672
   adminAddresses: http://my-domain:15672
   nodes: rabbit@my-domain
   username: myusername
   password: mypassword
   virtual_host: /
   useSSL: false
   sslProperties:
   ssl:
     keyStore:
     keyStorePassphrase:
     trustStore:
     trustStorePassphrase:
</code>```

EDIT 2:  It looks like the xd-admin and xd-container scripts do not add the messagebus jars to the $CLASSPATH upon the start of AdminServerApplication or ContainerServerApplication.  I'm not sure if this is the culprit yet.

答:
The required jars are in the subfolder under xd/lib, based on the message bus you have selected...

```<code>../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit
../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit/amqp-client-3.6.0.jar
../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit/http-client-1.0.0.RELEASE.jar
../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit/spring-amqp-1.5.4.RELEASE.jar
../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit/spring-integration-amqp-4.2.5.RELEASE.jar
../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit/spring-rabbit-1.5.4.RELEASE.jar
../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit/spring-xd-messagebus-rabbit-1.3.1.RELEASE.jar
</code>```

The runtime adds that directory to the classpath while parsing the configuration.

Body:
I am in the process of switching from xd-singlenode mode to distributed, using version 1.3.1-RELEASE.

I am running Spring XD in a docker container, with a Dockerfile similar to the one here. According to the XD guide, if I want to use RabbitMQ as my data transport, then I need to configure a servers.yml file.  I have RabbitMQ running in a separate docker container, and I link these two containers together as part of a docker composition.

In short, I have configured everything (I believe correctly), but when I go to run multiple streams in Spring XD (which is when RabbitMQ would come into play, since it will act as a message transport between containers) Spring XD throws the following exception:

java.lang.NoClassDefFoundError: org/springframework/amqp/rabbit/connection/ConnectionFactory
    at java.lang.Class.getDeclaredConstructors0(Native Method) ~[na:1.8.0_131]
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671) ~[na:1.8.0_131]
    at java.lang.Class.getConstructors(Class.java:1651) ~[na:1.8.0_131]
    at org.springframework.boot.BeanDefinitionLoader.isComponent(BeanDefinitionLoader.java:276) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.boot.BeanDefinitionLoader.load(BeanDefinitionLoader.java:158) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.boot.BeanDefinitionLoader.load(BeanDefinitionLoader.java:135) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.boot.BeanDefinitionLoader.load(BeanDefinitionLoader.java:127) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.boot.SpringApplication.load(SpringApplication.java:615) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:139) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.xd.dirt.plugins.spark.streaming.MessageBusConfiguration.createApplicationContext(MessageBusConfiguration.java:86) [spring-xd-dirt-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.xd.dirt.plugins.spark.streaming.MessageBusSender.start(MessageBusSender.java:105) [spring-xd-dirt-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.xd.spark.streaming.java.ModuleExecutor$1$1.call(ModuleExecutor.java:58) [spring-xd-spark-streaming-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.xd.spark.streaming.java.ModuleExecutor$1$1.call(ModuleExecutor.java:53) [spring-xd-spark-streaming-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.apache.spark.api.java.JavaRDDLike$$anonfun$foreachPartition$1.apply(JavaRDDLike.scala:206) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.api.java.JavaRDDLike$$anonfun$foreachPartition$1.apply(JavaRDDLike.scala:206) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.rdd.RDD$$anonfun$foreachPartition$1.apply(RDD.scala:806) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.rdd.RDD$$anonfun$foreachPartition$1.apply(RDD.scala:806) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1498) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1498) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:61) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.scheduler.Task.run(Task.scala:64) [spark-core_2.10-1.3.1.jar:1.3.1]
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:203) [spark-core_2.10-1.3.1.jar:1.3.1]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
Caused by: java.lang.ClassNotFoundException: org.springframework.amqp.rabbit.connection.ConnectionFactory
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_131]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_131]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_131]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_131]
    ... 26 common frames omitted

So, what gives?  Does Spring XD not come with the necessary RabbitMQ dependencies?

I've even tried manually adding the spring-messaging jar into /opt/spring-xd/xd/lib which contains the dependency without success.  What's going on here?

Edit:  I'll throw in my servers.yml file for extra context.  Maybe someone can see where I may have done something wrong:

spring:
  profiles: container
xd:
  transport: rabbit
  messagebus:
    local:
      queueSize:                   2147483647
      polling:                     1000
      executor:
        corePoolSize:              0
        maxPoolSize:               200
        queueSize:                 2147483647
        keepAliveSeconds:          60
    rabbit:
      compressionLevel:            1
            # bus-level property, applies only when 'compress=true' for a stream module
            # See java.util.zip.Deflater; 1=BEST_SPEED, 9=BEST_COMPRESSION, ...
      longStringLimit:             8192
            # Headers longer than this will not be converted to String and will be a
            # DataInputStream - such headers will NOT be properly converted back on output.
      default:
        ackMode:                   AUTO
             # Valid: AUTO (container acks), NONE (broker acks), MANUAL (consumer acks).
             # Upper case only.
             # Note: MANUAL requires specialized code in the consuming module and is unlikely to be
             # used in an XD application. For more information, see
             # http://docs.spring.io/spring-integration/reference/html/amqp.html#amqp-inbound-ack
        autoBindDLQ:               false
        backOffInitialInterval:    1000
        backOffMaxInterval:        10000
        backOffMultiplier:         2.0
        batchBufferLimit:          10000
        batchingEnabled:           false
        batchSize:                 100
        batchTimeout:              5000
        compress:                  false
        concurrency:               1
        deliveryMode:              PERSISTENT
        durableSubscription:       false
        maxAttempts:               3
        maxConcurrency:            1
        prefix:                    xdbus.
             # prefix for queue/exchange names so policies (ha, dle etc.) can be applied
        prefetch:                  1
        replyHeaderPatterns:       STANDARD_REPLY_HEADERS,*
        republishToDLQ:            false
             # When false, normal rabbitmq dlq processing; when true, republish to the DLQ with stack trace
        requestHeaderPatterns:     STANDARD_REQUEST_HEADERS,*
        requeue:                   true
        transacted:                false
        txSize:                    1

#    redis:
#      headers:
            # comma-delimited list of additional header names to transport
#      default:
            # default bus properties, if not specified at the module level
#        backOffInitialInterval:    1000
#        backOffMaxInterval:        10000
#        backOffMultiplier:         2.0
#        concurrency:               1
#        maxAttempts:               3
    kafka:
      brokers:                                 kafka:9092
      zkAddress:                               zookeeper:2181
      mode:                                    embeddedHeaders
      offsetManagement:                        kafkaTopic
      headers:
             # comma-delimited list of additional header names to transport
      socketBufferSize:                        2097152
      offsetStoreTopic:                        SpringXdOffsets
      offsetStoreSegmentSize:                  25000000
      offsetStoreRetentionTime:                60000
      offsetStoreRequiredAcks:                 1
      offsetStoreMaxFetchSize:                 1048576
      offsetStoreBatchBytes:                   16384
      offsetStoreBatchTime:                    1000
      offsetUpdateTimeWindow:                  10000
      offsetUpdateCount:                       0
      offsetUpdateShutdownTimeout:             2000
      default:
        batchSize:                 16384
        batchTimeout:              0
        replicationFactor:         1
        concurrency:               1
        requiredAcks:              1
        compressionCodec:          none
        queueSize:                 8192 # must be a power of 2
        maxWait:                   100
        fetchSize:                 1048576
        minPartitionCount:         1
        durableSubscription:       false
        syncProducer:              false
        syncProducerTimeout:       5000
---
#Config for admin
spring:
  profiles: admin
xd:
  transport: rabbit
  messagebus:
    local:
      queueSize:                   2147483647
      polling:                     1000
      executor:
        corePoolSize:              0
        maxPoolSize:               200
        queueSize:                 2147483647
        keepAliveSeconds:          60
    rabbit:
      compressionLevel:            1
            # bus-level property, applies only when 'compress=true' for a stream module
            # See java.util.zip.Deflater; 1=BEST_SPEED, 9=BEST_COMPRESSION, ...
      longStringLimit:             8192
            # Headers longer than this will not be converted to String and will be a
            # DataInputStream - such headers will NOT be properly converted back on output.
      default:
        ackMode:                   AUTO
             # Valid: AUTO (container acks), NONE (broker acks), MANUAL (consumer acks).
             # Upper case only.
             # Note: MANUAL requires specialized code in the consuming module and is unlikely to be
             # used in an XD application. For more information, see
             # http://docs.spring.io/spring-integration/reference/html/amqp.html#amqp-inbound-ack
        autoBindDLQ:               false
        backOffInitialInterval:    1000
        backOffMaxInterval:        10000
        backOffMultiplier:         2.0
        batchBufferLimit:          10000
        batchingEnabled:           false
        batchSize:                 100
        batchTimeout:              5000
        compress:                  false
        concurrency:               1
        deliveryMode:              PERSISTENT
        durableSubscription:       false
        maxAttempts:               3
        maxConcurrency:            1
        prefix:                    xdbus.
             # prefix for queue/exchange names so policies (ha, dle etc.) can be applied
        prefetch:                  1
        replyHeaderPatterns:       STANDARD_REPLY_HEADERS,*
        republishToDLQ:            false
             # When false, normal rabbitmq dlq processing; when true, republish to the DLQ with stack trace
        requestHeaderPatterns:     STANDARD_REQUEST_HEADERS,*
        requeue:                   true
        transacted:                false
        txSize:                    1

#    redis:
#      headers:
            # comma-delimited list of additional header names to transport
#      default:
            # default bus properties, if not specified at the module level
#        backOffInitialInterval:    1000
#        backOffMaxInterval:        10000
#        backOffMultiplier:         2.0
#        concurrency:               1
#        maxAttempts:               3
    kafka:
      brokers:                                 kafka:9092
      zkAddress:                               zookeeper:2181
      mode:                                    embeddedHeaders
      offsetManagement:                        kafkaTopic
      headers:
             # comma-delimited list of additional header names to transport
      socketBufferSize:                        2097152
      offsetStoreTopic:                        SpringXdOffsets
      offsetStoreSegmentSize:                  25000000
      offsetStoreRetentionTime:                60000
      offsetStoreRequiredAcks:                 1
      offsetStoreMaxFetchSize:                 1048576
      offsetStoreBatchBytes:                   16384
      offsetStoreBatchTime:                    1000
      offsetUpdateTimeWindow:                  10000
      offsetUpdateCount:                       0
      offsetUpdateShutdownTimeout:             2000
      default:
        batchSize:                 16384
        batchTimeout:              0
        replicationFactor:         1
        concurrency:               1
        requiredAcks:              1
        compressionCodec:          none
        queueSize:                 8192 # must be a power of 2
        maxWait:                   100
        fetchSize:                 1048576
        minPartitionCount:         1
        durableSubscription:       false
        syncProducer:              false
        syncProducerTimeout:       5000

---
#  Rabbit MQ Properties
#
#  NOTE: sslProperties is mutually exclusive with keyStore, keyStorePassphrase, trustStore, trustStorePassphrase.
#  if you set inline properties, values in the properties file location given by 'sslProperties' will be ignored.
#
spring:
  rabbitmq:
   addresses: my-domain:5672
   adminAddresses: http://my-domain:15672
   nodes: rabbit@my-domain
   username: myusername
   password: mypassword
   virtual_host: /
   useSSL: false
   sslProperties:
   ssl:
     keyStore:
     keyStorePassphrase:
     trustStore:
     trustStorePassphrase:

EDIT 2:  It looks like the xd-admin and xd-container scripts do not add the messagebus jars to the $CLASSPATH upon the start of AdminServerApplication or ContainerServerApplication.  I'm not sure if this is the culprit yet.

Body:
The required jars are in the subfolder under xd/lib, based on the message bus you have selected...

../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit
../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit/amqp-client-3.6.0.jar
../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit/http-client-1.0.0.RELEASE.jar
../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit/spring-amqp-1.5.4.RELEASE.jar
../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit/spring-integration-amqp-4.2.5.RELEASE.jar
../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit/spring-rabbit-1.5.4.RELEASE.jar
../../Downloads/spring-xd-1.3.1.RELEASE/xd/lib/messagebus/rabbit/spring-xd-messagebus-rabbit-1.3.1.RELEASE.jar

The runtime adds that directory to the classpath while parsing the configuration.


问:
Paging for facets in Marklogic
I am getting the facets for a give search string using

```<code>search:search($q, $options)
</code>```

Where $q is the search text
and $options is

```<code><options xmlns="http://marklogic.com/appservices/search">
  <constraint name="kn_entry_number">
    <range type="xs:string" facet="true">
      <facet-option>frequency-order</facet-option>
      <facet-option>descending</facet-option>
      <facet-option>limit=5</facet-option>
      <facet-option>skip=3</facet-option>
      <field name="kn_entrynumber">
      </field>
    </range>
  </constraint>
  <return-results>false</return-results>
  <return-facets>true</return-facets>
</options>
</code>```

I want to get the top 5 after the top 3, so as to mimic the paging. But skip option does not seem to work here.

Is there any way of doing this using the search api, or my only option is to use cts queries

答:
If you want to page over the values in a range index, you could also take a look at search:values():

http://docs.marklogic.com/search:values

You would have to use search:search() to parse the query.

Alternatively, you could use cts:parse() -- which takes a somewhat different approach to parsing query text -- and cts:values() or cts:value-ranges()

Hoping that helps,

Title: Paging for facets in Marklogic

Body:
I am getting the facets for a give search string using

search:search($q, $options)

Where $q is the search text
and $options is

<options xmlns="http://marklogic.com/appservices/search">
  <constraint name="kn_entry_number">
    <range type="xs:string" facet="true">
      <facet-option>frequency-order</facet-option>
      <facet-option>descending</facet-option>
      <facet-option>limit=5</facet-option>
      <facet-option>skip=3</facet-option>
      <field name="kn_entrynumber">
      </field>
    </range>
  </constraint>
  <return-results>false</return-results>
  <return-facets>true</return-facets>
</options>

I want to get the top 5 after the top 3, so as to mimic the paging. But skip option does not seem to work here.

Is there any way of doing this using the search api, or my only option is to use cts queries


问:
truly unique random number generate by php?
I'm have build an up php script to host large number of images upload by user, what is the best way to generate random numbers to image filenames so that in future there would be no filename conflict? Be it like Imageshack. Thanks.</p>

答:
Guaranteed unique cannot be random.  Random cannot be guaranteed unique.  If you want unique (without the random) then just use the integers: 0, 1, 2, ... 1235, 1236, 1237, ...  Definitely unique, but not random.

If that doesn't suit, then you can have definitely unique with the appearance of random.  You use encryption on the integers to make them appear random.  Using DES will give you 32 bit numbers, while using AES will give you 64 bit numbers.  Use either to encrypt 0, 1, 2, ... in order with the same key.  All you need to store is the key and the next number to encrypt.  Because encryption is reversible, then the encrypted numbers are guaranteed unique.

If 64 bit or 32 bit numbers are too large (32 bits is 8 hex digits) then look at a format preserving encryption which will give you a smaller size range at some cost in time.

ContentLicense: CC BY-SA 2.5


问:
sql in oracle to find ratio with grouping by a column
Can anyone please help me to find the following by using a sql in oracle

```<code>Input in oracle TableX --

ColumnA |ColumnB
1      |20
1      |10
1      |30
2      |10
2      |30
3      |20

-- Desired result

ColumnA |ColumnB  |Ratio
1    |20    |0.333333333
1    |10    |0.166666667
1    |30    |0.5
2    |10    |0.25
2    |30    |0.75
3    |20    |1

SELECT
    ColumnA,
    ColumnB,
    ColumnA/sum(ColumnB) group ColumnA by as Ratio
FROM
    TableX
GROUP BY
    ColumnA
ORDER BY
    ColumnA
</code>```

I can't figure out how to calculate percentage within the GROUP BY

+++++++++

    Explanation:

    Trying to get the ratio by grouping ColumnA

    First row results is grouping 1 from ColumnA like 20/(20+10+30) = 0.333333333

    Grouping 2 from ColumnA 10/(10+30) = 0.25

    last row result grouping 3 from ColumnA is like 20/20 = 1

```<code>Hence the sum of 0.333333333+0.166666667+0.5 = 1
sum of 0.25  + 0.75  = 1
sum of 1+0 = 1
</code>```

答:
You can use the sum window function to do this.

```<code>SELECT
    ColumnA,
    ColumnB,
    ColumnB/(sum(ColumnB) over(partition by ColumnA)) as Ratio
FROM
    TableX
ORDER BY
    ColumnA
</code>```

Body:
Can anyone please help me to find the following by using a sql in oracle

Input in oracle TableX --

ColumnA |ColumnB
1      |20
1      |10
1      |30
2      |10
2      |30
3      |20

-- Desired result

ColumnA |ColumnB  |Ratio
1    |20    |0.333333333
1    |10    |0.166666667
1    |30    |0.5
2    |10    |0.25
2    |30    |0.75
3    |20    |1

SELECT
    ColumnA,
    ColumnB,
    ColumnA/sum(ColumnB) group ColumnA by as Ratio
FROM
    TableX
GROUP BY
    ColumnA
ORDER BY
    ColumnA

I can't figure out how to calculate percentage within the GROUP BY

+++++++++

    Explanation:

    Trying to get the ratio by grouping ColumnA

    First row results is grouping 1 from ColumnA like 20/(20+10+30) = 0.333333333

    Grouping 2 from ColumnA 10/(10+30) = 0.25

    last row result grouping 3 from ColumnA is like 20/20 = 1

Hence the sum of 0.333333333+0.166666667+0.5 = 1
sum of 0.25  + 0.75  = 1
sum of 1+0 = 1

Body:
You can use the sum window function to do this.

SELECT
    ColumnA,
    ColumnB,
    ColumnB/(sum(ColumnB) over(partition by ColumnA)) as Ratio
FROM
    TableX
ORDER BY
    ColumnA


问:
How can I get node.js to return data once all operations are complete
I am just learning server-side JavaScript so please bear with any glaring mistakes I've made.

I am trying to write a file parser that operates on HTML files in a directory and returns a JSON string once all files have been parsed. I started it with a single file and it works fine. it loads the resource from Apache running on the same machine, injects jquery, does the parsing and returns my JSON.

```<code>var request = require('request'),
    jsdom = require('jsdom'),
    sys = require('sys'),
    http = require('http');

http.createServer(function (req, res) {
    request({uri:'http://localhost/tfrohe/Car3E.html'}, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var window = jsdom.jsdom(body).createWindow();
            jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
              // jQuery is now loaded on the jsdom window created from 'body'
                var emps = {};
                jquery("tr td img").parent().parent().each(function(){
                    var step = 0;
                    jquery(this).children().each(function(index){
                        if (jquery(this).children('img').attr('src') !== undefined) {
                            step++;
                            var name = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                            var name_parts = name.split(",");
                            var last = name_parts[0];
                            var name_parts = name_parts[1].split(/\u00a0/g);
                            var first = name_parts[2];
                            emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                        }
                    });
                });
                emps = JSON.stringify(emps);
                //console.log(emps);
                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.end(emps);

            });
        } else {
            res.writeHead(200, {"Content-Type": "text/plain"});
            res.end("empty");
            //console.log(response.statusCode);
        }
    });
}).listen(8124);
</code>```

Now I am trying to extend this to using the regular file system (fs) and get all HTML files in the directory and parse them the same way and return a single combined JSON object once all files have been parsed. Here is what I have so far but it does not work.

```<code>var sys = require("sys"),
    fs = require("fs"),
    jsdom = require("jsdom"),
    emps = {};
    //path = '/home/inet/www/media/employees/';

readDirectory = function(path) {
    fs.readdir(path, function(err, files) {
        var htmlfiles = [];
        files.forEach(function(name) {
            if(name.substr(-4) === "html") {
                htmlfiles.push(name);
            }
        });
        var count = htmlfiles.length;
        htmlfiles.forEach(function(filename) {
            fs.readFile(path + filename, "binary", function(err, data) {
                if(err) throw err;
                window = jsdom.jsdom(data).createWindow();
                jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
                    jquery("tr td img").parent().parent().each(function(){
                        var step = 0;
                        jquery(this).children().each(function(index){
                            if (jquery(this).children('img').attr('src') !== undefined) {
                                step++;
                                var empname = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                                var name_parts = empname.split(",");
                                var last = name_parts[0];
                                var name_parts = name_parts[1].split(/\u00a0/g);
                                var first = name_parts[2]
                                emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                            }
                        });
                    });
                });
            });
        });
    });
}

readDirectory('/home/inet/www/media/employees/', function() {
    console.log(emps);
});
</code>```

In this particular case, there are 2 html files in the directory. If i console.log(emps) during the htmlfiles.forEach() it shows me the results from the first file then the results for both files together the way I expect. how do I get emps to be returned to readDirectory so i can output it as desired?

Completed Script

After the answers below, here is the completed script with a httpServer to serve up the detail.

```<code>var sys = require('sys'),
    fs = require("fs"),
    http = require('http'),
    jsdom = require('jsdom'),
    emps = {};

    var timed = setInterval(function() {
        emps = {};
        readDirectory('/home/inet/www/media/employees/', function(emps) {
        });
    }, 3600000);

readDirectory = function(path, callback) {
    fs.readdir(path, function(err, files) {
        var htmlfiles = [];
        files.forEach(function(name) {
            if(name.substr(-4) === "html") {
                htmlfiles.push(name);
            }
        });
        var count = htmlfiles.length;
        htmlfiles.forEach(function(filename) {
            fs.readFile(path + filename, "binary", function(err, data) {
                if(err) throw err;
                window = jsdom.jsdom(data).createWindow();
                jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
                    var imagecount = jquery("tr td img").length;
                    jquery("tr td img").parent().parent().each(function(){
                        var step = 0;
                        jquery(this).children().each(function(index){
                            if (jquery(this).children('img').attr('src') !== undefined) {
                                step += 1;
                                var empname = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                                var name_parts = empname.split(",");
                                var last = name_parts[0];
                                var name_parts = name_parts[1].split(/\u00a0/g);
                                var first = name_parts[2]
                                emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                            }
                        });
                    });
                    count -= 1;
                    if (count <= 0) {
                        callback(JSON.stringify(emps));
                    }
                });
            });

        });
    });
}

var init = readDirectory('/home/inet/www/media/employees/', function(emps) {

        });

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(emps));
}).listen(8124);
</code>```

答:
You seem to be doing this a tad wrong

```<code>readDirectory('/home/inet/www/media/employees/', function() {
    console.log(emps);
});
</code>```

But you've defined your function as:

```<code>readDirectory = function(path) {
</code>```

Where is the callback argument? Try this:

```<code>readDirectory = function(path, callback) {
</code>```

then under emps[last + ",_" + first] = jquery(this).children('img').attr('src'); put

```<code>callback.call(null, emps);
</code>```

Your callback function will be called however many times your loop goes on for. If you want it to return all of them at once, you'll need to get a count of how many times the loop is going to run for, count up until that number then call your callback when the emps array is full of the data you need.

Body:
I am just learning server-side JavaScript so please bear with any glaring mistakes I've made.

I am trying to write a file parser that operates on HTML files in a directory and returns a JSON string once all files have been parsed. I started it with a single file and it works fine. it loads the resource from Apache running on the same machine, injects jquery, does the parsing and returns my JSON.

var request = require('request'),
    jsdom = require('jsdom'),
    sys = require('sys'),
    http = require('http');

http.createServer(function (req, res) {
    request({uri:'http://localhost/tfrohe/Car3E.html'}, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var window = jsdom.jsdom(body).createWindow();
            jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
              // jQuery is now loaded on the jsdom window created from 'body'
                var emps = {};
                jquery("tr td img").parent().parent().each(function(){
                    var step = 0;
                    jquery(this).children().each(function(index){
                        if (jquery(this).children('img').attr('src') !== undefined) {
                            step++;
                            var name = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                            var name_parts = name.split(",");
                            var last = name_parts[0];
                            var name_parts = name_parts[1].split(/\u00a0/g);
                            var first = name_parts[2];
                            emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                        }
                    });
                });
                emps = JSON.stringify(emps);
                //console.log(emps);
                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.end(emps);

            });
        } else {
            res.writeHead(200, {"Content-Type": "text/plain"});
            res.end("empty");
            //console.log(response.statusCode);
        }
    });
}).listen(8124);

Now I am trying to extend this to using the regular file system (fs) and get all HTML files in the directory and parse them the same way and return a single combined JSON object once all files have been parsed. Here is what I have so far but it does not work.

var sys = require("sys"),
    fs = require("fs"),
    jsdom = require("jsdom"),
    emps = {};
    //path = '/home/inet/www/media/employees/';

readDirectory = function(path) {
    fs.readdir(path, function(err, files) {
        var htmlfiles = [];
        files.forEach(function(name) {
            if(name.substr(-4) === "html") {
                htmlfiles.push(name);
            }
        });
        var count = htmlfiles.length;
        htmlfiles.forEach(function(filename) {
            fs.readFile(path + filename, "binary", function(err, data) {
                if(err) throw err;
                window = jsdom.jsdom(data).createWindow();
                jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
                    jquery("tr td img").parent().parent().each(function(){
                        var step = 0;
                        jquery(this).children().each(function(index){
                            if (jquery(this).children('img').attr('src') !== undefined) {
                                step++;
                                var empname = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                                var name_parts = empname.split(",");
                                var last = name_parts[0];
                                var name_parts = name_parts[1].split(/\u00a0/g);
                                var first = name_parts[2]
                                emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                            }
                        });
                    });
                });
            });
        });
    });
}

readDirectory('/home/inet/www/media/employees/', function() {
    console.log(emps);
});

In this particular case, there are 2 html files in the directory. If i console.log(emps) during the htmlfiles.forEach() it shows me the results from the first file then the results for both files together the way I expect. how do I get emps to be returned to readDirectory so i can output it as desired?

Completed Script

After the answers below, here is the completed script with a httpServer to serve up the detail.

var sys = require('sys'),
    fs = require("fs"),
    http = require('http'),
    jsdom = require('jsdom'),
    emps = {};

    var timed = setInterval(function() {
        emps = {};
        readDirectory('/home/inet/www/media/employees/', function(emps) {
        });
    }, 3600000);

readDirectory = function(path, callback) {
    fs.readdir(path, function(err, files) {
        var htmlfiles = [];
        files.forEach(function(name) {
            if(name.substr(-4) === "html") {
                htmlfiles.push(name);
            }
        });
        var count = htmlfiles.length;
        htmlfiles.forEach(function(filename) {
            fs.readFile(path + filename, "binary", function(err, data) {
                if(err) throw err;
                window = jsdom.jsdom(data).createWindow();
                jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
                    var imagecount = jquery("tr td img").length;
                    jquery("tr td img").parent().parent().each(function(){
                        var step = 0;
                        jquery(this).children().each(function(index){
                            if (jquery(this).children('img').attr('src') !== undefined) {
                                step += 1;
                                var empname = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                                var name_parts = empname.split(",");
                                var last = name_parts[0];
                                var name_parts = name_parts[1].split(/\u00a0/g);
                                var first = name_parts[2]
                                emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                            }
                        });
                    });
                    count -= 1;
                    if (count <= 0) {
                        callback(JSON.stringify(emps));
                    }
                });
            });

        });
    });
}

var init = readDirectory('/home/inet/www/media/employees/', function(emps) {

        });

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(emps));
}).listen(8124);

Body:
You seem to be doing this a tad wrong

readDirectory('/home/inet/www/media/employees/', function() {
    console.log(emps);
});

But you've defined your function as:

readDirectory = function(path) {

Where is the callback argument? Try this:

readDirectory = function(path, callback) {

then under emps[last + ",_" + first] = jquery(this).children('img').attr('src'); put

callback.call(null, emps);

Your callback function will be called however many times your loop goes on for. If you want it to return all of them at once, you'll need to get a count of how many times the loop is going to run for, count up until that number then call your callback when the emps array is full of the data you need.


问:
Unable to populate data in Views after switching fragments
As above - I can't populate data into Views (e.g. ImageView, TextView) when I switch fragments.

onCreateView - I execute AsyncTask to send request to server.
I use interface to know when AsyncTask end its job.
Once its done, I'm populating data into views.
It's work perfectly, but not when I switch the fragments.

I know there isn't problem with retrieving data, the only problem is with populate it into views.

答:
Since you don't have your code here am giving you an working example from one my my apps that sue fragments:-

```<code>public class FragmentA extends Fragment {
    private View mRoot;
    ....
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mRoot = inflater.inflate(R.layout.fragment_layout, container, false);
        updateUI();
        return mRoot;
    }

    private void updateUI() {
       TextView1 = (TextView) mRoot.findViewById(R.id.id1);
       TextView2 = (TextView) mRoot.findViewById(R.id.id2);
       ....
       ....
    }
}
</code>```

UPDATE

Now that I see your code try changing the individual views by rootView

```<code>final ConstraintLayout treeline_Tier = (ConstraintLayout) treelineView.findViewById(R.id.treeline);
</code>```

treelineView --> rootView

Body:
Since you don't have your code here am giving you an working example from one my my apps that sue fragments:-

public class FragmentA extends Fragment {
    private View mRoot;
    ....
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mRoot = inflater.inflate(R.layout.fragment_layout, container, false);
        updateUI();
        return mRoot;
    }

    private void updateUI() {
       TextView1 = (TextView) mRoot.findViewById(R.id.id1);
       TextView2 = (TextView) mRoot.findViewById(R.id.id2);
       ....
       ....
    }
}

UPDATE

Now that I see your code try changing the individual views by rootView

final ConstraintLayout treeline_Tier = (ConstraintLayout) treelineView.findViewById(R.id.treeline);

treelineView --> rootView


问:
Bash Script - Check mounted devices
What I'm trying to do -
In the end, I want a script that checks for 3 devices, an SD card, Backup1 & Backup2. They've all been set to auto-mount at their respective mountpoints. The script should check for SD card first, if this fails, then a warning should be sent, and nothing more. If SD is okay, but only one backup is mounted, then ask for confirmation to go ahead with rsync to mounted backup. If all devices are mounted, then rsync from SD card to both backups.

Currently I'm just trying to get the device check nailed, using echo commands. Here's what I have (after multiple attempts) -

```<code>if ! mount | grep /media/card >/dev/null
then
    echo "ERROR: SD card not mounted, aborting"
else
    if ! mount | grep /media/backup >/dev/null
        then
            if ! mount | grep /media/backup2 >/dev/null
            then
                echo "ERROR: No backup devices"
            else
                echo "CAUTION: Backup_2 missing, Backup_1 OKAY"
            fi
    else
        if ! mount | grep /media/backup2 /dev/null
        then
            echo "CAUTION: Backup_1 missing, Backup_2 OKAY"
        else
            echo "SUCCESS: All devices OKAY"
        fi
    fi
fi
</code>```

Which isn't working. I'm getting confused by all the nested 'if's and surely there's a simpler way? Perhaps something that checks each device independently, then returns values that equate to the various combinations (0=no devices, 1=sd only, 2=sd & backup1, 3=sd & backup 2, 4 = all okay) which then is read and decides next part of script to run? If not, where has this way gone wrong?

Any help is appreciated

答:
Solved! Part of the problem was using mount | grep /media/backup > /dev/null as there's an issue with similar names, so /media/backup2 being mounted meant it was counting both devices as mounted.

Using grep -q /media/backup2\ /proc/mounts works in a similar way, or at least produces the same outcome, just without the naming issue.

I've also changed the way the if statements work, it now checks for SD card, if that fails, then it aborts. It then checks for which devices are mounted with a fairly simple flow.

Here's the code:

GNU nano 2.2.6                                          File: backupSD2.sh                                                                                Modified

```<code>#!/bin/bash

#Check for SD

if ! grep -q /media/card\  /proc/mounts
then
    echo "ERROR: NO SD CARD"
    exit 0
else
    echo "SD OKAY..."
fi

#Check for Backup Devices

if (( grep -q /media/backup\  /proc/mounts ) && ( grep -q /media/backup2\  /proc/mounts ))
then
    echo "Both Backups mounted"

elif grep -q /media/backup\  /proc/mounts
then
    echo "CAUTION: Backup_2 missing, Backup_1 OKAY"

elif grep -q /media/backup2\  /proc/mounts
then
    echo "CAUTION: Backup_1 missing, Backup_2 OKAY"
else
    echo "ERROR: NO BACKUP DEVICES"
    exit 0
fi
</code>```

After the 'echo' commands is where I'll be putting the rsync commands.
The final exit 0 is probably unnecessary, but I don't think it's doing any harm and reassures that it's not going to try any more commands.

Title: Bash Script - Check mounted devices

Body:
What I'm trying to do -
In the end, I want a script that checks for 3 devices, an SD card, Backup1 & Backup2. They've all been set to auto-mount at their respective mountpoints. The script should check for SD card first, if this fails, then a warning should be sent, and nothing more. If SD is okay, but only one backup is mounted, then ask for confirmation to go ahead with rsync to mounted backup. If all devices are mounted, then rsync from SD card to both backups.

Currently I'm just trying to get the device check nailed, using echo commands. Here's what I have (after multiple attempts) -

if ! mount | grep /media/card >/dev/null
then
    echo "ERROR: SD card not mounted, aborting"
else
    if ! mount | grep /media/backup >/dev/null
        then
            if ! mount | grep /media/backup2 >/dev/null
            then
                echo "ERROR: No backup devices"
            else
                echo "CAUTION: Backup_2 missing, Backup_1 OKAY"
            fi
    else
        if ! mount | grep /media/backup2 /dev/null
        then
            echo "CAUTION: Backup_1 missing, Backup_2 OKAY"
        else
            echo "SUCCESS: All devices OKAY"
        fi
    fi
fi

Which isn't working. I'm getting confused by all the nested 'if's and surely there's a simpler way? Perhaps something that checks each device independently, then returns values that equate to the various combinations (0=no devices, 1=sd only, 2=sd & backup1, 3=sd & backup 2, 4 = all okay) which then is read and decides next part of script to run? If not, where has this way gone wrong?

Any help is appreciated

Body:
Solved! Part of the problem was using mount | grep /media/backup > /dev/null as there's an issue with similar names, so /media/backup2 being mounted meant it was counting both devices as mounted.

Using grep -q /media/backup2\ /proc/mounts works in a similar way, or at least produces the same outcome, just without the naming issue.

I've also changed the way the if statements work, it now checks for SD card, if that fails, then it aborts. It then checks for which devices are mounted with a fairly simple flow.

Here's the code:

GNU nano 2.2.6                                          File: backupSD2.sh                                                                                Modified

#!/bin/bash

#Check for SD

if ! grep -q /media/card\  /proc/mounts
then
    echo "ERROR: NO SD CARD"
    exit 0
else
    echo "SD OKAY..."
fi

#Check for Backup Devices

if (( grep -q /media/backup\  /proc/mounts ) && ( grep -q /media/backup2\  /proc/mounts ))
then
    echo "Both Backups mounted"

elif grep -q /media/backup\  /proc/mounts
then
    echo "CAUTION: Backup_2 missing, Backup_1 OKAY"

elif grep -q /media/backup2\  /proc/mounts
then
    echo "CAUTION: Backup_1 missing, Backup_2 OKAY"
else
    echo "ERROR: NO BACKUP DEVICES"
    exit 0
fi

After the 'echo' commands is where I'll be putting the rsync commands.
The final exit 0 is probably unnecessary, but I don't think it's doing any harm and reassures that it's not going to try any more commands.