问:
How could I define what function is more efficient for comparing arrays with custom models
I wrote two functions to compare arrays. Now I am struggling how to compare these approaches and find out what is the most suitable.

I would like to know how could I evaluate each function that I wrote.

By equal I understand that all elements of arrays are same.

By evaluate I am asking performance (Time and Complexity) and usage of Swift features.

My structure that is used in arrays:

```<code>struct Wallet {
    var fund = 0
    var name = ""

    public static func ==(lhs: Wallet, rhs: Wallet) -> Bool{
        return lhs.fund == rhs.fund && lhs.name == rhs.name
    }

    public static func !=(lhs: Wallet, rhs: Wallet) -> Bool{
        return lhs.fund != rhs.fund || lhs.name != rhs.name
    }
}
</code>```

First approach with usage of the zip:

```<code>func compare(x: Array<Wallet>, y: Array<Wallet>) -> Bool {
    let state = zip(x, y).enumerated().filter() {
        $1.0 == $1.1
        }.count == x.count
    return state
}
</code>```

Second approach when I sort array and than compare.

```<code>func compare(x: Array<Wallet>, y: Array<Wallet>) -> Bool {

    if x.count != y.count {
        return false
    }

    let xSorted = x.sorted{$0.fund > $1.fund}
    let ySorted = y.sorted{$0.fund > $1.fund}

    for (pos, xItem) in xSorted.enumerated() {
        let yItem = ySorted[pos]
        if xItem != yItem {
            return false
        }
    }

    return true
}
</code>```

答:
Both solutions are not optimal:

Calling enumerated() is unnecessary because the index position is
not used in the closure.

Both solutions do not short-circuit: They compare all array elements
even if a different pair is found.

contains() does short-circuit, so this would be a better solution:

```<code>func compare(x: Array<Wallet>, y: Array<Wallet>) -> Bool {
    return x.count == y.count &&
        !zip(x, y).contains { $0 != $1 }
}
</code>```

Alternatively:

```<code>func compare(x: Array<Wallet>, y: Array<Wallet>) -> Bool {
    return x.elementsEqual(y, by: ==)
}
</code>```

But you get that for free if you make the type Equatable (note
that you don't have to implement !=, that is provided automatically:

```<code>struct Wallet: Equatable {
    var fund = 0
    var name = ""

    public static func ==(lhs: Wallet, rhs: Wallet) -> Bool{
        return lhs.fund == rhs.fund && lhs.name == rhs.name
    }
}
</code>```

Now you can compare arrays simply with ==, using the existing

```<code>func ==<Element>(lhs: Array<Element>, rhs: Array<Element>) -> Bool
 where Element : Equatable
</code>```

operator.

Body:
I wrote two functions to compare arrays. Now I am struggling how to compare these approaches and find out what is the most suitable.

I would like to know how could I evaluate each function that I wrote.

By equal I understand that all elements of arrays are same.

By evaluate I am asking performance (Time and Complexity) and usage of Swift features.

My structure that is used in arrays:

struct Wallet {
    var fund = 0
    var name = ""

    public static func ==(lhs: Wallet, rhs: Wallet) -> Bool{
        return lhs.fund == rhs.fund && lhs.name == rhs.name
    }

    public static func !=(lhs: Wallet, rhs: Wallet) -> Bool{
        return lhs.fund != rhs.fund || lhs.name != rhs.name
    }
}

First approach with usage of the zip:

func compare(x: Array<Wallet>, y: Array<Wallet>) -> Bool {
    let state = zip(x, y).enumerated().filter() {
        $1.0 == $1.1
        }.count == x.count
    return state
}

Second approach when I sort array and than compare.

func compare(x: Array<Wallet>, y: Array<Wallet>) -> Bool {

    if x.count != y.count {
        return false
    }

    let xSorted = x.sorted{$0.fund > $1.fund}
    let ySorted = y.sorted{$0.fund > $1.fund}

    for (pos, xItem) in xSorted.enumerated() {
        let yItem = ySorted[pos]
        if xItem != yItem {
            return false
        }
    }

    return true
}

Body:
Both solutions are not optimal:

Calling enumerated() is unnecessary because the index position is
not used in the closure.

Both solutions do not short-circuit: They compare all array elements
even if a different pair is found.

contains() does short-circuit, so this would be a better solution:

func compare(x: Array<Wallet>, y: Array<Wallet>) -> Bool {
    return x.count == y.count &&
        !zip(x, y).contains { $0 != $1 }
}

Alternatively:

func compare(x: Array<Wallet>, y: Array<Wallet>) -> Bool {
    return x.elementsEqual(y, by: ==)
}

But you get that for free if you make the type Equatable (note
that you don't have to implement !=, that is provided automatically:

struct Wallet: Equatable {
    var fund = 0
    var name = ""

    public static func ==(lhs: Wallet, rhs: Wallet) -> Bool{
        return lhs.fund == rhs.fund && lhs.name == rhs.name
    }
}

Now you can compare arrays simply with ==, using the existing

func ==<Element>(lhs: Array<Element>, rhs: Array<Element>) -> Bool
 where Element : Equatable

operator.


来源: stackexchange

问:
How to pull a new submodule
Tried looking for answers on this site and others:
StackOverflow - Easy way pull latest of all submodules

They all seem to want to talk about if you are controlling them, not if someone else added one, and I just want to pull the additional one into my project without having to stash or backup my changes if I need to delete the folder.

Should I delete the .gitmodules file, and/or the submodule directories that I have already pulled down with git clone --recursive?
(StackOverflow - How to git clone including submodules?)

These commands do not seem to help either:

git submodule update --init --recursive seems like it did nothing.

git submodule update --recursive nothing.

git fetch --recurse-submodules output Fetching submodule ... several times.

git pull --recurse-submodules output the same thing, and then said Already up-to-date. after the fetch trial.  Strange since in either case my submodules were already downloaded.

git clone --recursive ... Not tried yet.  I feel like would overwrite any changes I have made, in the Stash or otherwise.

git submodule update --recursive --remote checked out a new commit SHA for one of the submodules.

git submodule update --recursive checked out a new commit SHA for one of the submodules.  Could be the older, original commit level.

git submodule status gives the appropriate SHA, version, and name information for each, while still lacking the one that I want.

git submodule foreach git pull origin master

git submodule update does nothing.

I have been double-checking the library directory manually each time to make sure whether the additional submodule appeared or not.

I want to avoid performing certain actions, unless they are not destructive to my current repository state containing code changes, and solves my problem, in case it is a command I have mentioned but did not run, or anyone else has another to try.

I could try some of these with more effort, but I think I want to stop messing with them for now, and since I have not found the answer to this issue after doing some online searching, maybe the hopeful and eventual answer would help others anyway.

Am I suffering from the con mentioned here at all?
Software Engineering - Git submodule vs Git clone

More links:

StackOverflow - Update Git submodule to latest commit on origin

答:
When you want to pull a specific new module, you can use the following command:

```<code>git submodule update --init local/path/to/submodule/folder
</code>```

If you wish to initialize all new submodules however. you can omit the path to the folder like so:

```<code>git submodule update --init
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to pull a new submodule

Body:
When you want to pull a specific new module, you can use the following command:

git submodule update --init local/path/to/submodule/folder

If you wish to initialize all new submodules however. you can omit the path to the folder like so:

git submodule update --init

ContentLicense: CC BY-SA 4.0


问:
UIView: How do i make the width automatically end before another image?
Right so i have this image:

And i need the width of the red bar to fit between the 2 images (Buttons) on all devices.

I have looked for answers but i haven't found anything that works yet.

This is the code I'm using:

```<code>_background = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 353, 20)];
    [self addSubview:_background];
    [self sendSubviewToBack:_background];
    [_background setBackgroundColor:[UIColor redColor]];
    _background.layer.cornerRadius = 10;
    _background.clipsToBounds = YES;
    _background.center = CGPointMake(200, 15);
    _background.keepLeftOffsetTo(_sendButton);
    _background.keepCenterAlignTo(self);
    [_background updateConstraintsIfNeeded];
</code>```

There may very well be an easy fix for this but I've only been on Objective-C for about a month! (Coming from Android Java).

Any help would be great right now

Thanks

Update #1: I've tried using Masonry as suggested but i still can't achieve what i need.

答:
So to help i setup a quick storyboard and replicated what i needed, then i looked at the constraints from the storyboard and then replicated it programmatically. Like so:

```<code>[background mas_remakeConstraints:^(MASConstraintMaker * make) {
    make.trailingMargin.equalTo(_sendButton);
    make.rightMargin.equalTo(@30);
    make.leading.equalTo(_optionsButton);
    make.leading.leadingMargin.equalTo(@25);
    make.height.equalTo(@20);
    make.center.equalTo(self);
        }];
</code>```

As you can tell, i did end up using Masonry to do this.

Body:
Right so i have this image:

And i need the width of the red bar to fit between the 2 images (Buttons) on all devices.

I have looked for answers but i haven't found anything that works yet.

This is the code I'm using:

_background = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 353, 20)];
    [self addSubview:_background];
    [self sendSubviewToBack:_background];
    [_background setBackgroundColor:[UIColor redColor]];
    _background.layer.cornerRadius = 10;
    _background.clipsToBounds = YES;
    _background.center = CGPointMake(200, 15);
    _background.keepLeftOffsetTo(_sendButton);
    _background.keepCenterAlignTo(self);
    [_background updateConstraintsIfNeeded];

There may very well be an easy fix for this but I've only been on Objective-C for about a month! (Coming from Android Java).

Any help would be great right now

Thanks

Update #1: I've tried using Masonry as suggested but i still can't achieve what i need.

Body:
So to help i setup a quick storyboard and replicated what i needed, then i looked at the constraints from the storyboard and then replicated it programmatically. Like so:

[background mas_remakeConstraints:^(MASConstraintMaker * make) {
    make.trailingMargin.equalTo(_sendButton);
    make.rightMargin.equalTo(@30);
    make.leading.equalTo(_optionsButton);
    make.leading.leadingMargin.equalTo(@25);
    make.height.equalTo(@20);
    make.center.equalTo(self);
        }];

As you can tell, i did end up using Masonry to do this.


问:
How can I move the contents of one directory tree into another?
I have a directory which contains files and a number of levels of subdirectories:

```<code>C:\Source
</code>```

I would like to move the contents of C:\Source into:

```<code>C:\Destination
</code>```

Requirements:

All files and all subdirectories
within C:\SourceData must be moved

I will be running the command in a
batch file

I can't use Powershell or
any other scripting languages

Attempt 0

```<code>XCOPY /E "C:\Source" "C:\Destination"
</code>```

This works perfectly, but it copies instead of moves. I can't copy then delete the source as I'm moving a very large set of files and there isn't enough disk space to have two copies of them at a time.

Attempt 1

```<code>MOVE "C:\Source" "C:\Destination"
</code>```

This moves the entire C:\Source directory into C:\Destination so I end up with:

```<code>C:\Destination\Source
</code>```

Attempt 2

With some help from this question and accepted answer I came up with:

```<code>for /r "C:\Source" %%x in (*) do move "%%x" "C:\Destination"
</code>```

This moves the files within C:\Source but not the subdirectories or their contents. Note that I used %%x instead of %x as I'm using it in a batch file.

Using FOR seems promising but I'm not sure I've used the right syntax? Have I missed something?

Attempt 3

As suggested by Nick D, I tried rename:

RENAME "C:\Source" Destination

For the example scenario I gave this works fine. Unfortunately my real Destination directory is at a different level to the Source directory and this doesn't seem to be supported:

```<code>C:\>REN /?
Renames a file or files.

RENAME [drive:][path]filename1 filename2.
REN [drive:][path]filename1 filename2.

Note that you cannot specify a new drive or path for your destination file.
</code>```

I get "The syntax of the command is incorrect." errors if I try to specify a more complex destination path, for example:

```<code>RENAME "C:\Source" "C:\MyOtherDirectory\Destination"
RENAME "C:\Source" "MyOtherDirectory\Destination"
</code>```

答:
In response to ufukgun's answer:

```<code>xcopy C:\Source\* C:\Destination\* /s /e /i /Y
</code>```

/s - Copies directories and subdirectories except empty ones.

/e - Copies directories and subdirectories, including empty ones. Same as /S /E. May be used to modify /T.

/i - If destination does not exist and copying more than one file, assumes that destination must be a directory.

/y - Suppresses prompting to confirm you want to overwrite an existing destination file.

As stated in another answer, using xcopy may be not as efficient as it would be a native move command that only changes pointers in the filesystem.

ContentLicense: CC BY-SA 2.5

Body:
I have a directory which contains files and a number of levels of subdirectories:

C:\Source

I would like to move the contents of C:\Source into:

C:\Destination

Requirements:

All files and all subdirectories
within C:\SourceData must be moved

I will be running the command in a
batch file

I can't use Powershell or
any other scripting languages

Attempt 0

XCOPY /E "C:\Source" "C:\Destination"

This works perfectly, but it copies instead of moves. I can't copy then delete the source as I'm moving a very large set of files and there isn't enough disk space to have two copies of them at a time.

Attempt 1

MOVE "C:\Source" "C:\Destination"

This moves the entire C:\Source directory into C:\Destination so I end up with:

C:\Destination\Source

Attempt 2

With some help from this question and accepted answer I came up with:

for /r "C:\Source" %%x in (*) do move "%%x" "C:\Destination"

This moves the files within C:\Source but not the subdirectories or their contents. Note that I used %%x instead of %x as I'm using it in a batch file.

Using FOR seems promising but I'm not sure I've used the right syntax? Have I missed something?

Attempt 3

As suggested by Nick D, I tried rename:

RENAME "C:\Source" Destination

For the example scenario I gave this works fine. Unfortunately my real Destination directory is at a different level to the Source directory and this doesn't seem to be supported:

C:\>REN /?
Renames a file or files.

RENAME [drive:][path]filename1 filename2.
REN [drive:][path]filename1 filename2.

Note that you cannot specify a new drive or path for your destination file.

I get "The syntax of the command is incorrect." errors if I try to specify a more complex destination path, for example:

RENAME "C:\Source" "C:\MyOtherDirectory\Destination"
RENAME "C:\Source" "MyOtherDirectory\Destination"

Body:
In response to ufukgun's answer:

xcopy C:\Source\* C:\Destination\* /s /e /i /Y

/s - Copies directories and subdirectories except empty ones.

/e - Copies directories and subdirectories, including empty ones. Same as /S /E. May be used to modify /T.

/i - If destination does not exist and copying more than one file, assumes that destination must be a directory.

/y - Suppresses prompting to confirm you want to overwrite an existing destination file.

As stated in another answer, using xcopy may be not as efficient as it would be a native move command that only changes pointers in the filesystem.


问:
ARG substitution in RUN command not working for Dockerfile
In my Dockerfile I have the following:

```<code>ARG a-version
RUN wget -q -O /tmp/alle.tar.gz http://someserver/server/$a-version/a-server-$a-version.tar.gz && \
    mkdir /opt/apps/$a-version
</code>```

However when building this with:

```<code>--build-arg http_proxy=http://myproxy","--build-arg a-version=a","--build-arg b-version=b"
</code>```

Step 10/15 : RUN wget... is shown with $a-version in the path instead of the substituted value and the build fails.

I have followed the instructions shown here but must be missing something else.

My questions is, what could be causing this issue and how can i solve
  it?

答:
Don't use - in variable names.

Docker build will always show you the line as is written down in the Dockerfile, despite the variable value.

So use this variable name a_version:

```<code>ARG a_version
</code>```

See this example:

Dockerfile:

```<code>FROM alpine

ARG a_version
RUN echo $a_version
</code>```

Build:

```<code>$ docker build . --build-arg a_version=1234
Sending build context to Docker daemon 2.048 kB
Step 1/3 : FROM alpine
 ---> a41a7446062d
Step 2/3 : ARG a_version
 ---> Running in c55e98cab494
 ---> 53dedab7de75
Removing intermediate container c55e98cab494
Step 3/3 : RUN echo $a_version                <<< note this <<
 ---> Running in 56b8aeddf77b
1234                                          <<<< and this <<
 ---> 89badadc1ccf
Removing intermediate container 56b8aeddf77b
Successfully built 89badadc1ccf
</code>```

Body:
In my Dockerfile I have the following:

ARG a-version
RUN wget -q -O /tmp/alle.tar.gz http://someserver/server/$a-version/a-server-$a-version.tar.gz && \
    mkdir /opt/apps/$a-version

However when building this with:

--build-arg http_proxy=http://myproxy","--build-arg a-version=a","--build-arg b-version=b"

Step 10/15 : RUN wget... is shown with $a-version in the path instead of the substituted value and the build fails.

I have followed the instructions shown here but must be missing something else.

My questions is, what could be causing this issue and how can i solve
  it?

Body:
Don't use - in variable names.

Docker build will always show you the line as is written down in the Dockerfile, despite the variable value.

So use this variable name a_version:

ARG a_version

See this example:

Dockerfile:

FROM alpine

ARG a_version
RUN echo $a_version

Build:

$ docker build . --build-arg a_version=1234
Sending build context to Docker daemon 2.048 kB
Step 1/3 : FROM alpine
 ---> a41a7446062d
Step 2/3 : ARG a_version
 ---> Running in c55e98cab494
 ---> 53dedab7de75
Removing intermediate container c55e98cab494
Step 3/3 : RUN echo $a_version                <<< note this <<
 ---> Running in 56b8aeddf77b
1234                                          <<<< and this <<
 ---> 89badadc1ccf
Removing intermediate container 56b8aeddf77b
Successfully built 89badadc1ccf


问:
How to combine index arrays and slices in numpy
I have a problem with a combination of index arrays and slices. I have an image (A) and a vector with positions/indexes (pos). Now, I want to select  slices (here 3x) from A at different positions. Instead of looping over the positions array, I tried to use the indexer functions (o1), but I does not work.
Finally, all slices should be in one array (o2).
Can you help me with this problem ?

```<code>A = np.array([[0,0,0,0,0,0,3,3],
             [0,0,0,0,0,0,3,3],
             [0,0,0,1,1,0,0,0],
             [0,0,0,1,1,0,0,0],
             [0,0,0,0,0,0,2,2],
             [0,0,0,0,0,0,2,2],
             [0,0,0,0,0,0,0,0],
             [0,0,0,0,0,0,0,0]])

# positions to select
# EDIT:
# pos = np.array([[2,6,7],
#                 [3,4,0]])
pos = np.array([[2,4,0],
                [3,6,6]])

# array with all selections
o1 = np.zeros((3,2,2)).astype(np.int)
# EDIT:
#o1 = A[pos[0]:pos[0]+1,pos[1]:pos[1]+1] ## this gives just one of the values in one area
o1 = A[pos[0]:pos[0] + 2,pos[1]:pos[1] + 2]
print(o1.shape)
print(o1)

# model result
o2 = np.array([[[1,1],[1,1]],[[2,2],[2,2]],[[3,3],[3,3]]])
print(o2.shape)
print(o2)
</code>```

Another example: With the following line I get the area with the ones. Starting from the position [2,3] choose the next two rows and cols:

```<code>print( A[pos[0,0] : pos[0,0] + 2 , pos[1,0] : pos[1,0] + 2]  )
</code>```

Isn't it possible to extend this to several position pairs (over the whole array pos[]) ?

答:
It looks like you want this:

```<code>A[pos.tolist()]
</code>```

That is, fancy indexing using pairs of points.

Body:
I have a problem with a combination of index arrays and slices. I have an image (A) and a vector with positions/indexes (pos). Now, I want to select  slices (here 3x) from A at different positions. Instead of looping over the positions array, I tried to use the indexer functions (o1), but I does not work.
Finally, all slices should be in one array (o2).
Can you help me with this problem ?

A = np.array([[0,0,0,0,0,0,3,3],
             [0,0,0,0,0,0,3,3],
             [0,0,0,1,1,0,0,0],
             [0,0,0,1,1,0,0,0],
             [0,0,0,0,0,0,2,2],
             [0,0,0,0,0,0,2,2],
             [0,0,0,0,0,0,0,0],
             [0,0,0,0,0,0,0,0]])

# positions to select
# EDIT:
# pos = np.array([[2,6,7],
#                 [3,4,0]])
pos = np.array([[2,4,0],
                [3,6,6]])

# array with all selections
o1 = np.zeros((3,2,2)).astype(np.int)
# EDIT:
#o1 = A[pos[0]:pos[0]+1,pos[1]:pos[1]+1] ## this gives just one of the values in one area
o1 = A[pos[0]:pos[0] + 2,pos[1]:pos[1] + 2]
print(o1.shape)
print(o1)

# model result
o2 = np.array([[[1,1],[1,1]],[[2,2],[2,2]],[[3,3],[3,3]]])
print(o2.shape)
print(o2)

Another example: With the following line I get the area with the ones. Starting from the position [2,3] choose the next two rows and cols:

print( A[pos[0,0] : pos[0,0] + 2 , pos[1,0] : pos[1,0] + 2]  )

Isn't it possible to extend this to several position pairs (over the whole array pos[]) ?

Body:
It looks like you want this:

A[pos.tolist()]

That is, fancy indexing using pairs of points.


问:
rails: complex view with three models
I need a suggestion how I could solve the following situation:

I have an employee, who has many skills through employeeskillsets.
Every skill belongs to one category.
Categories are self referenced, so the following structure is possible (classified as topcategory-category-subcategory).

```<code>category1
|
-skill1, skill2, skill3
-category2
  |
  -category3
  -category4
   |
   -skill4, skill5
  -category5
-category6
category7
|
-skill6, skill7
</code>```

In short, the models are related like this employee-skill-category
In my view I would like to list the skills for each employee with the related category to each skill.

Has anybody an idea how I could solve this?
In addition, only those categories, where the employee has skills in, should be displayed.

If more infos are needed, I would edit those surely.

Thanks in advance.

答:
You can query the db in your controller

```<code>@employees = Employee.includes(skills: :category)
</code>```

In your view, you just need to loop over them and display the values e.g. giving you the loop structure, you need to manipulate it based on your view and attributes..

```<code>@employees.each do |employee|
  employee.name
  employee.skills.each do |skill|
    skill.name
    skill.category.name
  end
end
</code>```

Title: rails: complex view with three models

Body:
I need a suggestion how I could solve the following situation:

I have an employee, who has many skills through employeeskillsets.
Every skill belongs to one category.
Categories are self referenced, so the following structure is possible (classified as topcategory-category-subcategory).

category1
|
-skill1, skill2, skill3
-category2
  |
  -category3
  -category4
   |
   -skill4, skill5
  -category5
-category6
category7
|
-skill6, skill7

In short, the models are related like this employee-skill-category
In my view I would like to list the skills for each employee with the related category to each skill.

Has anybody an idea how I could solve this?
In addition, only those categories, where the employee has skills in, should be displayed.

If more infos are needed, I would edit those surely.

Thanks in advance.

Body:
You can query the db in your controller

@employees = Employee.includes(skills: :category)

In your view, you just need to loop over them and display the values e.g. giving you the loop structure, you need to manipulate it based on your view and attributes..

@employees.each do |employee|
  employee.name
  employee.skills.each do |skill|
    skill.name
    skill.category.name
  end
end


问:
Django and eBay style multi listing
I'm trying to mimic eBay's multi listing function. Basically, eBay allows users to specify two variations of their choice, for example size and color. Each variation will have different data, for example:

```<code>Color: red, green
Size: 12, 9
</code>```

Then it gets a bit confusing for example:

```<code>quantity for color red, size 12: 15
quantity for color red, size 9: 12
quantity for color green, size 12: 20
quantity for color green, size 9: 59
</code>```

The user will have to specify the quantity for each mixture of variation, first variation takes precedence.

To complicate matters Name and Color are examples only. They can be different properties.

How can I apply this in database level? Currently I'm just producing a list like so:

```<code>[color blue,size = 12,Quantity = 24,Price = 299,size = 23,Quantity = 43,Price = 298]
</code>```

Planning to store the list as string in a field, and using JSON to rebuild it.

The problem is, unnecessary processing will be required for every request. For example if Quantity decreases, then I can't just edit a field, I would have to use flags to find right Quantity from the list (unnecessary processing), and make appropriate changes to the list, and then store it again.

Looking for an alternative approach? I can't create fields for variations because they're specified by the user.

Looking for some direction.

My current Table looks like:

```<code>class Auction(models.Model):
    auction_id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=50)
    description = models.TextField(validators=[MaxLengthValidator(1000)])
    price = models.PositiveSmallIntegerField(default = 0)
    bid = models.PositiveSmallIntegerField(default = 0)
    image = models.ImageField(upload_to = 'img/', default = 'img/None/no-img.jpg')
    ......
    # stores multi listing list/dict
    multi_listing = models.CharField(max_length=200)

    flag = models.BooleanField(default=False)
    slug = models.SlugField(unique=True, default = (randint(0,1000000)))

    def __unicode__(self):
        return self.name
</code>```

答:
JSON

Planning to store the list as string in a field, and using JSON to rebuild it.

If you take this approach at all, you should be using a database that has a native JSON field. Of the databases that are officially supported by django only Mysql and Postgresql has it. Unfortunately the mysql version isn't fully supported by Django and you will need third party libraries.

Of the two, postgresql has the richer set of functionality and provides better indexing options. In fact, JSONB in postgresql is good enough to rival Mongodb.

If JSON is your choice, it has to be Postgresql JSONB. Nothing else will come even close. With JSONB there is no need to rebuild anything and you don't need to fetch the complete field just to update one of the items in the JSON dictionary.

But the data structure you have chosen is wrong. It should be more like

```<code>[{'color': 'blue' , 'size': 12, 'Quantity': '24', 'Price': 299},
 {'size': 23, 'Quantity': 43, 'Price' :298}]
</code>```

But oops, that's still an Array

Tip: Arrays are not sets; searching for specific array elements can be
  a sign of database misdesign. Consider using a separate table with a
  row for each item that would be an array element. This will be easier
  to search, and is likely to scale better for a large number of
  elements.

Nevertheless, a JSON array can be more effective than an ArrayField

Related Model

This is the more traditional way of doing this. And probably better than using JSON, definitely better if you are not using postgresl. Your model might look like this:

```<code>class Auction(models.Model):
    auction_id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=50)
    description = models.TextField(validators=[MaxLengthValidator(1000)])

    bid = models.PositiveSmallIntegerField(default = 0)
    image = models.ImageField(upload_to = 'img/', default = 'img/None/no-img.jpg')

    flag = models.BooleanField(default=False)
    slug = models.SlugField(unique=True, default = (randint(0,1000000)))

    def __unicode__(self):
        return self.name

class Pricing(models.Model):
    # stores multi listing list/dict

    price = models.PositiveSmallIntegerField(default = 0)
    color = models.CharField(max_length=12)
    size = models.IntegerField(max_length=200)
    auction = models.ForeignKey(Auction)
</code>```

Update

because 'color' and 'size' is defined by user, it could be name
  something else. For example they may choose a different variation
  instead of 'size' and 'color', they might choose 'material' and
  'color', so then how would you name the field?

This explaination tilts the scales in favor of JSON. However there is still two other alternatives that could possibly be considered. The first is redis. Not to use redis as a complete replacement for your RBMS but to store the user defined properties in redis.

The second alternative is to completey switch to a nosql database such as mongo. Unfortunately though Django doesn't play very well with nosql.

Title: Django and eBay style multi listing

Body:
I'm trying to mimic eBay's multi listing function. Basically, eBay allows users to specify two variations of their choice, for example size and color. Each variation will have different data, for example:

Color: red, green
Size: 12, 9

Then it gets a bit confusing for example:

quantity for color red, size 12: 15
quantity for color red, size 9: 12
quantity for color green, size 12: 20
quantity for color green, size 9: 59

The user will have to specify the quantity for each mixture of variation, first variation takes precedence.

To complicate matters Name and Color are examples only. They can be different properties.

How can I apply this in database level? Currently I'm just producing a list like so:

[color blue,size = 12,Quantity = 24,Price = 299,size = 23,Quantity = 43,Price = 298]

Planning to store the list as string in a field, and using JSON to rebuild it.

The problem is, unnecessary processing will be required for every request. For example if Quantity decreases, then I can't just edit a field, I would have to use flags to find right Quantity from the list (unnecessary processing), and make appropriate changes to the list, and then store it again.

Looking for an alternative approach? I can't create fields for variations because they're specified by the user.

Looking for some direction.

My current Table looks like:

class Auction(models.Model):
    auction_id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=50)
    description = models.TextField(validators=[MaxLengthValidator(1000)])
    price = models.PositiveSmallIntegerField(default = 0)
    bid = models.PositiveSmallIntegerField(default = 0)
    image = models.ImageField(upload_to = 'img/', default = 'img/None/no-img.jpg')
    ......
    # stores multi listing list/dict
    multi_listing = models.CharField(max_length=200)

    flag = models.BooleanField(default=False)
    slug = models.SlugField(unique=True, default = (randint(0,1000000)))

    def __unicode__(self):
        return self.name

Body:
JSON

Planning to store the list as string in a field, and using JSON to rebuild it.

If you take this approach at all, you should be using a database that has a native JSON field. Of the databases that are officially supported by django only Mysql and Postgresql has it. Unfortunately the mysql version isn't fully supported by Django and you will need third party libraries.

Of the two, postgresql has the richer set of functionality and provides better indexing options. In fact, JSONB in postgresql is good enough to rival Mongodb.

If JSON is your choice, it has to be Postgresql JSONB. Nothing else will come even close. With JSONB there is no need to rebuild anything and you don't need to fetch the complete field just to update one of the items in the JSON dictionary.

But the data structure you have chosen is wrong. It should be more like

[{'color': 'blue' , 'size': 12, 'Quantity': '24', 'Price': 299},
 {'size': 23, 'Quantity': 43, 'Price' :298}]

But oops, that's still an Array

Tip: Arrays are not sets; searching for specific array elements can be
  a sign of database misdesign. Consider using a separate table with a
  row for each item that would be an array element. This will be easier
  to search, and is likely to scale better for a large number of
  elements.

Nevertheless, a JSON array can be more effective than an ArrayField

Related Model

This is the more traditional way of doing this. And probably better than using JSON, definitely better if you are not using postgresl. Your model might look like this:

class Auction(models.Model):
    auction_id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=50)
    description = models.TextField(validators=[MaxLengthValidator(1000)])

    bid = models.PositiveSmallIntegerField(default = 0)
    image = models.ImageField(upload_to = 'img/', default = 'img/None/no-img.jpg')

    flag = models.BooleanField(default=False)
    slug = models.SlugField(unique=True, default = (randint(0,1000000)))

    def __unicode__(self):
        return self.name

class Pricing(models.Model):
    # stores multi listing list/dict

    price = models.PositiveSmallIntegerField(default = 0)
    color = models.CharField(max_length=12)
    size = models.IntegerField(max_length=200)
    auction = models.ForeignKey(Auction)

Update

because 'color' and 'size' is defined by user, it could be name
  something else. For example they may choose a different variation
  instead of 'size' and 'color', they might choose 'material' and
  'color', so then how would you name the field?

This explaination tilts the scales in favor of JSON. However there is still two other alternatives that could possibly be considered. The first is redis. Not to use redis as a complete replacement for your RBMS but to store the user defined properties in redis.

The second alternative is to completey switch to a nosql database such as mongo. Unfortunately though Django doesn't play very well with nosql.


问:
Unshuffle an array of int/char
To shuffle the chars of the string st, I use std::shuffle and a random number generator, which is fed by a known seed. This is part of an encoder that, for simplicity, just shuffles the input.

The shuffled data is going to be sent to a decoder. At that side we don't have access to the original input, but the shuffled one.

How can I Unshuffle the string shuffledSt, using the same random number generator and the same seed, until I can obtain the original string st?

```<code>#include <random>
#include <algorithm>
int main (int argc, char* argv[])
{
    std::string st = "asdfgh";
    int seed = 1000;

    std::shuffle(st.begin(), st.end(), std::default_random_engine(seed));
    std::cerr << st << '\n';

    std::string shuffledSt = st;

    return 0;
}
</code>```

答:
I suggest following algorithm

Generate a vector indices with std::iota of st.size() elements.

Shuffle that vector with the same engine with the same seed.

While looping over the shuffled vector, generate a new string result where result[indices[i]] = st[i]

Title: Unshuffle an array of int/char

Body:
To shuffle the chars of the string st, I use std::shuffle and a random number generator, which is fed by a known seed. This is part of an encoder that, for simplicity, just shuffles the input.

The shuffled data is going to be sent to a decoder. At that side we don't have access to the original input, but the shuffled one.

How can I Unshuffle the string shuffledSt, using the same random number generator and the same seed, until I can obtain the original string st?

#include <random>
#include <algorithm>
int main (int argc, char* argv[])
{
    std::string st = "asdfgh";
    int seed = 1000;

    std::shuffle(st.begin(), st.end(), std::default_random_engine(seed));
    std::cerr << st << '\n';

    std::string shuffledSt = st;

    return 0;
}


问:
Sending binary data over gevent websocket
I need to send a pickled python dictionary containing several, large Pandas Dataframes over a websocket (Python API at both ends). To improve performance, I would like to compress the pickled object before sending it over the websocket. However, when doing this, the received message is always None.

Client:

```<code>df = pd.DataFrame({'a':[1,2,3,4]})
d = dict(b=df)
msg = zlib.compress(pickle.dumps(d),5)
socket.send(msg)
</code>```

Server:

```<code>msg = socket.receive()
# msg is always None when called with client code above.
data = pickle.loads(zlib.decompress(msg))
</code>```

Is there a better way to do this?
I am using gevent-websocket through the Flask-Sockets framework.

答:
To send binary data in Python 2.7, you must set binary=True in the client (ws4py):

```<code>socket.send(msg, Binary=True)
</code>```

As another note, on the receiving side, you will need to wrap the msg in a buffer before sending to zlib.decompress()

```<code>msg = socket.receive()
data = pickle.loads(zlib.decompress(buffer(msg)))
</code>```

Body:
I need to send a pickled python dictionary containing several, large Pandas Dataframes over a websocket (Python API at both ends). To improve performance, I would like to compress the pickled object before sending it over the websocket. However, when doing this, the received message is always None.

Client:

df = pd.DataFrame({'a':[1,2,3,4]})
d = dict(b=df)
msg = zlib.compress(pickle.dumps(d),5)
socket.send(msg)

Server:

msg = socket.receive()
# msg is always None when called with client code above.
data = pickle.loads(zlib.decompress(msg))

Is there a better way to do this?
I am using gevent-websocket through the Flask-Sockets framework.

Body:
To send binary data in Python 2.7, you must set binary=True in the client (ws4py):

socket.send(msg, Binary=True)

As another note, on the receiving side, you will need to wrap the msg in a buffer before sending to zlib.decompress()

msg = socket.receive()
data = pickle.loads(zlib.decompress(buffer(msg)))


问:
Join row with specified field value and highest value in other field
I have 2 tables:

Articles:

ID INTEGER

...

Article_versions:

article INTEGER

lang ENUM

time TIMESTAMP

PRIMARY KEY( article,lang,time )

...

I want to select fields from Articles and fields from related latest row Article_versions.
Should i use join or 2 select statements?

And how can i do this?

答:
Assuming [Articles_versions].[time] would be the only unique column returned in the join set you could use the following:</p>

```<code>SELECT [Articles].[ID], [Articles_versions].[article], [Articles_versions].[lang], MAX([Articles_versions].[time])
FROM Articles Inner Join Articles_versions ON [Articles].[ID] = [Articles_versions].[article]
GROUP BY [Articles].[ID], [Articles_versions].[article], [Articles_versions].[lang]
</code>```

Body:
Assuming [Articles_versions].[time] would be the only unique column returned in the join set you could use the following:

SELECT [Articles].[ID], [Articles_versions].[article], [Articles_versions].[lang], MAX([Articles_versions].[time])
FROM Articles Inner Join Articles_versions ON [Articles].[ID] = [Articles_versions].[article]
GROUP BY [Articles].[ID], [Articles_versions].[article], [Articles_versions].[lang]


问:
Spring Boot application.yml and application.properties
I was trying to understand if I have some properties in application.yml and a few in application.properties will my application read from both these files?</p>

答:
There is a good article here, that describes how both of these can be read using the @ConfigurationProperties annotation.

@ConfigurationProperties supports both .properties and .yml files.
@ConfigurationProperties support JSR-303 bean validation – javax.validation

Hope this helps!


问:
react child component fails to render when calling parent callback with setstate
I have a parent/child component:

```<code>class Input extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: this.props.value};
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    // event is persisted, used to update local state
    // and then call parent onChange callback after local state update
    e.persist();
    this.setState(
      {value: e.target.value},
      () => this.props.onChange(e)
    );
  }

  render() {
    return (<input ... onChange={this.handleChange} />);
  }
}

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {modified: false};
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    const {name, value} = e.target;
    console.log(`${name}: ${value}`);
    // the two line execute fine, and everything works ok
    // but as soon as I add the bottom on, Input no longer updates!
    this.setState({modified: true});
  }

  render() {
    return (
      <Input ... onChange={this.handleChange}
                 style={{backgroundColor: this.state.modified?"red":"blue"}}
      />
    );
  }
}
</code>```

So as soon as I do a setState on the parent, the child component no longer renders properly. Why? Does it have something to do with the event object or the fact that the parent event handler is called from the child event handler?

答:
Use this (add spaces before and after ?):

```<code>style={{backgroundColor: this.state.modified ? "red" : "blue"}}
</code>```

instead of this:

```<code>style={{backgroundColor: this.state.modified?"red":"blue"}}
</code>```

After this change your example works fine:

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: this.props.value};
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    // event is persisted, used to update local state
    // and then call parent onChange callback after local state update
    e.persist();
    this.setState(
      {value: e.target.value},
      () => this.props.onChange(e)
    );
  }

  render() {
    return (<input style={this.props.style}  onChange={this.handleChange} />);
  }
}

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {modified: false};
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    const {name, value} = e.target;
    console.log(`${name}: ${value}`);
    // the two line execute fine, and everything works ok
    // but as soon as I add the bottom on, Input no longer updates!
    this.setState({modified: true});
  }

  render() {
    return (
      <Input onChange={this.handleChange}
                 style={{backgroundColor: this.state.modified ? "red":"blue"}}
      />
    );
  }
}

ReactDOM.render(
  <Page />,
  document.getElementById('container')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div></code>```

Body:
I have a parent/child component:

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: this.props.value};
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    // event is persisted, used to update local state
    // and then call parent onChange callback after local state update
    e.persist();
    this.setState(
      {value: e.target.value},
      () => this.props.onChange(e)
    );
  }

  render() {
    return (<input ... onChange={this.handleChange} />);
  }
}

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {modified: false};
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    const {name, value} = e.target;
    console.log(`${name}: ${value}`);
    // the two line execute fine, and everything works ok
    // but as soon as I add the bottom on, Input no longer updates!
    this.setState({modified: true});
  }

  render() {
    return (
      <Input ... onChange={this.handleChange}
                 style={{backgroundColor: this.state.modified?"red":"blue"}}
      />
    );
  }
}

So as soon as I do a setState on the parent, the child component no longer renders properly. Why? Does it have something to do with the event object or the fact that the parent event handler is called from the child event handler?

Body:
Use this (add spaces before and after ?):

style={{backgroundColor: this.state.modified ? "red" : "blue"}}

instead of this:

style={{backgroundColor: this.state.modified?"red":"blue"}}

After this change your example works fine:

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: this.props.value};
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    // event is persisted, used to update local state
    // and then call parent onChange callback after local state update
    e.persist();
    this.setState(
      {value: e.target.value},
      () => this.props.onChange(e)
    );
  }

  render() {
    return (<input style={this.props.style}  onChange={this.handleChange} />);
  }
}

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {modified: false};
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    const {name, value} = e.target;
    console.log(`${name}: ${value}`);
    // the two line execute fine, and everything works ok
    // but as soon as I add the bottom on, Input no longer updates!
    this.setState({modified: true});
  }

  render() {
    return (
      <Input onChange={this.handleChange}
                 style={{backgroundColor: this.state.modified ? "red":"blue"}}
      />
    );
  }
}

ReactDOM.render(
  <Page />,
  document.getElementById('container')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>


问:
css opacity affecting sibling opacity
[EDIT: Due to a mistake when creating this question from it's javascript based original, this question is obsolete.  ]

I have a HTML page which shows a matrix of the latest build states of our various products and multiple versions.

In this matrix, older builds are faded out by setting an opacity: .5 through assigning an additional style class "stale".

This matrix also shows results of tests performed. The test result element is a sibling to the build element and partially overlays it.

However, my problem now is, that if the 'build' element is faded out, the 'test' element is faded out too. First of all I'd like to understand why and secondly I don't want the 'test' result to be transparent.

table { border: 1px solid darkgrey; }
td { border: 1px solid darkgrey; overflow: hidden; }
div { text-align: center; }
.build {
    border: solid black 1px;
    width: 10em;
    margin: 0.2em;
    padding: 0.2em;
    font-size: 1.0em;
}
.test {
    float: right;
    border: solid lightgrey 1px;
    width: 3em;
    margin-top: -0.8em;
    margin-right: -0.4em;
    // opacity: .99;      // workaround
}
.fail { background-color: rgb(255, 150, 150); }
.ok { background-color: rgb(170, 255, 170); }
.red { background-color: rgb(255, 150, 150); }
.green { background-color: rgb(150, 255, 150); }
.stale { opacity: .5; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <th>Version</th>
    <th>Product A</th>
    <th>Product B</th>
  </tr>
  <tr>
    <td>1.1</td>
    <td>
      <div class="build ok">success</div>
      <div class="test green">100%</div>
    </td>
    <td>
      <div class="build ok">success</div>
      <div class="test red">98%</div>
    </td>
  </tr>
  <tr>
    <td>1.0</td>
    <td>
      <div class="build ok stale">success</div>
      <div class="test red">99%</div>
    </td>
    <td>
      <div class="build fail stale">failure</div>
    </td>
  </tr>
</table></code>```

(tested with Firefox 52.1 ESR, Chrome 58)

I did some research and came across the SO question css opacity affecting sibling image opacity but adding position and z-index (on either or both of the style classes build and test) did not solve my problem.

The only way I found so far to work around this behaviour is to add opacity: .99; to my .test style definition, but don't consider this a clean solution, and would like to better understand the reason of this behaviour.

答:
You need to close your
 tags properly.

The issue you are experiencing is a result of your browser's attempt to 'fix' your markup at run-time, the
 elements are incorrectly placed within one another, so they are no longer siblings.

Fixing your markup solves your problem.

table { border: 1px solid darkgrey; }
td { border: 1px solid darkgrey; overflow: hidden; }
div { text-align: center; }
.build {
    border: solid black 1px;
    width: 10em;
    margin: 0.2em;
    padding: 0.2em;
    font-size: 1.0em;
}
.test {
    float: right;
    border: solid lightgrey 1px;
    width: 3em;
    margin-top: -0.8em;
    margin-right: -0.4em;
    // opacity: .99;      // workaround
}
.fail { background-color: rgb(255, 150, 150); }
.ok { background-color: rgb(170, 255, 170); }
.red { background-color: rgb(255, 150, 150); }
.green { background-color: rgb(150, 255, 150); }
.stale { opacity: .5; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <th>Version</th>
    <th>Product A</th>
    <th>Product B</th>
  </tr>
  <tr>
    <td>1.1</td>
    <td>
      <div class="build ok">success</div>
      <div class="test green">100%</div>
    </td>
    <td>
      <div class="build ok">success</div>
      <div class="test red">98%</div>
    </td>
  </tr>
  <tr>
    <td>1.0</td>
    <td>
      <div class="build ok stale">success</div>
      <div class="test red">99%</div>
    </td>
    <td>
      <div class="build fail stale">failure</div>
    </td>
  </tr>
</table></code>```

Title: css opacity affecting sibling opacity

Body:
[EDIT: Due to a mistake when creating this question from it's javascript based original, this question is obsolete.  ]

I have a HTML page which shows a matrix of the latest build states of our various products and multiple versions.

In this matrix, older builds are faded out by setting an opacity: .5 through assigning an additional style class "stale".

This matrix also shows results of tests performed. The test result element is a sibling to the build element and partially overlays it.

However, my problem now is, that if the 'build' element is faded out, the 'test' element is faded out too. First of all I'd like to understand why and secondly I don't want the 'test' result to be transparent.

table { border: 1px solid darkgrey; }
td { border: 1px solid darkgrey; overflow: hidden; }
div { text-align: center; }
.build {
    border: solid black 1px;
    width: 10em;
    margin: 0.2em;
    padding: 0.2em;
    font-size: 1.0em;
}
.test {
    float: right;
    border: solid lightgrey 1px;
    width: 3em;
    margin-top: -0.8em;
    margin-right: -0.4em;
    // opacity: .99;      // workaround
}
.fail { background-color: rgb(255, 150, 150); }
.ok { background-color: rgb(170, 255, 170); }
.red { background-color: rgb(255, 150, 150); }
.green { background-color: rgb(150, 255, 150); }
.stale { opacity: .5; }

    Version
    Product A
    Product B

    1.1

success

100%

success

98%

    1.0

success

99%

failure

(tested with Firefox 52.1 ESR, Chrome 58)

I did some research and came across the SO question css opacity affecting sibling image opacity but adding position and z-index (on either or both of the style classes build and test) did not solve my problem.

The only way I found so far to work around this behaviour is to add opacity: .99; to my .test style definition, but don't consider this a clean solution, and would like to better understand the reason of this behaviour.

Body:
You need to close your <div> tags properly.

The issue you are experiencing is a result of your browser's attempt to 'fix' your markup at run-time, the <div> elements are incorrectly placed within one another, so they are no longer siblings.

Fixing your markup solves your problem.

table { border: 1px solid darkgrey; }
td { border: 1px solid darkgrey; overflow: hidden; }
div { text-align: center; }
.build {
    border: solid black 1px;
    width: 10em;
    margin: 0.2em;
    padding: 0.2em;
    font-size: 1.0em;
}
.test {
    float: right;
    border: solid lightgrey 1px;
    width: 3em;
    margin-top: -0.8em;
    margin-right: -0.4em;
    // opacity: .99;      // workaround
}
.fail { background-color: rgb(255, 150, 150); }
.ok { background-color: rgb(170, 255, 170); }
.red { background-color: rgb(255, 150, 150); }
.green { background-color: rgb(150, 255, 150); }
.stale { opacity: .5; }

<table>
  <tr>
    <th>Version</th>
    <th>Product A</th>
    <th>Product B</th>
  </tr>
  <tr>
    <td>1.1</td>
    <td>
      <div class="build ok">success</div>
      <div class="test green">100%</div>
    </td>
    <td>
      <div class="build ok">success</div>
      <div class="test red">98%</div>
    </td>
  </tr>
  <tr>
    <td>1.0</td>
    <td>
      <div class="build ok stale">success</div>
      <div class="test red">99%</div>
    </td>
    <td>
      <div class="build fail stale">failure</div>
    </td>
  </tr>
</table>


问:
Indenting with white spaces, tabs, and how many spaces or the tab width
I know that this is more of a coding style, instead of a one right way of doing things. But, I'm a bit frustrated if I came across different indenting formats.

But, I would like to hear the reasons by various people on these issues:

Do you use spaces or tabs? Tabs with spaces? Any difference with "Tab insert space", instead of using the space key directly?

How many spaces to indent each line of code? Why?

Does different code has different style that is more suitable for each of them?

Is there a way to "visually" indent code without actually writing the indent? So it won't ruin the original indenting? It seems unlikely.

I'm using Xcode, so it's better if you have advice for Xcode projects.

答:
An advantage to spaces vs tabs is alignment when wrapping long lines.  If you use tabs, no matter what you do, the lines below will most likely not align, unless the editor has the same settings.

For example:

```<code>    result = variable_one + variable_two + variable_three +
             variable_four;
</code>```

If you use tabs, how to ensure that 'variable_four' will show up aligned if tab indentation changes?

Body:
An advantage to spaces vs tabs is alignment when wrapping long lines.  If you use tabs, no matter what you do, the lines below will most likely not align, unless the editor has the same settings.

For example:

    result = variable_one + variable_two + variable_three +
             variable_four;

If you use tabs, how to ensure that 'variable_four' will show up aligned if tab indentation changes?


问:
Selenium Webdriver with Python: Element is not clickable & Cannot read property 'click' of null
when running this command, I'm getting an error:

```<code>driver.find_element_by_link_text("Confirm").click()

selenium.common.exceptions.WebDriverException: Message: unknown error: Element <a href="javascript:void(0);" class="c-button u-fontSize13 c-button--blue transparent-button js-connect-button js-request-connection" data-href="https://angel.co/user_graph_requests" data-invited-id="5911955">...</a> is not clickable at point (67, 581). Other element would receive the click: `<div class="mfp-container mfp-ajax-holder mfp-s-loading">...</div>`
</code>```

After searching answers on this issue, I've changed the above code to:

```<code>element = driver.find_element_by_link_text("Confirm").click()
driver.execute_script("arguments[0].click();", element)
</code>```

For the first click it worked and then printed this error:

```<code>selenium.common.exceptions.WebDriverException: Message: unknown error: Cannot read property 'click' of null
</code>```

The HTML code is:

```<code><a href="javascript:void(0);" class="c-button js-close s-vgLeft0_5 c-button--blue" data-modal="true" data-url="https://angel.co/user_graph_requests/102006082/verify">Confirm</a>
</code>```

答:
Try to search for the class:

driver.find_element_by_class("c-button js-close s-vgLeft0_5 c-button--blue").click()

Body:
when running this command, I'm getting an error:

driver.find_element_by_link_text("Confirm").click()

selenium.common.exceptions.WebDriverException: Message: unknown error: Element ... is not clickable at point (67, 581). Other element would receive the click: `<div class="mfp-container mfp-ajax-holder mfp-s-loading">...</div>`

After searching answers on this issue, I've changed the above code to:

element = driver.find_element_by_link_text("Confirm").click()
driver.execute_script("arguments[0].click();", element)

For the first click it worked and then printed this error:

selenium.common.exceptions.WebDriverException: Message: unknown error: Cannot read property 'click' of null

The HTML code is:

Confirm


问:
Xamarin.Android: starting a new intent
I was targeting android 4.4 and was starting a service like this

```<code>start.Click += delegate {
    StartService(new Intent("com.xamarin.LocationService"));
    start.Enabled = false;
    stop.Enabled = true;
};
</code>```

and it all worked fine. Now I am targeting 6.0 and find from this thread that this isn't secure, and I should do this:

```<code>Intent serviceIntent = new Intent(context,MyService.class);
context.startService(serviceIntent);
</code>```

but I cannot work out what the arguments for 'new Intent()' should be. The class name is 'LocationActivity' but if I do this

```<code>serviceIntent = new Intent(this, typeof(LocationActivity));
context.startService(serviceIntent);
</code>```

it compiles OK but the service doesn't actually start.

The marked answer in that thread also suggests this

```<code>Intent bi = new Intent("com.android.vending.billing.InAppBillingService.BIND");
bi.setPackage("com.android.vending");
</code>```

but if I try that I find that 'Intent does not contain a  definition for setPackage'.

So, can someone help me with a solution here? Thanks in advance.

答:
If you want to start an activity you need to use StartActivity and not StartService
Then use this but change from StartService to StartActivity.

From

```<code>serviceIntent = new Intent(this, typeof(LocationActivity));
context.startService(serviceIntent);
</code>```

To

```<code>serviceIntent = new Intent(this, typeof(LocationActivity));
context.StartActivity(serviceIntent);
</code>```

Title: Xamarin.Android: starting a new intent

Body:
I was targeting android 4.4 and was starting a service like this

start.Click += delegate {
    StartService(new Intent("com.xamarin.LocationService"));
    start.Enabled = false;
    stop.Enabled = true;
};

and it all worked fine. Now I am targeting 6.0 and find from this thread that this isn't secure, and I should do this:

Intent serviceIntent = new Intent(context,MyService.class);
context.startService(serviceIntent);

but I cannot work out what the arguments for 'new Intent()' should be. The class name is 'LocationActivity' but if I do this

serviceIntent = new Intent(this, typeof(LocationActivity));
context.startService(serviceIntent);

it compiles OK but the service doesn't actually start.

The marked answer in that thread also suggests this

Intent bi = new Intent("com.android.vending.billing.InAppBillingService.BIND");
bi.setPackage("com.android.vending");

but if I try that I find that 'Intent does not contain a  definition for setPackage'.

So, can someone help me with a solution here? Thanks in advance.

Body:
If you want to start an activity you need to use StartActivity and not StartService
Then use this but change from StartService to StartActivity.

From

serviceIntent = new Intent(this, typeof(LocationActivity));
context.startService(serviceIntent);

To

serviceIntent = new Intent(this, typeof(LocationActivity));
context.StartActivity(serviceIntent);


问:
Jetty to serve plain html and JS code
I've installed Jetty using homebrew on osx. Jetty is in the usual folder:

```<code>/usr/local/Cellar/jetty/9.4.5.v20170502
</code>```

However, we are not going to use this for anything related to Java. It's just our requirement that the web server we will have in production is Websphere. Our code is pure html and some JS. Only static files. All the tutorials on the web require modifying XML files and setting up complex folder structures for java apps. We do not need any of this. All we want is to put html/js files in some specific place.

Is there an easy way to do this? Do we have to create a start.jar for this simple task? How do we create a WAR package via Maven or something else? Would appreciate any simple pointer to getting this dev environment set up. Thank you!

答:
It seems you might be overthinking this a bit. start.jar is merely the JAR file that starts up the sever. You can easily host static content out of Jetty. I am unsure of your specific requirements, but for the sake of an example, I will just assume you have a simple webapp with a page and some resources. Your implementation might look like this.

Inside the Jetty 9.4.5.v20170502 directory - Also called Jetty_Home (you can learn about Jetty_Home vs Jetty_Base here), you'll find the following directories:

bin demo-base etc lib logs modules resources webapps

These are the standard of truth and should not be modified (though demo-base can be removed entirely if desired). You will want to create your own Jetty_Base directory to host your content out of, let's call it stackoverflow for this example. It is worth noting that a Jetty_Base can exist anywhere, I am just keeping it here for ease of this example.

Inside the stackoverflow directory you'll find nothing to start with, so we will need to enable some modules to populate our Jetty_Base. Now, I have no idea what all you plan to do with this webserver, so I will keep it minimal - enough to host the content. From inside this directory run:

```<code>> java -jar ../start.jar --create-startd
MKDIR : ${jetty.base}/start.d
INFO  : Base directory was modified
</code>```

This will create a start.d directory for all of our module files to live in, which makes modifying and configuring things a breeze (though for the sake of this example everything will be left default). Now we need to add the modules which will enable the functionality on the server. You can view a whole list of available modules by running:

```<code>> java -jar ../start.jar --list-modules
</code>```

I am not going to paste the whole list here but instead enable the following:

```<code>> java -jar ../start.jar --add-to-start=server,client,deploy,http,webapp,jsp
INFO  : webapp          initialized in ${jetty.base}/start.d/webapp.ini
INFO  : server          initialized in ${jetty.base}/start.d/server.ini
INFO  : security        transitively enabled
INFO  : apache-jsp      transitively enabled
INFO  : servlet         transitively enabled
INFO  : jsp             initialized in ${jetty.base}/start.d/jsp.ini
INFO  : jndi            transitively enabled
INFO  : client          initialized in ${jetty.base}/start.d/client.ini
INFO  : http            initialized in ${jetty.base}/start.d/http.ini
INFO  : annotations     transitively enabled
INFO  : plus            transitively enabled
INFO  : deploy          initialized in ${jetty.base}/start.d/deploy.ini
MKDIR : ${jetty.base}/webapps
INFO  : Base directory was modified
</code>```

This will enable all the modules I defined (server,client,deploy,http,webapp,jsp) as well as any dependencies required for them to operate and any required folders (such as webapps).

Now, I created a very small webapp named example. I've gone ahead and moved it into the webapps directory inside our stackoverflow Jetty_Base:

```<code>> tree
.
├── start.d
│   ├── client.ini
│   ├── deploy.ini
│   ├── http.ini
│   ├── jsp.ini
│   ├── server.ini
│   └── webapp.ini
└── webapps
    ├── example
    │   ├── images
    │   │   ├── jetty-header.jpg
    │   │   └── webtide_logo.jpg
    │   ├── index.html
    │   └── jetty.css
    └── example.xml
</code>```

I have a context xml file I created for this webapp named example.xml, which is only serving static content, and it is very simple:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">

<Configure id="exampleApp" class="org.eclipse.jetty.webapp.WebAppContext">
  <Set name="contextPath">/example</Set>
  <Set name="war"><Property name="jetty.webapps" default="."/>/example</Set>
</Configure>
</code>```

This configures the webapp so that when I run the server I can navigate to, in this case, localhost:8080/example and see my content. Now all I have to do is run my server. From inside the stackoverflow directory:

```<code>java -jar ../start.jar
2017-06-08 10:36:32.300:INFO::main: Logging initialized @427ms to org.eclipse.jetty.util.log.StdErrLog
2017-06-08 10:36:32.477:INFO:oejs.Server:main: jetty-9.4.5.v20170502
2017-06-08 10:36:32.494:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:///Users/example/installs/repository/jetty-distribution-9.4.5.v20170502/stackoverflow/webapps/] at interval 1
2017-06-08 10:36:32.633:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=26ms
2017-06-08 10:36:32.668:INFO:oejs.session:main: DefaultSessionIdManager workerName=node0
2017-06-08 10:36:32.668:INFO:oejs.session:main: No SessionScavenger set, using defaults
2017-06-08 10:36:32.669:INFO:oejs.session:main: Scavenging every 600000ms
2017-06-08 10:36:32.692:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@6e06451e{/example,file:///Users/example/installs/repository/jetty-distribution-9.4.5.v20170502/stackoverflow/webapps/example/,AVAILABLE}{/example}
2017-06-08 10:36:32.713:INFO:oejs.AbstractConnector:main: Started ServerConnector@21a947fe{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2017-06-08 10:36:32.714:INFO:oejs.Server:main: Started @840ms
</code>```

And now you have a server up and running and content being served. I hope this helps. It can seem overwhelming at first, but it isn't so bad once your get your hands dirty. I recommend reading up more at the official documentation.

Title: Jetty to serve plain html and JS code

Body:
I've installed Jetty using homebrew on osx. Jetty is in the usual folder:

/usr/local/Cellar/jetty/9.4.5.v20170502

However, we are not going to use this for anything related to Java. It's just our requirement that the web server we will have in production is Websphere. Our code is pure html and some JS. Only static files. All the tutorials on the web require modifying XML files and setting up complex folder structures for java apps. We do not need any of this. All we want is to put html/js files in some specific place.

Is there an easy way to do this? Do we have to create a start.jar for this simple task? How do we create a WAR package via Maven or something else? Would appreciate any simple pointer to getting this dev environment set up. Thank you!

Body:
It seems you might be overthinking this a bit. start.jar is merely the JAR file that starts up the sever. You can easily host static content out of Jetty. I am unsure of your specific requirements, but for the sake of an example, I will just assume you have a simple webapp with a page and some resources. Your implementation might look like this.

Inside the Jetty 9.4.5.v20170502 directory - Also called Jetty_Home (you can learn about Jetty_Home vs Jetty_Base here), you'll find the following directories:

bin demo-base etc lib logs modules resources webapps

These are the standard of truth and should not be modified (though demo-base can be removed entirely if desired). You will want to create your own Jetty_Base directory to host your content out of, let's call it stackoverflow for this example. It is worth noting that a Jetty_Base can exist anywhere, I am just keeping it here for ease of this example.

Inside the stackoverflow directory you'll find nothing to start with, so we will need to enable some modules to populate our Jetty_Base. Now, I have no idea what all you plan to do with this webserver, so I will keep it minimal - enough to host the content. From inside this directory run:

> java -jar ../start.jar --create-startd
MKDIR : ${jetty.base}/start.d
INFO  : Base directory was modified

This will create a start.d directory for all of our module files to live in, which makes modifying and configuring things a breeze (though for the sake of this example everything will be left default). Now we need to add the modules which will enable the functionality on the server. You can view a whole list of available modules by running:

> java -jar ../start.jar --list-modules

I am not going to paste the whole list here but instead enable the following:

> java -jar ../start.jar --add-to-start=server,client,deploy,http,webapp,jsp
INFO  : webapp          initialized in ${jetty.base}/start.d/webapp.ini
INFO  : server          initialized in ${jetty.base}/start.d/server.ini
INFO  : security        transitively enabled
INFO  : apache-jsp      transitively enabled
INFO  : servlet         transitively enabled
INFO  : jsp             initialized in ${jetty.base}/start.d/jsp.ini
INFO  : jndi            transitively enabled
INFO  : client          initialized in ${jetty.base}/start.d/client.ini
INFO  : http            initialized in ${jetty.base}/start.d/http.ini
INFO  : annotations     transitively enabled
INFO  : plus            transitively enabled
INFO  : deploy          initialized in ${jetty.base}/start.d/deploy.ini
MKDIR : ${jetty.base}/webapps
INFO  : Base directory was modified

This will enable all the modules I defined (server,client,deploy,http,webapp,jsp) as well as any dependencies required for them to operate and any required folders (such as webapps).

Now, I created a very small webapp named example. I've gone ahead and moved it into the webapps directory inside our stackoverflow Jetty_Base:

> tree
.
├── start.d
│   ├── client.ini
│   ├── deploy.ini
│   ├── http.ini
│   ├── jsp.ini
│   ├── server.ini
│   └── webapp.ini
└── webapps
    ├── example
    │   ├── images
    │   │   ├── jetty-header.jpg
    │   │   └── webtide_logo.jpg
    │   ├── index.html
    │   └── jetty.css
    └── example.xml

I have a context xml file I created for this webapp named example.xml, which is only serving static content, and it is very simple:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">

<Configure id="exampleApp" class="org.eclipse.jetty.webapp.WebAppContext">
  <Set name="contextPath">/example</Set>
  <Set name="war"><Property name="jetty.webapps" default="."/>/example</Set>
</Configure>

This configures the webapp so that when I run the server I can navigate to, in this case, localhost:8080/example and see my content. Now all I have to do is run my server. From inside the stackoverflow directory:

java -jar ../start.jar
2017-06-08 10:36:32.300:INFO::main: Logging initialized @427ms to org.eclipse.jetty.util.log.StdErrLog
2017-06-08 10:36:32.477:INFO:oejs.Server:main: jetty-9.4.5.v20170502
2017-06-08 10:36:32.494:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:///Users/example/installs/repository/jetty-distribution-9.4.5.v20170502/stackoverflow/webapps/] at interval 1
2017-06-08 10:36:32.633:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=26ms
2017-06-08 10:36:32.668:INFO:oejs.session:main: DefaultSessionIdManager workerName=node0
2017-06-08 10:36:32.668:INFO:oejs.session:main: No SessionScavenger set, using defaults
2017-06-08 10:36:32.669:INFO:oejs.session:main: Scavenging every 600000ms
2017-06-08 10:36:32.692:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@6e06451e{/example,file:///Users/example/installs/repository/jetty-distribution-9.4.5.v20170502/stackoverflow/webapps/example/,AVAILABLE}{/example}
2017-06-08 10:36:32.713:INFO:oejs.AbstractConnector:main: Started ServerConnector@21a947fe{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2017-06-08 10:36:32.714:INFO:oejs.Server:main: Started @840ms

And now you have a server up and running and content being served. I hope this helps. It can seem overwhelming at first, but it isn't so bad once your get your hands dirty. I recommend reading up more at the official documentation.


问:
Java. Consumer - Producer with BlockingQueue. Search tool
I was trying to implement some Consumer-Producer problem with BlockingQueue. To do it with some purpose, I decided to write file searching tool.

I decided that search mechanism is working recursively, and every new directory is going to have new thread pool to increase speed of searching.

My problem is, that I have no idea how can I implement mechanism that stops printing threads (consumers) at the end - when searching threads get job done.

I was trying to do that with some ideas like POISON PILLS, but it doesn't works well (threads stops before print any results). Any ideas how can I do that?

Here is some code:

Searching mechanism:

```<code>public class SearchingAlgorithm implements Runnable {

private final File file;
private BlockingQueue<File> queue;
private ExecutorService executor;

public SearchingAlgorithm(File fileName, BlockingQueue<File> queue) {
    this.file = fileName;
    this.queue = queue;
    this.executor = Executors.newWorkStealingPool();
}

@Override
public void run() {
    try {
        searchDeep();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void searchDeep() throws InterruptedException {
    File[] files = file.listFiles();
    if (files != null) {
        for (File fil : files) {
            if (fil.isDirectory()) {
                executor.submit(new SearchingAlgorithm(fil, this.queue));
            } else {
                this.queue.add(fil);
            }
        }
    }
}
</code>```

}

Printer:

```<code>public class ContainingCheckAlgorithm implements Runnable {

private BlockingQueue<File> queue;
// private ExecutorService executor;
private String keyWord;

public ContainingCheckAlgorithm(BlockingQueue<File> queue, String keyWord) {
    this.queue = queue;
    this.keyWord = keyWord;
    // executor = Executors.newFixedThreadPool(2);
}

@Override
public void run() {
    try {
        printFile();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

private void printFile() throws InterruptedException {
    while (true) {
        File takeFile = queue.take();
        String fileName = takeFile.getAbsolutePath()
                .toLowerCase();
        boolean isContainingKeyWord = fileName.contains(keyWord.toLowerCase());

        if (isContainingKeyWord) {
            System.out.println(takeFile.getAbsolutePath());
        }
    }
}
</code>```

}

Main test class:

```<code>public class MainClass {

public static void main(String[] args) throws InterruptedException {
    ExecutorService executor = Executors.newFixedThreadPool(2);
    BlockingQueue<File> queue = new LinkedBlockingQueue<>();

    File fileName = new File("C:/");

    SearchingAlgorithm sa = new SearchingAlgorithm(fileName, queue);
    executor.submit(sa);

    ContainingCheckAlgorithm ca = new ContainingCheckAlgorithm(queue, "Slipknot");
    executor.submit(ca);

    executor.shutdown();
}
</code>```

}

答:
As u said, I try to do it this way:

Searching algorithm share Thread Pool with others insatances of searchingAlgorithm.

SEARCHING:

```<code>public class SearchingAlgorithm implements Runnable {

private final File file;
private BlockingQueue<File> queue;
private ExecutorService executor;

public SearchingAlgorithm(File fileName, BlockingQueue<File> queue, ExecutorService executor) {
    this.file = fileName;
    this.queue = queue;
    this.executor = executor;
}

@Override
public void run() {
    try {
        searchDeep();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void searchDeep() throws InterruptedException {
    File[] files = file.listFiles();
    if (files != null) {
        for (File fil : files) {
            if (fil.isDirectory()) {
                executor.submit(new SearchingAlgorithm(fil, this.queue, executor));
            } else {
                this.queue.add(fil);
            }
        }
    }
}
</code>```

Now ContainingCheckAlgorith needs to share CountDownLatch with main class, because I need some mechanism to close Thread Pool in main class. Also it uses pool(timeout) as u said, and my threads finally finishing thier job.

CHECKING

```<code>public class ContainingCheckAlgorithm implements Runnable {

private BlockingQueue<File> queue;
private String keyWord;
private CountDownLatch latch;

public ContainingCheckAlgorithm(BlockingQueue<File> queue, String keyWord, CountDownLatch latch) {
    this.queue = queue;
    this.keyWord = keyWord;
    this.latch = latch;
}

@Override
public void run() {
    try {
        printFile();
        latch.countDown();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

private void printFile() throws InterruptedException {
    File takeFile;
    while ((takeFile = queue.poll(1, TimeUnit.SECONDS)) != null) {
        String fileName = takeFile.getName()
                .toLowerCase();
        boolean isContainingKeyWord = fileName.contains(keyWord.toLowerCase());

        if (isContainingKeyWord) {
            System.out.println(takeFile.getAbsolutePath());
        }
    }
}
</code>```

MAIN:

```<code>public class MainClass {

public static void main(String[] args) throws InterruptedException {
    ExecutorService executor = Executors.newCachedThreadPool();
    BlockingQueue<File> queue = new LinkedBlockingQueue<>();
    CountDownLatch latch = new CountDownLatch(1);

    File fileName = new File("C:/");

    SearchingAlgorithm sa = new SearchingAlgorithm(fileName, queue, executor);
    executor.submit(sa);

    ContainingCheckAlgorithm ca = new ContainingCheckAlgorithm(queue, "Slipknot", latch);
    executor.submit(ca);

    latch.await();
    executor.shutdown();
}
</code>```

It looks weird, but I wonder what if:

More than 1 thread would run as ContainingCheckAlgorithm ?

SearchingAlgorithm would searching for an file more than 1 second, and ContainingCheckAlgorithm finish work ? Obviously, I can change timeout to 2 second, and more, but we always try to optimize our programs.

Body:
I was trying to implement some Consumer-Producer problem with BlockingQueue. To do it with some purpose, I decided to write file searching tool.

I decided that search mechanism is working recursively, and every new directory is going to have new thread pool to increase speed of searching.

My problem is, that I have no idea how can I implement mechanism that stops printing threads (consumers) at the end - when searching threads get job done.

I was trying to do that with some ideas like POISON PILLS, but it doesn't works well (threads stops before print any results). Any ideas how can I do that?

Here is some code:

Searching mechanism:

public class SearchingAlgorithm implements Runnable {

private final File file;
private BlockingQueue<File> queue;
private ExecutorService executor;

public SearchingAlgorithm(File fileName, BlockingQueue<File> queue) {
    this.file = fileName;
    this.queue = queue;
    this.executor = Executors.newWorkStealingPool();
}

@Override
public void run() {
    try {
        searchDeep();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void searchDeep() throws InterruptedException {
    File[] files = file.listFiles();
    if (files != null) {
        for (File fil : files) {
            if (fil.isDirectory()) {
                executor.submit(new SearchingAlgorithm(fil, this.queue));
            } else {
                this.queue.add(fil);
            }
        }
    }
}

}

Printer:

public class ContainingCheckAlgorithm implements Runnable {

private BlockingQueue<File> queue;
// private ExecutorService executor;
private String keyWord;

public ContainingCheckAlgorithm(BlockingQueue<File> queue, String keyWord) {
    this.queue = queue;
    this.keyWord = keyWord;
    // executor = Executors.newFixedThreadPool(2);
}

@Override
public void run() {
    try {
        printFile();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

private void printFile() throws InterruptedException {
    while (true) {
        File takeFile = queue.take();
        String fileName = takeFile.getAbsolutePath()
                .toLowerCase();
        boolean isContainingKeyWord = fileName.contains(keyWord.toLowerCase());

        if (isContainingKeyWord) {
            System.out.println(takeFile.getAbsolutePath());
        }
    }
}

}

Main test class:

public class MainClass {

public static void main(String[] args) throws InterruptedException {
    ExecutorService executor = Executors.newFixedThreadPool(2);
    BlockingQueue<File> queue = new LinkedBlockingQueue<>();

    File fileName = new File("C:/");

    SearchingAlgorithm sa = new SearchingAlgorithm(fileName, queue);
    executor.submit(sa);

    ContainingCheckAlgorithm ca = new ContainingCheckAlgorithm(queue, "Slipknot");
    executor.submit(ca);

    executor.shutdown();
}

}

Body:
As u said, I try to do it this way:

Searching algorithm share Thread Pool with others insatances of searchingAlgorithm.

SEARCHING:

public class SearchingAlgorithm implements Runnable {

private final File file;
private BlockingQueue<File> queue;
private ExecutorService executor;

public SearchingAlgorithm(File fileName, BlockingQueue<File> queue, ExecutorService executor) {
    this.file = fileName;
    this.queue = queue;
    this.executor = executor;
}

@Override
public void run() {
    try {
        searchDeep();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void searchDeep() throws InterruptedException {
    File[] files = file.listFiles();
    if (files != null) {
        for (File fil : files) {
            if (fil.isDirectory()) {
                executor.submit(new SearchingAlgorithm(fil, this.queue, executor));
            } else {
                this.queue.add(fil);
            }
        }
    }
}

Now ContainingCheckAlgorith needs to share CountDownLatch with main class, because I need some mechanism to close Thread Pool in main class. Also it uses pool(timeout) as u said, and my threads finally finishing thier job.

CHECKING

public class ContainingCheckAlgorithm implements Runnable {

private BlockingQueue<File> queue;
private String keyWord;
private CountDownLatch latch;

public ContainingCheckAlgorithm(BlockingQueue<File> queue, String keyWord, CountDownLatch latch) {
    this.queue = queue;
    this.keyWord = keyWord;
    this.latch = latch;
}

@Override
public void run() {
    try {
        printFile();
        latch.countDown();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

private void printFile() throws InterruptedException {
    File takeFile;
    while ((takeFile = queue.poll(1, TimeUnit.SECONDS)) != null) {
        String fileName = takeFile.getName()
                .toLowerCase();
        boolean isContainingKeyWord = fileName.contains(keyWord.toLowerCase());

        if (isContainingKeyWord) {
            System.out.println(takeFile.getAbsolutePath());
        }
    }
}

MAIN:

public class MainClass {

public static void main(String[] args) throws InterruptedException {
    ExecutorService executor = Executors.newCachedThreadPool();
    BlockingQueue<File> queue = new LinkedBlockingQueue<>();
    CountDownLatch latch = new CountDownLatch(1);

    File fileName = new File("C:/");

    SearchingAlgorithm sa = new SearchingAlgorithm(fileName, queue, executor);
    executor.submit(sa);

    ContainingCheckAlgorithm ca = new ContainingCheckAlgorithm(queue, "Slipknot", latch);
    executor.submit(ca);

    latch.await();
    executor.shutdown();
}

It looks weird, but I wonder what if:

More than 1 thread would run as ContainingCheckAlgorithm ?

SearchingAlgorithm would searching for an file more than 1 second, and ContainingCheckAlgorithm finish work ? Obviously, I can change timeout to 2 second, and more, but we always try to optimize our programs.


问:
Using 'auth' middleware with subdomains
I am attempting to pass certain functions in my Controller through the auth middleware. However, the routes associated with these functions require a subdomain in the URL to work. The functions seem to work when they are not passed through middleware or when they are passed through custom made middleware, but the 'auth' middleware throws the error:

UrlGenerationException in UrlGenerationException.php line 17:
Missing required parameters for [Route: login] [URI: login].

This is similar to the error that is thrown when I try to run a function without the $account variable in the parameter list (since it is expecting a subdomain with the route).

Upon looking deeper into the Authenticate class that is being called by the 'auth' middleware, I have found that the line that is causing the error is in public function authenticate(array $guards) as shown below.

```<code>protected function authenticate(array $guards)

{
    if (empty($guards)) {
        /** ANYTHING BEFORE THIS RETURN STATEMENT RUNS WITH NO ERRORS **/
        return $this->auth->authenticate();
    }

    foreach ($guards as $guard) {
        if ($this->auth->guard($guard)->check()) {
            return $this->auth->shouldUse($guard);
        }
    }

    throw new AuthenticationException('Unauthenticated.', $guards);
}
</code>```

Here is some of my code for reference (only relevant snippets of the code will be included):

Routes Files

routes\web.php

```<code>Route::group(['domain' => '{account}.'.env('APP_URL')], function () {
  include('appRoutes/bcm.php');
});
</code>```

routes\appRoutes\bcm.php

```<code>/********************************************/
/*********STATIC PAGE ROUTES******************/
/********************************************/

Route::get('/boards-commissions', 'BCM\PagesController@home');

/********************************************/
/*********BOARD ROUTES***********************/
/********************************************/

Route::get('/boards-commissions/boards', 'BCM\BoardsController@index');

Route::get('/boards-commissions/boards/archive/index',
'BCM\BoardsController@archiveIndex');
</code>```

Controllers

app\Http\Controllers\BCM\BoardsController.php

```<code>namespace App\Http\Controllers\BCM;

use Auth;
use Session;
use Validator;

use Illuminate\Http\Request;
use Illuminate\Foundation\Validation\ValidatesRequests;

//Models
use App\Models\BCM\Board;

class BoardsController extends Controller
{
    public function __construct()
    {
        $this->middleware('bcm_app_access');
        $this->middleware('auth', ['except' => array('index', 'show')]);
        $this->middleware('bcm_admin', ['only' => array('edit', 'update',
'create', 'store', 'archive', 'showArchive', 'showArchivedBoard', 'restore')]);
    }

    public function index($account, Request $request) {
        $boards = Board::all();
        $user = $request->user();
        return view('bcm.boards.index')->with('boards', $boards)->with('user', $user);
    }

    public function archiveIndex($account, Request $request) {
        $boards = Board::all();
        $user = $request->user();
        return view('bcm.boards.archiveList')->with('boards', $boards)->with('user', $user);
    }
}
</code>```

It seems to be only the auth middleware that is not working so far. The index function runs just fine (since it is being excluded from the auth middleware in the construct of the controller) even though it is being passed through the bcm_app_access middleware. But archiveIndex will throw the UrlGenerationException error mentioned above when it passes through the auth middleware.

I have a feeling that the $account parameter needs to be added or included somewhere so that the auth middleware knows that it needs to reference it but I'm not sure where to add that in and I don't know what other files are being referenced when $this->auth->authenticate(); is run so I don't know where to add that in. Any thoughts?

答:
In the original question I wanted to know how to get the 'auth' middleware to work with subdomains. I still haven't figured out to do that but I have established a functional work-around by creating a basic custom middleware. The point of the authenticate middleware was to check whether a user of the site was logged in or running as a guest. To mimic this functionality, I created a middleware by running

```<code>php artisan make:middleware SubdomainAuth
</code>```

in command line. Then I configured the auto-generated middleware file to look as follows:

```<code><?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class SubdomainAuth
{
    /**
     * Handle an incoming request to make sure that a valid user is logged in.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        $user = Auth::user();
        if ($user == null) {
          return redirect('/login');
        }
        return $next($request);
    }
}
</code>```

Lastly, I configured my Kernel to recognize the new middleware by adding the line

```<code>'sub_auth' => \App\Http\Middleware\SubdomainAuth::class,
</code>```

to app/Http/Kernel.php. From there I was able to replace the auth middleware in my controllers with the sub_auth middleware that I created. My example from the question above now looks like this:

```<code>namespace App\Http\Controllers\BCM;

use Auth;
use Session;
use Validator;

use Illuminate\Http\Request;
use Illuminate\Foundation\Validation\ValidatesRequests;

//Models
use App\Models\BCM\Board;

class BoardsController extends Controller
{
    public function __construct()
    {
        $this->middleware('bcm_app_access');
        $this->middleware('sub_auth', ['except' => array('index', 'show')]);
        $this->middleware('bcm_admin', ['only' => array('edit', 'update',
'create', 'store', 'archive', 'showArchive', 'showArchivedBoard', 'restore')]);
    }

    public function index($account, Request $request) {
        $boards = Board::all();
        $user = $request->user();
        return view('bcm.boards.index')->with('boards', $boards)->with('user', $user);
    }

    public function archiveIndex($account, Request $request) {
        $boards = Board::all();
        $user = $request->user();
        return view('bcm.boards.archiveList')->with('boards', $boards)->with('user', $user);
    }
}
</code>```

This work-around successfully screens those who are not logged in and redirects them to the login page. However, I am not familiar enough with how the Authenticate middleware works to know if there is any added security that my custom class is missing in the SubdomainAuth class I created.

Title: Using 'auth' middleware with subdomains

Body:
I am attempting to pass certain functions in my Controller through the auth middleware. However, the routes associated with these functions require a subdomain in the URL to work. The functions seem to work when they are not passed through middleware or when they are passed through custom made middleware, but the 'auth' middleware throws the error:

UrlGenerationException in UrlGenerationException.php line 17:
Missing required parameters for [Route: login] [URI: login].

This is similar to the error that is thrown when I try to run a function without the $account variable in the parameter list (since it is expecting a subdomain with the route).

Upon looking deeper into the Authenticate class that is being called by the 'auth' middleware, I have found that the line that is causing the error is in public function authenticate(array $guards) as shown below.

protected function authenticate(array $guards)

{
    if (empty($guards)) {
        /** ANYTHING BEFORE THIS RETURN STATEMENT RUNS WITH NO ERRORS **/
        return $this->auth->authenticate();
    }

    foreach ($guards as $guard) {
        if ($this->auth->guard($guard)->check()) {
            return $this->auth->shouldUse($guard);
        }
    }

    throw new AuthenticationException('Unauthenticated.', $guards);
}

Here is some of my code for reference (only relevant snippets of the code will be included):

Routes Files

routes\web.php

Route::group(['domain' => '{account}.'.env('APP_URL')], function () {
  include('appRoutes/bcm.php');
});

routes\appRoutes\bcm.php

/********************************************/
/*********STATIC PAGE ROUTES******************/
/********************************************/

Route::get('/boards-commissions', 'BCM\PagesController@home');

/********************************************/
/*********BOARD ROUTES***********************/
/********************************************/

Route::get('/boards-commissions/boards', 'BCM\BoardsController@index');

Route::get('/boards-commissions/boards/archive/index',
'BCM\BoardsController@archiveIndex');

Controllers

app\Http\Controllers\BCM\BoardsController.php

namespace App\Http\Controllers\BCM;

use Auth;
use Session;
use Validator;

use Illuminate\Http\Request;
use Illuminate\Foundation\Validation\ValidatesRequests;

//Models
use App\Models\BCM\Board;

class BoardsController extends Controller
{
    public function __construct()
    {
        $this->middleware('bcm_app_access');
        $this->middleware('auth', ['except' => array('index', 'show')]);
        $this->middleware('bcm_admin', ['only' => array('edit', 'update',
'create', 'store', 'archive', 'showArchive', 'showArchivedBoard', 'restore')]);
    }

    public function index($account, Request $request) {
        $boards = Board::all();
        $user = $request->user();
        return view('bcm.boards.index')->with('boards', $boards)->with('user', $user);
    }

    public function archiveIndex($account, Request $request) {
        $boards = Board::all();
        $user = $request->user();
        return view('bcm.boards.archiveList')->with('boards', $boards)->with('user', $user);
    }
}

It seems to be only the auth middleware that is not working so far. The index function runs just fine (since it is being excluded from the auth middleware in the construct of the controller) even though it is being passed through the bcm_app_access middleware. But archiveIndex will throw the UrlGenerationException error mentioned above when it passes through the auth middleware.

I have a feeling that the $account parameter needs to be added or included somewhere so that the auth middleware knows that it needs to reference it but I'm not sure where to add that in and I don't know what other files are being referenced when $this->auth->authenticate(); is run so I don't know where to add that in. Any thoughts?

Body:
In the original question I wanted to know how to get the 'auth' middleware to work with subdomains. I still haven't figured out to do that but I have established a functional work-around by creating a basic custom middleware. The point of the authenticate middleware was to check whether a user of the site was logged in or running as a guest. To mimic this functionality, I created a middleware by running

php artisan make:middleware SubdomainAuth

in command line. Then I configured the auto-generated middleware file to look as follows:

<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class SubdomainAuth
{
    /**
     * Handle an incoming request to make sure that a valid user is logged in.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        $user = Auth::user();
        if ($user == null) {
          return redirect('/login');
        }
        return $next($request);
    }
}

Lastly, I configured my Kernel to recognize the new middleware by adding the line

'sub_auth' => \App\Http\Middleware\SubdomainAuth::class,

to app/Http/Kernel.php. From there I was able to replace the auth middleware in my controllers with the sub_auth middleware that I created. My example from the question above now looks like this:

namespace App\Http\Controllers\BCM;

use Auth;
use Session;
use Validator;

use Illuminate\Http\Request;
use Illuminate\Foundation\Validation\ValidatesRequests;

//Models
use App\Models\BCM\Board;

class BoardsController extends Controller
{
    public function __construct()
    {
        $this->middleware('bcm_app_access');
        $this->middleware('sub_auth', ['except' => array('index', 'show')]);
        $this->middleware('bcm_admin', ['only' => array('edit', 'update',
'create', 'store', 'archive', 'showArchive', 'showArchivedBoard', 'restore')]);
    }

    public function index($account, Request $request) {
        $boards = Board::all();
        $user = $request->user();
        return view('bcm.boards.index')->with('boards', $boards)->with('user', $user);
    }

    public function archiveIndex($account, Request $request) {
        $boards = Board::all();
        $user = $request->user();
        return view('bcm.boards.archiveList')->with('boards', $boards)->with('user', $user);
    }
}

This work-around successfully screens those who are not logged in and redirects them to the login page. However, I am not familiar enough with how the Authenticate middleware works to know if there is any added security that my custom class is missing in the SubdomainAuth class I created.


问:
Aggregator transformation in Informatica
Is it compulsory to select group-by while performing count operation in the aggregator transformation in Informatica</p>

答:
In order to perform a count, you have to specify atleast one column in group by to AGGREGATOR transformation to let it know that it has to perform grouping on that column.

Even if you don't provide GROUP BY also, the mapping will not fail, but you won't get the expected result.